diff --git a/.github/workflows/affinity-corpus.yml b/.github/workflows/affinity-corpus.yml index 948b87be97..b3e0178f56 100644 --- a/.github/workflows/affinity-corpus.yml +++ b/.github/workflows/affinity-corpus.yml @@ -24,9 +24,13 @@ jobs: CARGO_PROFILE_DEV_DEBUG: "0" CARGO_PROFILE_TEST_DEBUG: "0" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Rust - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable + uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: "1.95" - name: Fetch pinned and checksum-verified corpus diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index da85536c43..0a91cc0505 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -29,6 +29,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a57e0e6b0..fd836de6c7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,6 +3,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "52 2 * * *" push: branches: [release] workflow_dispatch: @@ -32,6 +36,10 @@ jobs: permissions: contents: read steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Git dependencies come from storytold run: | @@ -73,6 +81,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: vectorcraft app-title: VectorCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 diff --git a/ASSETS.md b/ASSETS.md index 17ab680ff4..5658882d48 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -159,6 +159,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-grad-conic.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-grad-diamond.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-freeform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-linear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-radial.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -265,6 +267,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/flip-vertical-2.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/folder-open.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/frame.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | +| `assets/icons/graduation-cap.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | Learn panel, Explore tutorials button | | `assets/icons/grid-3x3.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/group.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | | `assets/icons/hand.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | | diff --git a/Cargo.lock b/Cargo.lock index 064b89e9e8..02e109b6b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -967,6 +967,17 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-affinity" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=228f6d0c50f1fdee4c5124603602993fc79d4c9d#228f6d0c50f1fdee4c5124603602993fc79d4c9d" +dependencies = [ + "crc32fast", + "flate2", + "image", + "ruzstd", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -4879,9 +4890,6 @@ name = "ruzstd" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" -dependencies = [ - "twox-hash", -] [[package]] name = "ryu" @@ -6066,12 +6074,6 @@ dependencies = [ "core_maths", ] -[[package]] -name = "twox-hash" -version = "2.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" - [[package]] name = "type-map" version = "0.5.1" @@ -6313,7 +6315,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.21.0" +version = "0.24.1" dependencies = [ "arboard", "block2 0.6.2", @@ -6353,31 +6355,31 @@ dependencies = [ "winit", "winresource", "winsafe", + "wl-clipboard-rs", "x11rb", "zbus", ] [[package]] name = "vectorcraft-affinity" -version = "0.21.0" +version = "0.24.1" dependencies = [ + "craft-affinity", "crc32fast", - "flate2", "image", "proptest", - "ruzstd", ] [[package]] name = "vectorcraft-apischema" -version = "0.21.0" +version = "0.24.1" dependencies = [ "serde_json", ] [[package]] name = "vectorcraft-brush" -version = "0.21.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "serde", @@ -6389,7 +6391,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.21.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6405,7 +6407,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.21.0" +version = "0.24.1" dependencies = [ "log", "objc2-core-foundation", @@ -6428,7 +6430,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.21.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6440,7 +6442,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.21.0" +version = "0.24.1" dependencies = [ "chrono", "hayro-ccitt", @@ -6459,7 +6461,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.21.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6477,7 +6479,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.21.0" +version = "0.24.1" dependencies = [ "cfb", "chrono", @@ -6498,6 +6500,7 @@ dependencies = [ "roxmltree 0.21.2", "rustix 1.1.6", "ruzstd", + "same-file", "serde", "serde_json", "skrifa 0.47.0", @@ -6530,7 +6533,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-pdf", "encoding_rs", @@ -6558,7 +6561,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-vectorcraft-format", "flate2", @@ -6574,7 +6577,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.21.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6586,16 +6589,17 @@ dependencies = [ [[package]] name = "vectorcraft-js" -version = "0.21.0" +version = "0.24.1" dependencies = [ "chrono", + "getrandom 0.4.3", "proptest", - "unicode-general-category", + "unicode-properties", ] [[package]] name = "vectorcraft-mcp" -version = "0.21.0" +version = "0.24.1" dependencies = [ "image", "log", @@ -6614,7 +6618,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.21.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6628,7 +6632,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.21.0" +version = "0.24.1" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6640,7 +6644,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.21.0" +version = "0.24.1" dependencies = [ "aes", "chrono", @@ -6674,7 +6678,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-vectorcraft-format", "image", @@ -6693,7 +6697,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.21.0" +version = "0.24.1" dependencies = [ "flate2", "gif 0.14.2", @@ -6723,14 +6727,15 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.21.0" +version = "0.24.1" dependencies = [ "proptest", + "unicode-properties", ] [[package]] name = "vectorcraft-svg" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-docpath", "flate2", @@ -6757,7 +6762,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.21.0" +version = "0.24.1" dependencies = [ "fax", "image", @@ -6775,7 +6780,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.21.0" +version = "0.24.1" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6796,7 +6801,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.21.0" +version = "0.24.1" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6804,7 +6809,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.21.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6821,7 +6826,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.21.0" +version = "0.24.1" dependencies = [ "image", "kurbo 0.13.1", @@ -6833,7 +6838,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.21.0" +version = "0.24.1" dependencies = [ "bytemuck", "craft-keymap", @@ -6871,7 +6876,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.21.0" +version = "0.24.1" dependencies = [ "craft-web-api", "eframe", @@ -8003,7 +8008,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.21.0" +version = "0.24.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 6d47f057c0..29f43866c2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.21.0" +version = "0.24.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -23,6 +23,8 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63 # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # craft-update: app-specific pretend versions apply to startup and manual checks. +# Native Affinity documents (craft-libs#914). +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } diff --git a/README.md b/README.md index dc7a1cfa5f..7e49943a31 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu (92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday vector illustration is close to usable: drawing and path tools, Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and -files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package). +files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package). Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master diff --git a/ROADMAP.md b/ROADMAP.md index 327036c371..87aaed1109 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -122,10 +122,12 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. +- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 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`). +- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). @@ -137,6 +139,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. +- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets. +- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets. - 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. - 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index fab468c391..57ab103590 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -486,7 +486,12 @@ fn info(args: &[String]) -> Result<(), String> { let base = h.call("engine.execute", json!({"command": "file.info", "params": {}}))?; let doc = h.session.doc().map_err(|e| e.to_string())?.doc.clone(); let mut kinds: std::collections::BTreeMap<&'static str, usize> = Default::default(); - doc.walk(|n| *kinds.entry(n.kind_label()).or_default() += 1); + // Ruler guides are not counted among the objects. + doc.walk(|n| { + if !n.is_ruler_guide() { + *kinds.entry(n.kind_label()).or_default() += 1; + } + }); let fonts = h.call("engine.execute", json!({"command": "text.fonts", "params": {}})).unwrap_or(Value::Null); let artboards: Vec = doc.artboards.iter().map(|a| json!({"name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()]})).collect(); diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 5bdd2bf631..0b1c560901 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -3,8 +3,6 @@ use std::process::{Command, Stdio}; use serde_json::{Value, json}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - /// Returns the path of `name` in `vectorcraft-cli-test-` in the temp folder. The first call removes /// that folder and creates it again empty. fn tmp(name: &str) -> std::path::PathBuf { @@ -27,7 +25,12 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) { std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap(); let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id()))); let run = |extra: &[&str]| { - Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap() + Command::new(crate::bin()) + .env("VECTORCRAFT_CONFIG_DIR", &config) + .args(["run", "--commands", steps.to_str().unwrap()]) + .args(extra) + .output() + .unwrap() }; let out = run(&[]); assert!(!out.status.success()); @@ -38,7 +41,7 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) { let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id()))); let mcp_install = |extra: &[&str]| -> Value { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .env("VECTORCRAFT_CONFIG_DIR", &mcp_config) .args(["mcp", "--headless"]) .args(extra) @@ -77,22 +80,23 @@ fn plugin_grants_need_the_start_up_flag() { approval_param_needs_the_start_up_flag("grant", json!(["doc.read"])); approval_param_needs_the_start_up_flag("allowHeavy", json!(true)); - let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap(); assert!(!out.status.success()); assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server")); let root = std::env::temp_dir(); for flag in ["--automation-read-root", "--automation-write-root"] { - let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); + let out = + Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); assert!(!out.status.success(), "{flag}"); assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}"); } - let usage = Command::new(BIN).arg("help").output().unwrap(); + let usage = Command::new(crate::bin()).arg("help").output().unwrap(); assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect")); } #[test] fn commands_prints_catalogue() { - let out = Command::new(BIN).arg("commands").output().unwrap(); + let out = Command::new(crate::bin()).arg("commands").output().unwrap(); assert!(out.status.success()); let v: Value = serde_json::from_slice(&out.stdout).unwrap(); let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect(); @@ -104,7 +108,7 @@ fn run_batch_exports() { let svg = tmp("batch.svg"); let png = tmp("batch.png"); let dc = tmp("batch.vectorcraft"); - let out = Command::new(BIN) + let out = Command::new(crate::bin()) .args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#]) .args(["--cmd", "shape.ellipse", "--params", r#"{"x":10,"y":10,"width":80,"height":60}"#]) .args(["--cmd", "paint.setFill", "--params", r##"{"color":"#3366ff"}"##]) @@ -121,7 +125,7 @@ fn run_batch_exports() { assert_eq!(u32::from_be_bytes(png_bytes[16..20].try_into().unwrap()), 400); // Re-open the native file and inspect. - let out = Command::new(BIN).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); let last: Value = serde_json::from_str(String::from_utf8(out.stdout).unwrap().lines().last().unwrap()).unwrap(); assert_eq!(last["result"]["artboards"][0]["width"], 200.0); @@ -137,7 +141,7 @@ fn scale_sizes_raster_exports_only() { let svg = svg.to_str().unwrap(); let (plain, scaled, png) = (tmp("plain.dxf"), tmp("scaled.dxf"), tmp("scaled.png")); let ok = |args: &[&str]| { - let out = Command::new(BIN).args(args).output().unwrap(); + let out = Command::new(crate::bin()).args(args).output().unwrap(); assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); }; ok(&["convert", svg, plain.to_str().unwrap()]); @@ -151,11 +155,11 @@ fn scale_sizes_raster_exports_only() { #[test] fn run_reports_errors() { - let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--cmd", "nope.nothing"]).output().unwrap(); assert!(!out.status.success()); let stderr = String::from_utf8_lossy(&out.stderr).to_string(); assert!(stderr.contains("step 0 (nope.nothing)"), "{stderr}"); - let out = Command::new(BIN).args(["run", "--params", "{}"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--params", "{}"]).output().unwrap(); assert!(!out.status.success()); } @@ -184,7 +188,7 @@ fn run_reads_steps_from_a_commands_file() { {"id": "object.setProps", "params": {"id": "$2.ids.0", "name": "barcode"}}, ]); std::fs::write(&steps, serde_json::to_string_pretty(&file).unwrap()).unwrap(); - let out = Command::new(BIN) + let out = Command::new(crate::bin()) .args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#, "--commands", steps.to_str().unwrap()]) .args(["--cmd", "document.node", "--params", r#"{"id":"$2.ids.0"}"#, "--export", svg.to_str().unwrap()]) .output() @@ -204,7 +208,7 @@ fn run_reads_steps_from_a_commands_file() { #[test] fn run_reads_json_lines_from_standard_input() { let svg = tmp("stdin.svg"); - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["run", "--commands", "-", "--export", svg.to_str().unwrap()]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -227,7 +231,7 @@ fn run_reads_json_lines_from_standard_input() { #[test] fn run_refuses_malformed_commands_naming_the_step() { let fails = |args: &[&str]| { - let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap(); assert!(!out.status.success(), "{args:?}"); (String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len()) }; @@ -275,11 +279,11 @@ fn run_refuses_malformed_commands_naming_the_step() { /// `--help` and `-h` right after a subcommand print the usage that `vectorcraft-cli help` prints. #[test] fn help_after_a_subcommand_prints_the_usage() { - let usage = Command::new(BIN).arg("help").output().unwrap(); + let usage = Command::new(crate::bin()).arg("help").output().unwrap(); assert!(usage.status.success() && String::from_utf8_lossy(&usage.stdout).contains("USAGE:")); for sub in ["mcp", "run", "commands", "convert", "info", "bench", "perf"] { for flag in ["--help", "-h"] { - let out = Command::new(BIN).args([sub, flag]).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args([sub, flag]).stdin(Stdio::null()).output().unwrap(); assert!(out.status.success(), "{sub} {flag}: {}", String::from_utf8_lossy(&out.stderr)); assert!(out.stdout == usage.stdout, "{sub} {flag}: {}", String::from_utf8_lossy(&out.stdout)); } @@ -290,7 +294,7 @@ fn help_after_a_subcommand_prints_the_usage() { /// with them. #[test] fn help_later_in_the_line_prints_the_usage() { - let usage = Command::new(BIN).arg("help").output().unwrap(); + let usage = Command::new(crate::bin()).arg("help").output().unwrap(); let mut wrong = vec![]; for args in [ &["mcp", "--headless", "--help"][..], @@ -311,7 +315,7 @@ fn help_later_in_the_line_prints_the_usage() { &["perf", "--paths", "many", "-h"], &["convert", "--decimals", "many", "--help"], ] { - let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap(); if !out.status.success() || out.stdout != usage.stdout { wrong.push(format!("{args:?}: {}{}", String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout))); } @@ -322,17 +326,18 @@ fn help_later_in_the_line_prints_the_usage() { /// Further along the line, `-h` is the value of the option before it. #[test] fn help_as_an_option_value_goes_to_the_option() { - let out = Command::new(BIN).args(["run", "--cmd", "-h"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--cmd", "-h"]).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains("vectorcraft-cli: step 0 (-h):") && out.stdout.is_empty(), "{err}"); - let out = Command::new(BIN).args(["convert", "in.svg", "--range", "-h"]).output().unwrap(); + let out = Command::new(crate::bin()).args(["convert", "in.svg", "--range", "-h"]).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains("convert needs IN and OUT") && out.stdout.is_empty(), "{err}"); } #[test] fn mcp_headless_over_stdio() { - let mut child = Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); + let mut child = + Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); { let mut stdin = child.stdin.take().unwrap(); for m in [ @@ -359,13 +364,13 @@ fn mcp_headless_over_stdio() { /// plug-ins. #[test] fn safe_mode_mcp_does_not_connect_to_a_running_app() { - let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap(); + let out = Command::new(crate::bin()).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}"); // Something listening on the default address, as a running app does; a running app or another // program already holding it serves as well. let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR); - let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}"); } @@ -402,7 +407,7 @@ fn mcp_automation_roots_take_several_folders() { } let dir = |d: &str| base.join(d).to_string_lossy().into_owned(); let file = |d: &str, f: &str| base.join(d).join(f).to_string_lossy().into_owned(); - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-read-root={}", dir("in2"))]) .args(["--automation-write-root", &dir("out"), "--automation-write-root", &dir("out2")]) .stdin(Stdio::piped()) @@ -457,7 +462,7 @@ fn automation_roots(base: &std::path::Path) { } let dir = |d: &str| base.join(d).to_string_lossy().into_owned(); let fails = |args: &[&str], why: &str| { - let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success() && err.contains(why), "{args:?}: {err}"); }; @@ -469,7 +474,7 @@ fn automation_roots(base: &std::path::Path) { "a running app enforces its own roots: start it with `vectorcraft --control ", ); - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-write-root={}", dir("out"))]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -530,7 +535,7 @@ fn automation_roots(base: &std::path::Path) { fn mcp_protocol_over_stdio() { use std::io::{BufRead, BufReader}; let mut child = - Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); let mut stdin = child.stdin.take().unwrap(); let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); let mut notes = vec![]; @@ -711,7 +716,7 @@ fn run_command(id: u64, command: &str, params: Value) -> Value { #[test] fn closed_stdout_ends_quietly() { use std::io::Read; - let mut child = Command::new(BIN).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut child = Command::new(crate::bin()).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); let mut first = [0u8; 16]; child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap(); drop(child.stdout.take()); @@ -728,13 +733,13 @@ fn run_with_a_closed_stdout_ends_quietly_and_finishes_the_batch() { let _ = std::fs::remove_file(&svg); let rect = r#"{"x":1,"y":1,"width":5,"height":5}"#; let args = ["run", "--cmd", "document.json", "--cmd", "shape.rectangle", "--params", rect, "--export", svg.to_str().unwrap()]; - let mut child = Command::new(BIN).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut child = Command::new(crate::bin()).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); drop(child.stdout.take()); let out = child.wait_with_output().unwrap(); let err = String::from_utf8_lossy(&out.stderr); assert!(out.status.success() && err.is_empty(), "{:?}: {err}", out.status); assert!(svg.is_file(), "the export after the closed reader still ran"); - let out = Command::new(BIN).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap(); + let out = Command::new(crate::bin()).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap(); assert!(!out.status.success()); } @@ -749,7 +754,7 @@ fn config_dir(name: &str) -> std::path::PathBuf { /// One `vectorcraft-cli run` with `steps` ((command, params)) against the settings folder `config`; /// the result of each step. fn run_in(config: &std::path::Path, steps: &[(&str, Value)]) -> Vec { - let mut cmd = Command::new(BIN); + let mut cmd = Command::new(crate::bin()); cmd.arg("run").env("VECTORCRAFT_CONFIG_DIR", config).env_remove("VECTORCRAFT_NO_PREFS"); for (id, params) in steps { cmd.args(["--cmd", id, "--params", ¶ms.to_string()]); @@ -820,7 +825,7 @@ fn saved_pdf_presets_and_loaded_profiles_survive_a_restart() { #[test] fn runs_without_preferences_remember_nothing() { let config = config_dir("noprefs"); - let out = Command::new(BIN) + let out = Command::new(crate::bin()) .args(["run", "--cmd", "pdf.preset.save", "--params", r#"{"name":"Press"}"#]) .env("VECTORCRAFT_CONFIG_DIR", &config) .env("VECTORCRAFT_NO_PREFS", "1") diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index c60357b5f8..71044be4a5 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -4,8 +4,6 @@ use std::process::Command; use serde_json::Value; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - /// Returns the path of `name` in `vectorcraft-cli-fileio-` in the temp folder. The first call /// removes that folder and creates it again empty. fn tmp(name: &str) -> String { @@ -20,7 +18,7 @@ fn tmp(name: &str) -> String { } fn ok(args: &[&str]) -> String { - let out = Command::new(BIN).args(args).output().unwrap(); + let out = Command::new(crate::bin()).args(args).output().unwrap(); assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); String::from_utf8(out.stdout).unwrap() } @@ -130,7 +128,7 @@ fn raster_exports_use_document_resolution_unless_overridden() { 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(); + let out = Command::new(crate::bin()).args(&args).output().unwrap(); assert!(!out.status.success(), "{args:?}"); assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}"); } @@ -228,7 +226,7 @@ fn convert_writes_legacy_ai_with_its_options() { assert!(r["warnings"].to_string().contains("hidden objects are left out"), "{r}"); assert!(std::fs::read(&one).unwrap().starts_with(b"%!PS-Adobe-3.0")); // A value the engine doesn't take is an error. - let bad = Command::new(BIN).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap(); + let bad = Command::new(crate::bin()).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap(); assert!(!bad.status.success()); assert!(String::from_utf8_lossy(&bad.stderr).contains("hiddenObjects"), "{}", String::from_utf8_lossy(&bad.stderr)); } @@ -253,7 +251,7 @@ fn convert_and_run_write_ait_templates() { assert_eq!(info(ait)["artboards"].as_array().unwrap().len(), 2, "{ait}"); } // A template holds every artboard: one can't be picked. - let one = Command::new(BIN).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap(); + let one = Command::new(crate::bin()).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap(); assert!(!one.status.success()); assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr)); } diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs index 07e5a3a70d..d898dda20a 100644 --- a/apps/vectorcraft-cli/tests/it/main.rs +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -6,3 +6,11 @@ mod cli; mod fileio; mod mcp_e2e; mod script; + +/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner. +fn bin() -> std::path::PathBuf { + std::env::var_os("NEXTEST_BIN_EXE_vectorcraft_cli") + .or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft-cli")) + .map(std::path::PathBuf::from) + .unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft-cli").into()) +} diff --git a/apps/vectorcraft-cli/tests/it/mcp_e2e.rs b/apps/vectorcraft-cli/tests/it/mcp_e2e.rs index 5a353070ae..4931602ec8 100644 --- a/apps/vectorcraft-cli/tests/it/mcp_e2e.rs +++ b/apps/vectorcraft-cli/tests/it/mcp_e2e.rs @@ -6,8 +6,6 @@ use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use serde_json::{Value, json}; use vectorcraft_testkit::raster::Image; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - struct Mcp { child: Child, stdin: Option, @@ -17,7 +15,7 @@ struct Mcp { impl Mcp { fn spawn() -> Self { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(["mcp", "--headless"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/apps/vectorcraft-cli/tests/it/script.rs b/apps/vectorcraft-cli/tests/it/script.rs index d68716f7b3..3652e585d0 100644 --- a/apps/vectorcraft-cli/tests/it/script.rs +++ b/apps/vectorcraft-cli/tests/it/script.rs @@ -2,11 +2,9 @@ use std::process::Command; use serde_json::{Value, json}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli"); - /// `run` with `script.run` after `file.new`, with `params`. fn run_script(params: &Value) -> std::process::Output { - Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap() + Command::new(crate::bin()).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap() } /// `run` runs a script headless: the reply holds the report, with what the script logged and the diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index f7dd201af2..3808c281f9 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -7,7 +7,7 @@ //! Differences from the desktop app: //! - no TCP control server (browsers can't listen on sockets); //! - File → Open uses the browser file picker; bytes arrive asynchronously through -//! `Services::inbox`; +//! `Services::picked_inbox`; //! - Save / Export trigger a browser download; //! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox; //! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index b4ca434d90..2de7f3b481 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -17,7 +17,7 @@ use vectorcraft_ui_egui::i18n; use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox}; use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; use vectorcraft_ui_egui::stylus::StylusFeed; -use vectorcraft_ui_egui::{Services, VectorcraftApp}; +use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp}; use wasm_bindgen::JsCast as _; use crate::locks::WebLocks; @@ -25,6 +25,18 @@ use crate::pencil::SharedPointers; pub(crate) type Inbox = Arc)>>>; +/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and +/// `page_inbox`). +#[derive(Clone, Default)] +struct OpenInboxes { + /// Dropped on the page. + dropped: Inbox, + /// The open picker's answers. + picked: PickedInbox, + /// Handed over by the page's script (`window.vectorcraft.openFile`). + page: Inbox, +} + /// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and /// whether Shift was held: where dropped files land. type DragPos = Rc>>; @@ -48,7 +60,7 @@ const MAX_RESTARTS: u32 = 3; #[derive(Clone)] struct Host { runner: eframe::WebRunner, - inbox: Inbox, + inbox: OpenInboxes, place_inbox: PlaceInbox, script_inbox: ScriptInbox, drag: DragPos, @@ -77,7 +89,7 @@ pub fn start() { crate::fonts::load_startup_fonts().await; let host = Host { runner: eframe::WebRunner::new(), - inbox: Arc::default(), + inbox: OpenInboxes::default(), place_inbox: Arc::default(), script_inbox: Arc::default(), drag: DragPos::default(), @@ -132,13 +144,13 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option { // `window.vectorcraft`: the page's control channel (crate::api). let (control_tx, control_rx) = std::sync::mpsc::channel(); - crate::api::connect(Some(control_tx), host.inbox.clone(), ctx.clone()); + crate::api::connect(Some(control_tx), host.inbox.page.clone(), ctx.clone()); if let Err(e) = crate::api::install() { log::error!("vectorcraft-web: couldn't install window.vectorcraft: {}", js_err(e)); } @@ -409,7 +421,7 @@ impl eframe::App for WebShell { for f in dropped { let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); let target = app.drop_target(&name, pos, shift); - let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone()); + let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone()); wasm_bindgen_futures::spawn_local(async move { match f.bytes_async().await { Ok(bytes) => { @@ -432,14 +444,14 @@ impl eframe::App for WebShell { } fn services( - inbox: Inbox, + inbox: OpenInboxes, place_inbox: PlaceInbox, script_inbox: ScriptInbox, ctx: egui::Context, locks: Option, stylus: StylusFeed, ) -> Services { - let open_inbox = inbox.clone(); + let open_inbox = inbox.picked.clone(); let picked = place_inbox.clone(); let place_ctx = ctx.clone(); let screen_color = eye_dropper(ctx.clone()); @@ -488,11 +500,12 @@ fn services( let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| { d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) }); - let Some(file) = dialog.pick_file().await else { - return; + // A canceled pick answers `None`. + let answer = match dialog.pick_file().await { + Some(file) => Some((file.file_name(), file.read().await)), + None => None, }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes)); + inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer); ctx.request_repaint(); }); })), @@ -500,7 +513,9 @@ fn services( screen_color, // A download that couldn't be started fails the save or export it is for (#1693). download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))), - inbox: Some(inbox), + inbox: Some(inbox.dropped), + picked_inbox: Some(inbox.picked), + page_inbox: Some(inbox.page), recovery_store: Some(Arc::new(BrowserStore { locks })), // File → Print: the browser's print dialog. print: Some(Box::new(BrowserPrint)), diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index dfd9b16719..047c4530c7 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -113,6 +113,10 @@ wayland-backend = { version = "0.3", features = ["client_system"] } # exactly: review the diff before bumping. [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies] zbus = "=5.19.0" +# Tells whether arboard reads through the compositor's data-control protocol or through X11, the +# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through +# arboard. +wl-clipboard-rs = "0.9" [build-dependencies] # Icon + VERSIONINFO for vectorcraft.exe; build.rs only uses it when targeting Windows. diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index fa0f0dca29..0391b7534b 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -9,6 +9,7 @@ use super::{App, VectorcraftApp, file_access, window}; #[cfg(target_os = "macos")] use super::{mac_menu, mac_window, open_documents}; use vectorcraft_ui_egui::dialogs::safe_mode; +use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage}; /// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating /// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel @@ -34,12 +35,16 @@ impl eframe::App for App { // control channel asks for, and the frames carrying input it injected, to the automation roots // (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process. fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + let _timed = BEACON.enter_timed(Stage::Logic); file_access::unconfined(|| self.logic_frame(ctx, frame)); self.app.finish_ime_logic(ctx); + BEACON.enter(Stage::Idle); } /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + let _timed = BEACON.enter_timed(Stage::Input); + self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, // restore, …): take it off again before the frame is laid out (#1758). if let Some(window_frame) = self.window_frame.as_mut() { @@ -60,9 +65,10 @@ impl eframe::App for App { // that no mouse button is down. #[cfg(target_os = "macos")] self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0); + BEACON.enter(Stage::Idle); } - #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + let _timed = BEACON.enter_timed(Stage::Interface); #[cfg(target_os = "macos")] { let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT; @@ -89,8 +95,13 @@ impl eframe::App for App { if !self.app.file_dialog_open() && self.app.take_ime_discard() { discard_marked_text(); } + self.end_frame(ui.ctx(), frame); } fn on_exit(&mut self) { + // The window is closing: saving and teardown are not timed for the hang report, and a report + // of a stall the interface came back from is removed. + let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled()); + super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON); file_access::unconfined(|| save_prefs(&self.app)); // A ready update installs once the process has exited. The macOS exit below skips // dropping the app, so the helper is started here. @@ -102,6 +113,35 @@ impl eframe::App for App { } impl App { + /// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a + /// focused, shown window whose windows had input waits for the renderer and the next frame, + /// which the input asks for at once; any other frame leaves the interface thread idle + /// (`hang_watch`). + fn end_frame(&mut self, ctx: &egui::Context, frame: &eframe::Frame) { + // A pass egui discards and runs again is not the frame's end: the pass after it is. + if ctx.will_discard() { + return; + } + if let Some(start) = self.frame_start.take() { + let work_ms = start.elapsed().as_secs_f32() * 1000.0; + let previous_total_ms = frame.info().cpu_usage.map(|s| s * 1000.0); + BEACON.frame(FrameTime { work_ms, previous_total_ms }, self.app.session.documents().len()); + } + // Hide on macOS hides the window at once, before the window reports losing focus. + let main_shown = ctx.input(|i| i.focused && i.viewport().minimized != Some(true)) + && self.winit_window.as_ref().is_none_or(|w| w.is_visible() != Some(false)); + // A floating panel or document window with the focus counts as well, with the commands it + // was sent after its pass, and those its pass sent (`hang_beacon::watch_input`). + let shown = ctx.input(|i| hang_beacon::shown_window(main_shown, &i.raw.viewports)); + let handed_off = BEACON.take_handed_off(); + let input = BEACON.take_input(); + let stage = match shown { + Some(id) => ctx.viewport_for(id, |vp| hang_beacon::after_frame(input && !handed_off.contains(&id), true, &vp.commands)), + None => hang_beacon::after_frame(input, false, &[]), + }; + BEACON.enter(stage); + } + fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) { diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index b9be306898..c5ef4d5579 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -12,7 +12,9 @@ //! copied), falling back to X11 where the compositor lacks the protocol, and where there is no //! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection, //! text only. A clipboard that can't be opened is tried again after a wait that grows to a -//! minute, not each time Paste asks. +//! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app +//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at +//! once; a paste then waits for that read's answer off the UI thread. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, //! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). @@ -332,11 +334,290 @@ mod win { } } +/// Reads made on a worker thread and waited for a bounded time: a clipboard owner that never sends +/// its data holds the worker, not the caller. On Linux and the BSDs arboard's reads go through one, +/// and on Linux the Wayland core protocol's reads through another. Built everywhere so it is +/// tested everywhere. +#[cfg_attr( + not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")), + allow(dead_code) +)] +mod loads { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, PoisonError, Weak, mpsc}; + use std::time::{Duration, Instant}; + + /// The longest a read waits for the clipboard's owner to send its data. + pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2); + /// What a read says once its worker has stopped. + pub(super) const GONE: &str = "the clipboard's reader stopped"; + + /// Requests of type `R` answered with `A` on a worker thread. + pub(super) struct Loads { + /// The worker's requests; the worker stops once this is dropped. + line: Arc>, + /// Disconnected once the worker has let go of what its `load` holds. + done: mpsc::Receiver<()>, + /// How long after it was sent dropping `Loads` waits for an unanswered read to end. + finish: Duration, + } + + /// Where requests go to a [`Loads`] worker. + struct Line { + /// Each request goes with the channel its answer is sent on. + requests: mpsc::Sender<(R, mpsc::Sender)>, + /// Requests sent and not answered yet, counted down by the worker: while one is open, + /// reads don't queue behind it. + open: Arc, + /// When the last request was sent, and whether the `Loads` has stopped taking requests: + /// requests are sent with this locked. + sent: Mutex, + } + + #[derive(Default)] + struct Sent { + at: Option, + closed: bool, + } + + impl Line { + /// A line whose worker has stopped. + fn dead() -> Arc { + Arc::new(Self { requests: mpsc::channel().0, open: Arc::default(), sent: Mutex::default() }) + } + + /// `request` sent to the worker ([`Loads::ask`]). + fn ask(&self, request: R) -> Result, String> { + let mut sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner); + if sent.closed { + return Err(GONE.into()); + } + if self.open.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst).is_err() { + return Err("the clipboard's owner hasn't answered an earlier read".into()); + } + let (reply, answer) = mpsc::channel(); + sent.at = Some(Instant::now()); + if self.requests.send((request, reply)).is_err() { + self.open.fetch_sub(1, Ordering::SeqCst); + return Err(GONE.into()); + } + Ok(answer) + } + + /// Stops taking requests → when the one still unanswered was sent. + fn close(&self) -> Option { + let mut sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner); + sent.closed = true; + sent.at.filter(|_| self.open.load(Ordering::SeqCst) > 0) + } + } + + /// Sends requests to a [`Loads`] worker from another thread while the `Loads` is open. + pub(super) struct Asker(Weak>); + + impl Asker { + /// [`Loads::ask`]; Err also once the `Loads` has been dropped. + pub(super) fn ask(&self, request: R) -> Result, String> { + self.0.upgrade().ok_or_else(|| GONE.to_string())?.ask(request) + } + } + + /// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read + /// `pending` was sent (at once if that time has passed), and with no read unanswered + /// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once). + fn stop_by(pending: Option, now: Instant, finish: Duration) -> Instant { + pending.map_or(now + LOAD_WAIT, |sent| sent + finish) + } + + impl Loads { + /// A worker thread named `name` that answers each request with `load`; dropping the result + /// waits up to `finish` after an unanswered read was sent for that read to end. None when the + /// worker can't start. + pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option { + let (requests, asked) = mpsc::channel::<(R, mpsc::Sender)>(); + let (alive, done) = mpsc::channel::<()>(); + let open = Arc::new(AtomicUsize::new(0)); + let answered = open.clone(); + let work = move || { + while let Ok((request, reply)) = asked.recv() { + let answer = load(request); + // Counted down before the answer goes, so its reader can ask again at once. + answered.fetch_sub(1, Ordering::SeqCst); + // A read that timed out no longer waits: its late answer is dropped. + let _ = reply.send(answer); + } + // `load` and the clipboard it holds go first: dropping `Loads` waits for `alive`. + drop(load); + drop(alive); + }; + std::thread::Builder::new().name(name.into()).spawn(work).ok()?; + Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish }) + } + + /// `request` sent to the worker; its answer comes on the channel returned, for + /// [`wait_for_answer`] here or on another thread. Err when an earlier request is still + /// unanswered or the worker has stopped. + pub(super) fn ask(&mut self, request: R) -> Result, String> { + self.line.ask(request) + } + + /// Whether a request sent is still unanswered. + pub(super) fn waiting(&self) -> bool { + self.line.open.load(Ordering::SeqCst) > 0 + } + + /// A handle that sends requests from another thread until this is dropped. + pub(super) fn asker(&self) -> Asker { + Asker(Arc::downgrade(&self.line)) + } + + /// The answer to `request`, or why there is none, after `wait` at most. + #[cfg(test)] + pub(super) fn get(&mut self, request: R, wait: Duration) -> Result { + wait_for_answer(&self.ask(request)?, wait) + } + } + + /// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most. + pub(super) fn wait_for_answer(answer: &mpsc::Receiver, wait: Duration) -> Result { + match answer.recv_timeout(wait) { + Ok(answer) => Ok(answer), + Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")), + Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()), + } + } + + impl Drop for Loads { + /// Stops the worker and waits until it has let go of what its `load` holds, until + /// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to + /// the clipboard manager, and the app's own handle must be that one. + fn drop(&mut self) { + // No `Asker` sends after this, and one that holds the line lets go once it has sent. + let pending = self.line.close(); + drop(std::mem::replace(&mut self.line, Line::dead())); + let end = stop_by(pending, Instant::now(), self.finish); + // Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`. + let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now())); + } + } + + #[cfg(test)] + mod tests { + use std::sync::Arc; + + use super::*; + + #[test] + fn a_read_that_answers_in_time_gives_the_text() { + let mut loads = Loads::spawn("test", Duration::ZERO, |()| "".to_string()).unwrap(); + assert_eq!(loads.get((), Duration::from_secs(5)), Ok("".to_string())); + assert_eq!(loads.get((), Duration::from_secs(5)), Ok("".to_string())); + } + + #[test] + fn an_owner_that_never_answers_holds_the_worker_not_the_caller() { + let (release, gate) = mpsc::channel::<()>(); + let mut calls = 0; + let mut loads = Loads::spawn("test", Duration::ZERO, move |()| { + calls += 1; + if calls == 1 { + // The first owner sends nothing until released. + let _ = gate.recv(); + return "stale".to_string(); + } + "fresh".to_string() + }) + .unwrap(); + assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out"); + // While it is unanswered, a read doesn't queue behind it or wait at all. + assert!(loads.get((), Duration::from_secs(600)).is_err()); + release.send(()).unwrap(); + // Once the late answer is in, it is dropped and a new read is made. + let text = loop { + match loads.get((), Duration::from_secs(600)) { + Ok(text) => break text, + Err(why) => { + // The late answer isn't in yet. + assert_ne!(why, GONE); + std::thread::yield_now(); + } + } + }; + assert_eq!(text, "fresh"); + } + + #[test] + fn a_read_after_the_worker_stops_says_so() { + let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap(); + // The worker ends when its requests stop: cut them off by hand. + drop(std::mem::replace(&mut loads.line, Line::dead())); + assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string())); + } + + #[test] + fn another_threads_reads_stop_with_the_reads() { + let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap(); + let asker = loads.asker(); + assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1)); + drop(loads); + assert_eq!(asker.ask(()).err(), Some(GONE.to_string())); + // Closed while an asker still holds the line: nothing more is sent. + let line = Line::<(), ()>::dead(); + assert_eq!(line.close(), None); + assert_eq!(line.ask(()).err(), Some(GONE.to_string())); + } + + #[test] + fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() { + let (release, gate) = mpsc::channel::<()>(); + let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| { + if n == 1 { + let _ = gate.recv(); + } + n + }) + .unwrap(); + let answer = loads.ask(1).unwrap(); + // The caller doesn't wait: the answer is waited for wherever the channel goes. + let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600))); + // Until it comes, a read fails at once instead of queuing behind it. + assert!(loads.get(2, Duration::from_secs(600)).is_err()); + release.send(()).unwrap(); + assert_eq!(waiter.join().ok(), Some(Ok(1))); + assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3)); + } + + #[test] + fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() { + let clipboard = Arc::new(()); + let held = clipboard.clone(); + let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap(); + assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2)); + drop(loads); + assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's"); + } + + #[test] + fn dropping_the_reads_waits_for_an_unanswered_read_up_to_its_limit() { + let now = Instant::now(); + let limit = Duration::from_secs(25); + // No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound. + assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT); + // A read sent 2 s ago that timed out: wait for it until 25 s after it was sent. + assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23)); + // Its limit already over, or no limit (data-control, the core protocol): no wait. + assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now); + assert_eq!(stop_by(Some(now), now, Duration::ZERO), now); + } + } +} + /// arboard, or on a Wayland compositor without its data-control protocol the core protocol's text /// clipboard: one format at a time. Built everywhere so it is checked everywhere. #[cfg_attr(windows, allow(dead_code))] mod portable { use std::borrow::Cow; + use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; @@ -344,14 +625,343 @@ mod portable { use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of}; /// What our last write put on the clipboard. + #[derive(Clone)] enum Ours { Text(String), Image(usize, usize), } + /// A read of arboard's clipboard. + #[derive(Clone, Copy, PartialEq, Eq)] + enum Request { + Text, + Image, + Files, + } + + /// What a [`Request`] read. + enum Answer { + Text(Result), + Image(Result, String>), + Files(Vec), + } + + /// What a read says when it gets the answer to another request. + const MIXED: &str = "the clipboard answered another read"; + + impl Answer { + /// The answer to `request` when it couldn't be read: `why`, or no files. + #[cfg(any(test, target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn failed(request: Request, why: String) -> Self { + match request { + Request::Text => Self::Text(Err(why)), + Request::Image => Self::Image(Err(why)), + Request::Files => Self::Files(vec![]), + } + } + + /// The request this answers. + #[cfg_attr( + not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")), + allow(dead_code) + )] + fn request(&self) -> Request { + match self { + Self::Text(_) => Request::Text, + Self::Image(_) => Request::Image, + Self::Files(_) => Request::Files, + } + } + + fn text(self) -> Result { + match self { + Self::Text(text) => text, + _ => Err(MIXED.into()), + } + } + + fn image(self) -> Result, String> { + match self { + Self::Image(image) => image, + _ => Err(MIXED.into()), + } + } + + fn files(self) -> Vec { + match self { + Self::Files(files) => files, + _ => vec![], + } + } + } + + /// `request` read through `cb`. + fn answer(cb: &mut arboard::Clipboard, request: Request) -> Answer { + match request { + Request::Text => Answer::Text(cb.get_text().map_err(|e| e.to_string())), + Request::Image => Answer::Image(cb.get_image().map_err(|e| e.to_string())), + Request::Files => Answer::Files(cb.get().file_list().unwrap_or_default()), + } + } + + /// `request` read on `reads`' worker, waiting `wait` at most. + #[cfg(test)] + fn read_within(reads: &mut super::loads::Loads, request: Request, wait: Duration) -> Answer { + reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why)) + } + + /// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI + /// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as + /// long, from when it was sent, for a read that got no answer in its wait, the core protocol's + /// text read included. Text, file lists and the UI thread's bitmap check wait + /// [`LOAD_WAIT`](super::loads::LOAD_WAIT). + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + const IMAGE_WAIT: Duration = Duration::from_secs(10); + + /// How long a read of `request` waits for the app that copied. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn wait_for(request: Request) -> Duration { + match request { + Request::Image => IMAGE_WAIT, + Request::Text | Request::Files => super::loads::LOAD_WAIT, + } + } + + /// How long a paste's read of `request` after a late answer waits at `now`: as long as any read + /// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration { + wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now)) + } + + /// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries + /// six formats and waits up to 4 s for each, and a second more covers the rest of the read. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + const X11_READ_LIMIT: Duration = Duration::from_secs(25); + + /// Whether arboard's handles use the compositor's data-control protocol rather than X11. arboard + /// 3.7 makes the same check when it opens: data-control where `WAYLAND_DISPLAY` is set and + /// wl-clipboard-rs finds the protocol, X11 otherwise. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn on_data_control() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() && wl_clipboard_rs::utils::is_primary_selection_supported().is_ok() + } + + /// How long after an unanswered read was sent dropping the reads waits for it to end: on X11 + /// the last handle dropped hands what the app copied to a clipboard manager, and on + /// data-control, where a read may never end, nothing is handed over. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn finish(data_control: bool) -> Duration { + if data_control { Duration::ZERO } else { X11_READ_LIMIT } + } + + /// arboard's clipboard, with `C` for writes (arboard's handle; a stand-in in tests). On Linux + /// and the BSDs its reads run on a worker with a handle of its own and wait + /// [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, a paste's bitmap 10 s off the UI thread: arboard's Wayland + /// data-control read waits for the app that copied to send its data with no limit, and its X11 + /// read waits up to 4 s for each format it tries. + struct Arboard { + /// Dropped before `cb`, and waits for its worker's handle to go, on X11 up to + /// [`X11_READ_LIMIT`] after an unanswered read was sent: there the last handle dropped + /// hands what the app copied to the clipboard manager. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + reads: super::loads::Loads, + /// The last read that got no answer in its wait, until a paste takes it or the next read + /// is sent. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + unanswered: Option, + /// Writes, and elsewhere reads. + cb: C, + } + + /// A read on arboard's worker that got no answer in its wait. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + struct Unanswered { + request: Request, + answer: std::sync::mpsc::Receiver, + sent: Instant, + /// The worker, for the paste's other reads. + reads: super::loads::Asker, + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + impl Unanswered { + /// Whether a paste of one of `mimes` can take this read's answer: files paste as any of + /// them. + fn fits(&self, mimes: &[&'static str]) -> bool { + match self.request { + Request::Text => mimes.contains(&TEXT), + Request::Image => mimes.contains(&BITMAP), + Request::Files => true, + } + } + + /// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until + /// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes, + /// the same read is made again, since the clipboard may have changed hands meanwhile. + /// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the + /// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as + /// [`Clipboard::read_now_or_later`] and the paste read it, the new answer standing in for + /// the read it answers: copied files, else + /// text, else the bitmap, and the bitmap when it is asked for and the text is blank or only + /// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads + /// wait as [`follow_up_wait`] says. + fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { + let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now()); + super::loads::wait_for_answer(&self.answer, wait).ok()?; + let fresh = |request: Request| { + self.reads + .ask(request) + .and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now()))) + .unwrap_or_else(|why| Answer::failed(request, why)) + }; + // The late answer may come from an app that lost the clipboard while it was awaited. + let answer = fresh(self.request); + let held = match (&answer, ours) { + (Answer::Text(Ok(now)), Some(Ours::Text(t))) => now == t, + (Answer::Image(Ok(now)), Some(Ours::Image(w, h))) => (now.width, now.height) == (*w, *h), + _ => false, + }; + if held { + return None; + } + let mut answer = Some(answer); + let mut read = |request: Request| match answer.take_if(|a| a.request() == request) { + Some(answer) => answer, + None => fresh(request), + }; + if let Some(f) = copied_file(read(Request::Files).files(), mimes) { + return Some(f); + } + let text = if mimes.contains(&TEXT) { read(Request::Text).text().ok().filter(|t| !t.is_empty()) } else { None }; + let bitmap = |read: &mut dyn FnMut(Request) -> Answer| image_flavour(read(Request::Image).image().ok()?); + match text { + Some(t) if mimes.contains(&BITMAP) && (t.trim().is_empty() || vectorcraft_engine::cmd::clipboard::names_a_picture(&t)) => { + bitmap(&mut read).or(Some(Flavour { mime: TEXT, data: t.into_bytes() })) + } + Some(t) => Some(Flavour { mime: TEXT, data: t.into_bytes() }), + None if mimes.contains(&BITMAP) => bitmap(&mut read), + None => None, + } + } + } + + /// A read that got no answer in its wait, for a paste to wait for off the UI thread. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + enum Late { + Arboard(Unanswered), + /// The core protocol's text read. + #[cfg(target_os = "linux")] + Wayland(super::wayland::Unanswered), + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + impl Late { + /// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The + /// core protocol's text is waited for as long, until [`IMAGE_WAIT`] after its read was + /// sent, then read again, and pasted unless it is empty, what `ours` put on the clipboard, + /// or doesn't come. + fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { + match self { + Self::Arboard(unanswered) => unanswered.paste(ours, mimes), + #[cfg(target_os = "linux")] + Self::Wayland(unanswered) => { + let text = unanswered.text(IMAGE_WAIT).ok().filter(|t| !t.is_empty())?; + let held = matches!(ours, Some(Ours::Text(t)) if *t == text); + (!held).then(|| Flavour { mime: TEXT, data: text.into_bytes() }) + } + } + } + } + + /// arboard's bitmap as a PNG flavour. + fn image_flavour(img: arboard::ImageData<'static>) -> Option { + let (width, height) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?); + png_flavour(&image::RgbaImage::from_raw(width, height, img.bytes.into_owned())?) + } + + impl Arboard { + fn open() -> Result { + let cb = arboard::Clipboard::new().map_err(|e| e.to_string())?; + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + { + let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?; + let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request)) + .ok_or("the clipboard's reader didn't start")?; + Ok(Self { reads, unanswered: None, cb }) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + Ok(Self { cb }) + } + + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + fn read(&mut self, request: Request) -> Answer { + answer(&mut self.cb, request) + } + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + impl Arboard { + /// Reads on the worker; the write handle `C` is not used. + fn read(&mut self, request: Request) -> Answer { + self.read_waiting(request, wait_for(request)) + } + + /// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for + /// a check on the UI thread. + fn image_now(&mut self) -> Result, String> { + self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image() + } + + /// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that + /// time is kept ([`Self::unanswered`]) for a paste to wait for off the UI thread. + fn read_waiting(&mut self, request: Request, wait: Duration) -> Answer { + let sent = Instant::now(); + let answer = match self.ask(request) { + Ok(answer) => answer, + Err(why) => return Answer::failed(request, why), + }; + match super::loads::wait_for_answer(&answer, wait) { + Ok(answer) => answer, + Err(why) => { + if why != super::loads::GONE { + self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() }); + } + Answer::failed(request, why) + } + } + } + + /// `request` sent to the worker. A read sent means the one kept unanswered has been + /// answered, and its answer is dropped. + fn ask(&mut self, request: Request) -> Result, String> { + let answer = self.reads.ask(request)?; + self.unanswered = None; + Ok(answer) + } + + /// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for + /// it, so the caller can wait off the UI thread. Err when the read can't be sent. + fn image_later(&mut self) -> Result { + let answer = self.ask(Request::Image)?; + Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image))) + } + + /// The read that got no answer in its wait, while its answer has still not come and a paste + /// of one of `mimes` can take it: what the clipboard holds is not known until it comes. Once + /// it has come the answer may be old, and it is dropped: a new read is made. + fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + let unanswered = self.unanswered.take_if(|u| u.fits(mimes))?; + self.reads.waiting().then_some(unanswered) + } + } + + /// A bitmap read whose answer is waited for when it runs. + type ImageWork = Box Result, String> + Send>; + /// An open clipboard connection. enum Backend { - Arboard(arboard::Clipboard), + Arboard(Arboard), /// The compositor's core data-device protocol on the window's connection (text only). #[cfg(target_os = "linux")] Wayland(super::wayland::TextClipboard), @@ -366,7 +976,7 @@ mod portable { /// Wayland connection. Err: why each failed. fn open(window: Option<&Arc>) -> Result { first_open( - || arboard::Clipboard::new().map(Self::Arboard).map_err(|e| e.to_string()), + || Arboard::open().map(Self::Arboard), || { #[cfg(target_os = "linux")] return window.and_then(|w| super::wayland::TextClipboard::new(w.clone())).map(Self::Wayland).ok_or("not a Wayland window"); @@ -389,7 +999,7 @@ mod portable { fn get_text(&mut self) -> Result { match self { - Self::Arboard(cb) => cb.get_text().map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.read(Request::Text).text(), #[cfg(target_os = "linux")] Self::Wayland(cb) => cb.get_text(), } @@ -397,7 +1007,7 @@ mod portable { fn set_text(&mut self, text: &str) -> Result<(), String> { match self { - Self::Arboard(cb) => cb.set_text(text).map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.cb.set_text(text).map_err(|e| e.to_string()), #[cfg(target_os = "linux")] Self::Wayland(cb) => { cb.set_text(text); @@ -406,9 +1016,30 @@ mod portable { } } - fn get_image(&mut self) -> Result, String> { + /// The bitmap, for a check on the UI thread: on Linux and the BSDs it waits + /// [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, as text does. + fn image_now(&mut self) -> Result, String> { match self { - Self::Arboard(cb) => cb.get_image().map_err(|e| e.to_string()), + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + Self::Arboard(cb) => cb.image_now(), + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + Self::Arboard(cb) => cb.read(Request::Image).image(), + #[cfg(target_os = "linux")] + Self::Wayland(_) => Err(TEXT_ONLY.into()), + } + } + + /// The bitmap as work for another thread: on Linux and the BSDs the wait for the app + /// that copied happens when the work runs, elsewhere the bitmap is read here. + fn image_later(&mut self) -> Result { + match self { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + Self::Arboard(cb) => cb.image_later(), + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] + Self::Arboard(cb) => { + let image = cb.read(Request::Image).image()?; + Ok(Box::new(move || Ok(image))) + } #[cfg(target_os = "linux")] Self::Wayland(_) => Err(TEXT_ONLY.into()), } @@ -416,7 +1047,7 @@ mod portable { fn set_image(&mut self, img: arboard::ImageData<'_>) -> Result<(), String> { match self { - Self::Arboard(cb) => cb.set_image(img).map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.cb.set_image(img).map_err(|e| e.to_string()), #[cfg(target_os = "linux")] Self::Wayland(_) => Err(TEXT_ONLY.into()), } @@ -424,7 +1055,7 @@ mod portable { fn clear(&mut self) -> Result<(), String> { match self { - Self::Arboard(cb) => cb.clear().map_err(|e| e.to_string()), + Self::Arboard(cb) => cb.cb.clear().map_err(|e| e.to_string()), #[cfg(target_os = "linux")] Self::Wayland(cb) => { cb.set_text(""); @@ -433,10 +1064,31 @@ mod portable { } } - /// Files copied in a file manager (none where the backend can't read a file list). - fn file_list(&mut self) -> Vec { + /// The read that got no answer in its wait, when a paste of one of `mimes` can take its + /// answer ([`Arboard::unanswered`], [`TextReads::unanswered`](super::wayland::TextReads::unanswered)). + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn unanswered(&mut self, mimes: &[&'static str]) -> Option { match self { - Self::Arboard(cb) => cb.get().file_list().unwrap_or_default(), + Self::Arboard(cb) => cb.unanswered(mimes).map(Late::Arboard), + #[cfg(target_os = "linux")] + Self::Wayland(cb) => cb.unanswered(mimes).map(Late::Wayland), + } + } + + /// Drops the read that got no answer in its wait: a paste no longer takes its answer. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn forget_unanswered(&mut self) { + match self { + Self::Arboard(cb) => cb.unanswered = None, + #[cfg(target_os = "linux")] + Self::Wayland(cb) => cb.forget_unanswered(), + } + } + + /// Files copied in a file manager (none where the backend can't read a file list). + fn file_list(&mut self) -> Vec { + match self { + Self::Arboard(cb) => cb.read(Request::Files).files(), #[cfg(target_os = "linux")] Self::Wayland(_) => vec![], } @@ -560,6 +1212,38 @@ mod portable { let window = self.window.as_ref(); self.cb.get(asker, Instant::now(), || Backend::open(window), Backend::name).ok_or_else(|| "no system clipboard".to_string()) } + + /// The work that pastes the answer to a read that got no answer in its wait + /// ([`Late::paste`]), while that answer has not come. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn paste_unanswered(&mut self, mimes: &[&'static str]) -> Option { + let ours = self.ours.clone(); + let unanswered = self.cb(Asker::User).ok()?.unanswered(mimes)?; + let mimes = mimes.to_vec(); + Some(ClipboardRead::Later(Box::new(move || unanswered.paste(ours.as_ref(), &mimes)))) + } + + /// Text and copied files are read here, and work that reads arboard's image comes back. + fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option { + let cb = self.cb(Asker::User).ok()?; + if let Some(f) = copied_file(cb.file_list(), mimes) { + return Some(ClipboardRead::Now(f)); + } + mimes.iter().find_map(|m| { + #[cfg(target_os = "macos")] + if let Some(f) = super::mac::read(m) { + return Some(ClipboardRead::Now(f)); + } + match *m { + TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| ClipboardRead::Now(Flavour { mime: TEXT, data: t.into_bytes() })), + BITMAP => { + let read = cb.image_later().ok()?; + Some(ClipboardRead::Later(Box::new(move || image_flavour(read().ok()?)))) + } + _ => None, + } + }) + } } impl SystemClipboard for Clipboard { @@ -585,6 +1269,9 @@ mod portable { None } }; + // What a read got late was on the clipboard before this write. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + cb.forget_unanswered(); self.ours = ours; Ok(()) } @@ -593,37 +1280,31 @@ mod portable { let Some(cb) = self.cb.opened() else { return false }; match &self.ours { Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t), - Some(Ours::Image(w, h)) => cb.get_image().is_ok_and(|now| (now.width, now.height) == (*w, *h)), + Some(Ours::Image(w, h)) => cb.image_now().is_ok_and(|now| (now.width, now.height) == (*w, *h)), None => false, } } fn read(&mut self, mimes: &[&'static str]) -> Option { - self.read_deferred(mimes)?.flavour() + self.read_now_or_later(mimes)?.flavour() } - /// arboard's image is read here and encoded as PNG by the work that comes back. + /// arboard's image is read here and encoded as PNG by the work that comes back. On Linux and + /// the BSDs, after a read that got no answer in its wait (such as the check whether the + /// clipboard still holds what was copied here, or one of the reads here), the work waits for + /// that read's answer instead and pastes from it, or nothing when it is what was copied here. fn read_deferred(&mut self, mimes: &[&'static str]) -> Option { - let cb = self.cb(Asker::User).ok()?; - if let Some(f) = copied_file(cb.file_list(), mimes) { - return Some(ClipboardRead::Now(f)); + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + if let Some(read) = self.paste_unanswered(mimes) { + return Some(read); } - mimes.iter().find_map(|m| { - #[cfg(target_os = "macos")] - if let Some(f) = super::mac::read(m) { - return Some(ClipboardRead::Now(f)); - } - match *m { - TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| ClipboardRead::Now(Flavour { mime: TEXT, data: t.into_bytes() })), - BITMAP => { - let img = cb.get_image().ok()?; - let (width, height) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?); - let bytes = img.bytes.into_owned(); - Some(ClipboardRead::Later(Box::new(move || png_flavour(&image::RgbaImage::from_raw(width, height, bytes)?)))) - } - _ => None, - } - }) + let read = self.read_now_or_later(mimes); + // One of these reads got no answer in its wait, and the ones after it failed at once. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + if read.is_none() { + return self.paste_unanswered(mimes); + } + read } /// Text, and on macOS vector art or a bitmap (by the pasteboard's types). Linux has no @@ -642,6 +1323,7 @@ mod portable { mod tests { use std::cell::Cell; + use super::super::loads::Loads; use super::*; /// A clock that starts now and moves only when told. @@ -763,6 +1445,270 @@ mod portable { ); } + #[test] + fn reads_return_while_the_clipboard_owner_sends_nothing() { + let (release, gate) = std::sync::mpsc::channel::<()>(); + // The app that copied never sends its data until released. + let mut reads = Loads::spawn("test", Duration::ZERO, move |request| { + let _ = gate.recv(); + Answer::failed(request, "late".into()) + }) + .unwrap(); + // Copy's look at the text, Paste's file list and its bitmap: none waits for the owner. + assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err()); + assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty()); + assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err()); + drop(release); + } + + #[test] + fn each_read_takes_its_own_answer() { + let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request { + Request::Text => Answer::Text(Ok("".into())), + Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })), + Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]), + }) + .unwrap(); + let wait = Duration::from_secs(600); + assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("".to_string())); + assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1))); + assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]); + // The answer to another read is not taken for this one. + assert_eq!(Answer::Files(vec![]).text(), Err(MIXED.to_string())); + assert!(Answer::Text(Ok(String::new())).image().is_err()); + assert!(Answer::Text(Ok("art.svg".into())).files().is_empty()); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn arboards_reads_run_on_its_reader_and_wait_by_kind() { + let reads = Loads::spawn("test", Duration::ZERO, |request| match request { + Request::Text => Answer::Text(Ok("read on the worker".into())), + _ => Answer::failed(request, "not asked".into()), + }) + .unwrap(); + // `()` for writes: a read made through the write handle wouldn't build. + let mut cb = Arboard { reads, unanswered: None, cb: () }; + assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string())); + assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT); + assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT); + assert_eq!(wait_for(Request::Image), Duration::from_secs(10)); + // A paste's reads after a late answer wait until 10 s after the unanswered read was + // sent, and never less than any read of their kind. + let sent = Instant::now(); + assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7)); + assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT); + assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT); + // X11 waits for an unanswered read when the clipboard closes; data-control doesn't. + assert_eq!(finish(false), X11_READ_LIMIT); + assert_eq!(finish(true), Duration::ZERO); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() { + let (release, gate) = std::sync::mpsc::channel::<()>(); + // The app that copied sends its bitmap only when released. + let reads = Loads::spawn("test", Duration::ZERO, move |request| match request { + Request::Image => { + let _ = gate.recv(); + Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })) + } + _ => Answer::failed(request, "not asked".into()), + }) + .unwrap(); + let mut cb = Arboard { reads, unanswered: None, cb: () }; + // The read is sent and the UI thread goes on without its answer. + let work = cb.image_later().unwrap(); + // A check on the UI thread meanwhile fails at once instead of waiting behind it. + assert!(cb.read(Request::Text).text().is_err()); + let paste = std::thread::spawn(work); + release.send(()).unwrap(); + assert_eq!(paste.join().ok().and_then(Result::ok).map(|i| (i.width, i.height)), Some((2, 1))); + } + + /// An arboard clipboard whose owner answers each read with `answer` only once the sender + /// returned is used or dropped. + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) { + let (release, gate) = std::sync::mpsc::channel::<()>(); + let reads = Loads::spawn("test", Duration::ZERO, move |request| { + let _ = gate.recv(); + answer(request) + }) + .unwrap(); + (Arboard { reads, unanswered: None, cb: () }, release) + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_paste_after_an_unanswered_ownership_check_waits_for_its_answer() { + let image = |width: usize| Answer::Image(Ok(arboard::ImageData { width, height: 1, bytes: Cow::Owned(vec![0; width * 4]) })); + // A 2×1 bitmap was copied here; the clipboard's owner sends a `width`×1 one late. + let paste_after_check = |width: usize| { + let (mut cb, release) = slow_owner(move |_| image(width)); + // The check whether the clipboard still holds what was copied here gets no answer + // in its wait (2 s on the UI thread, none here). + assert!(cb.read_waiting(Request::Image, Duration::ZERO).image().is_err()); + // The paste's own reads fail at once while the owner hasn't answered. + assert!(cb.read(Request::Files).files().is_empty()); + assert!(cb.read(Request::Text).text().is_err()); + assert!(cb.image_later().is_err()); + // The paste waits for the check's answer off the UI thread instead. + let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the check's read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &[BITMAP])); + drop(release); + paste.join().ok().flatten() + }; + // Another app's bitmap is pasted, not the art copied here. + let pasted = paste_after_check(3).expect("the new bitmap is pasted"); + assert_eq!((pasted.mime, decode_png(&pasted.data).map(|i| i.dimensions())), (PNG, Some((3, 1)))); + // The bitmap copied here: the paste takes the internal clipboard. + assert!(paste_after_check(2).is_none()); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + #[test] + fn a_late_answer_to_an_ownership_check_is_pasted_only_while_it_is_awaited() { + // Text was copied here; the clipboard's owner answers the check with `text` late, and + // has a 3×1 bitmap. + let paste_after_check = |text: &'static str| { + let (mut cb, release) = slow_owner(move |request| match request { + Request::Text => Answer::Text(Ok(text.into())), + Request::Image => Answer::Image(Ok(arboard::ImageData { width: 3, height: 1, bytes: Cow::Owned(vec![0; 12]) })), + Request::Files => Answer::Files(vec![]), + }); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + // A paste of a bitmap alone can't take a text read's answer: the read stays kept. + assert!(cb.unanswered(&[BITMAP]).is_none()); + let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the check's read is kept for the paste"); + let ours = Ours::Text("copied here".into()); + let paste = std::thread::spawn(move || unanswered.paste(Some(&ours), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER)); + drop(release); + paste.join().ok().flatten() + }; + let pasted = paste_after_check("copied elsewhere").expect("the other app's text is pasted"); + assert_eq!((pasted.mime, pasted.data), (TEXT, b"copied elsewhere".to_vec())); + // Text that only names a picture goes with it: the picture is pasted, as at once. + let pasted = paste_after_check("").expect("the picture is pasted"); + assert_eq!((pasted.mime, decode_png(&pasted.data).map(|i| i.dimensions())), (PNG, Some((3, 1)))); + // The text copied here: the paste takes the internal clipboard. + assert!(paste_after_check("copied here").is_none()); + + // A paste's own file-list read that gets no answer: once it comes, the text is read. + let (mut cb, release) = slow_owner(|request| match request { + Request::Text => Answer::Text(Ok("late text".into())), + _ => Answer::failed(request, "none".into()), + }); + assert!(cb.read_waiting(Request::Files, Duration::ZERO).files().is_empty()); + let unanswered = cb.unanswered(&[TEXT]).expect("the file-list read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(None, &[TEXT])); + drop(release); + assert_eq!(paste.join().ok().flatten().map(|f| f.data), Some(b"late text".to_vec())); + + // A paste of text alone pastes text that names a picture, not the picture. + let (mut cb, release) = slow_owner(|request| match request { + Request::Text => Answer::Text(Ok("".into())), + Request::Image => Answer::Image(Ok(arboard::ImageData { width: 3, height: 1, bytes: Cow::Owned(vec![0; 12]) })), + Request::Files => Answer::Files(vec![]), + }); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + let unanswered = cb.unanswered(&[TEXT]).expect("the text read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(None, &[TEXT])); + drop(release); + let pasted = paste.join().ok().flatten().expect("the text is pasted"); + assert_eq!((pasted.mime, pasted.data), (TEXT, b"".to_vec())); + + // The app that answers late may have lost the clipboard meanwhile: the paste reads it + // again and takes the new owner's text. + let texts_read = std::sync::atomic::AtomicUsize::new(0); + let (mut cb, release) = slow_owner(move |request| match request { + Request::Text if texts_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 => Answer::Text(Ok("old owner".into())), + Request::Text => Answer::Text(Ok("new owner".into())), + _ => Answer::failed(request, "none".into()), + }); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + let unanswered = cb.unanswered(&[TEXT]).expect("the text read is kept for the paste"); + let paste = std::thread::spawn(move || unanswered.paste(None, &[TEXT])); + drop(release); + assert_eq!(paste.join().ok().flatten().map(|f| f.data), Some(b"new owner".to_vec())); + + // An answer that came before the paste may be old: it is dropped, not pasted. + let (mut cb, release) = slow_owner(|request| Answer::failed(request, "not asked".into())); + assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err()); + drop(release); + while cb.reads.waiting() { + std::thread::yield_now(); + } + assert!(cb.unanswered(&[TEXT]).is_none()); + } + + #[cfg(target_os = "linux")] + #[test] + fn a_paste_after_an_unanswered_core_protocol_text_read_waits_for_its_answer() { + use super::super::wayland::TextReads; + use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; + + /// Core protocol text reads whose owner answers with `text` only once the sender + /// returned is used or dropped. + fn slow_text(text: &'static str) -> (TextReads, std::sync::mpsc::Sender<()>) { + let (release, gate) = std::sync::mpsc::channel::<()>(); + let loads = Loads::spawn("test", Duration::ZERO, move |()| { + let _ = gate.recv(); + Ok(text.to_string()) + }) + .unwrap(); + (TextReads::new(loads), release) + } + // Text was copied here; the clipboard's owner answers the check with `text` late. + let paste_after_check = |text: &'static str| { + let (mut reads, release) = slow_text(text); + // The check whether the clipboard still holds what was copied here gets no answer + // in its wait (2 s on the UI thread, none here). + assert!(reads.get(Duration::ZERO).is_err()); + // The paste's own read fails at once while the owner hasn't answered. + assert!(reads.get(Duration::from_secs(600)).is_err()); + // A paste of a bitmap alone can't take text: the read stays kept. + assert!(reads.unanswered(&[BITMAP]).is_none()); + let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste")); + let ours = Ours::Text("copied here".into()); + let paste = std::thread::spawn(move || late.paste(Some(&ours), &PASTE_ORDER)); + drop(release); + paste.join().ok().flatten() + }; + let pasted = paste_after_check("copied elsewhere").expect("the other app's text is pasted"); + assert_eq!((pasted.mime, pasted.data), (TEXT, b"copied elsewhere".to_vec())); + // The text copied here, or nothing: the paste takes the internal clipboard. + assert!(paste_after_check("copied here").is_none()); + assert!(paste_after_check("").is_none()); + + // An answer that came before the paste may be old: it is dropped, not pasted. + let (mut reads, release) = slow_text("old"); + assert!(reads.get(Duration::ZERO).is_err()); + drop(release); + while reads.waiting() { + std::thread::yield_now(); + } + assert!(reads.unanswered(&[TEXT]).is_none()); + + // The app that answers late may have lost the clipboard meanwhile: the paste reads it + // again and takes the new owner's text. + let (release, gate) = std::sync::mpsc::channel::<()>(); + let mut texts_read = 0; + let loads = Loads::spawn("test", Duration::ZERO, move |()| { + let _ = gate.recv(); + texts_read += 1; + Ok(if texts_read == 1 { "old owner" } else { "new owner" }.to_string()) + }) + .unwrap(); + let mut reads = TextReads::new(loads); + assert!(reads.get(Duration::ZERO).is_err()); + let late = Late::Wayland(reads.unanswered(&[TEXT]).expect("the read is kept for the paste")); + let paste = std::thread::spawn(move || late.paste(None, &[TEXT])); + drop(release); + assert_eq!(paste.join().ok().flatten().map(|f| f.data), Some(b"new owner".to_vec())); + } + #[test] fn one_outage_is_logged_once_across_handles() { static LOGGED: AtomicBool = AtomicBool::new(false); @@ -783,27 +1729,93 @@ mod portable { /// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on /// a Wayland session). Text only (smithay-clipboard), and only while the window has focus, as the /// protocol has it. A read waits [`LOAD_WAIT`] at most: smithay-clipboard waits for the owner's -/// data with no limit, so reads run on a worker of their own. +/// data with no limit, so reads run on a worker of their own. A read that gets no answer in that +/// time is kept for a paste to wait for off the UI thread, as arboard's are. #[cfg(target_os = "linux")] mod wayland { - use std::sync::Arc; - use std::sync::mpsc; - use std::time::Duration; + use std::sync::{Arc, mpsc}; + use std::time::{Duration, Instant}; - /// The longest a read waits for the selection's owner to send its text. - const LOAD_WAIT: Duration = Duration::from_secs(2); - /// What a read says once its worker has stopped. - const GONE: &str = "the clipboard's reader stopped"; + use super::TEXT; + use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer}; + + /// What a text read gives. + type Text = Result; pub struct TextClipboard { /// Writes: a store only hands the text to smithay-clipboard's thread. cb: smithay_clipboard::Clipboard, /// Reads, on a worker with a second clipboard on the same connection. - loads: Loads, + reads: TextReads, /// Held as long as the clipboards: their connection is the window's. _window: Arc, } + /// Text reads on a worker, and the last one that got no answer in its wait. + pub(super) struct TextReads { + loads: Loads<(), Text>, + /// The last read that got no answer in its wait, until a paste takes it or the next read + /// is sent. + unanswered: Option, + } + + /// A text read that got no answer in its wait. + pub(super) struct Unanswered { + answer: mpsc::Receiver, + sent: Instant, + /// The worker, for the read made again once the answer comes. + reads: Asker<(), Text>, + } + + impl Unanswered { + /// The text, read again once this read's answer comes, waiting for that answer until + /// `limit` after the read was sent, and for the new one as long, [`LOAD_WAIT`] at least. + /// The late answer may come from an app that lost the clipboard while it was awaited. + pub(super) fn text(self, limit: Duration) -> Text { + let left = |now: Instant| (self.sent + limit).saturating_duration_since(now); + let _late = wait_for_answer(&self.answer, left(Instant::now()))?; + wait_for_answer(&self.reads.ask(())?, LOAD_WAIT.max(left(Instant::now())))? + } + } + + impl TextReads { + pub(super) fn new(loads: Loads<(), Text>) -> Self { + Self { loads, unanswered: None } + } + + /// The text, waiting `wait` at most. A read that gets no answer in that time is kept + /// ([`Self::unanswered`]) for a paste to wait for off the UI thread; a read sent means the + /// one kept has been answered, and its answer is dropped. + pub(super) fn get(&mut self, wait: Duration) -> Text { + let sent = Instant::now(); + let answer = self.loads.ask(())?; + self.unanswered = None; + match wait_for_answer(&answer, wait) { + Ok(text) => text, + Err(why) => { + if why != GONE { + self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker() }); + } + Err(why) + } + } + } + + /// The read that got no answer in its wait, while its answer has still not come and a + /// paste of one of `mimes` can take text. Once it has come the answer may be old, and it is + /// dropped: a new read is made. + pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + let unanswered = self.unanswered.take_if(|_| mimes.contains(&TEXT))?; + self.loads.waiting().then_some(unanswered) + } + + /// Whether a read sent is still unanswered. + #[cfg(test)] + pub(super) fn waiting(&self) -> bool { + self.loads.waiting() + } + } + /// The read worker's clipboard and the window whose connection it uses, dropped in that order. struct Loader { cb: smithay_clipboard::Clipboard, @@ -830,113 +1842,29 @@ mod wayland { let loader = Loader { cb: reader, _window: window.clone() }; // `loader.load()`, not `loader.cb.load()`: a closure moves only the fields it names, // and the worker must hold the window as long as its clipboard. - let loads = Loads::spawn(move || loader.load())?; - Some(Self { cb, loads, _window: window }) + // Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the + // app copied on when the last one goes. + let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |()| loader.load())?; + Some(Self { cb, reads: TextReads::new(loads), _window: window }) } pub fn get_text(&mut self) -> Result { - self.loads.get(LOAD_WAIT) + self.reads.get(LOAD_WAIT) } pub fn set_text(&self, text: &str) { self.cb.store(text); } - } - /// Reads made on a worker thread and waited for a bounded time: a selection owner that never - /// sends its data holds the worker, not the caller. - struct Loads { - requests: mpsc::Sender<()>, - answers: mpsc::Receiver>, - /// A read that timed out and hasn't answered yet: until it does, reads don't queue behind it. - pending: bool, - } - - impl Loads { - fn spawn(mut load: impl FnMut() -> Result + Send + 'static) -> Option { - let (requests, asked) = mpsc::channel::<()>(); - let (answer, answers) = mpsc::channel(); - let work = move || { - while asked.recv().is_ok() { - if answer.send(load()).is_err() { - break; - } - } - }; - std::thread::Builder::new().name("wayland-clipboard-read".into()).spawn(work).ok()?; - Some(Self { requests, answers, pending: false }) + /// The read that got no answer in its wait, when a paste of one of `mimes` can take its + /// answer ([`TextReads::unanswered`]). + pub(super) fn unanswered(&mut self, mimes: &[&'static str]) -> Option { + self.reads.unanswered(mimes) } - /// The text, or why there is none, after `wait` at most. - fn get(&mut self, wait: Duration) -> Result { - if self.pending { - match self.answers.try_recv() { - // The late answer of the read that timed out: stale by now. - Ok(_) => self.pending = false, - Err(mpsc::TryRecvError::Empty) => return Err("the clipboard's owner hasn't answered an earlier read".into()), - Err(mpsc::TryRecvError::Disconnected) => return Err(GONE.into()), - } - } - self.requests.send(()).map_err(|_| GONE.to_string())?; - match self.answers.recv_timeout(wait) { - Ok(text) => text, - Err(mpsc::RecvTimeoutError::Timeout) => { - self.pending = true; - Err(format!("the clipboard's owner didn't send its text within {wait:?}")) - } - Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()), - } - } - } - - #[cfg(test)] - mod tests { - use std::time::Instant; - - use super::*; - - #[test] - fn a_read_that_answers_in_time_gives_the_text() { - let mut loads = Loads::spawn(|| Ok("".into())).unwrap(); - assert_eq!(loads.get(Duration::from_secs(5)), Ok("".to_string())); - assert_eq!(loads.get(Duration::from_secs(5)), Ok("".to_string())); - } - - #[test] - fn an_owner_that_never_answers_holds_the_worker_not_the_caller() { - let (release, gate) = mpsc::channel::<()>(); - let mut calls = 0; - let mut loads = Loads::spawn(move || { - calls += 1; - if calls == 1 { - // The first owner sends nothing until released. - let _ = gate.recv(); - return Ok("stale".into()); - } - Ok("fresh".into()) - }) - .unwrap(); - let start = Instant::now(); - assert!(loads.get(Duration::from_millis(50)).is_err(), "the first read times out"); - // While it is unanswered, a read doesn't queue behind it or wait at all. - assert!(loads.get(Duration::from_secs(60)).is_err()); - assert!(start.elapsed() < Duration::from_secs(30), "no read waited past its bound"); - release.send(()).unwrap(); - // Once the late answer is in, it is dropped and a new read is made. - let text = (0..200).find_map(|_| { - std::thread::sleep(Duration::from_millis(10)); - loads.get(Duration::from_secs(5)).ok() - }); - assert_eq!(text.as_deref(), Some("fresh")); - } - - #[test] - fn a_read_after_the_worker_stops_says_so() { - let mut loads = Loads::spawn(|| Ok(String::new())).unwrap(); - // The worker ends when its answers can't be sent: drop them by hand. - let (_, dead) = mpsc::channel(); - drop(std::mem::replace(&mut loads.answers, dead)); - assert_eq!(loads.get(Duration::from_millis(50)), Err(GONE.to_string())); + /// Drops the read that got no answer in its wait: a paste no longer takes its answer. + pub fn forget_unanswered(&mut self) { + self.reads.unanswered = None; } } } diff --git a/apps/vectorcraft/src/hang_watch.rs b/apps/vectorcraft/src/hang_watch.rs new file mode 100644 index 0000000000..e5adb77dfa --- /dev/null +++ b/apps/vectorcraft/src/hang_watch.rs @@ -0,0 +1,445 @@ +//! The hang report. A thread reads the interface thread's marks +//! ([`vectorcraft_ui_egui::hang_beacon`]) every [`POLL`]. When the interface thread has made no +//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the +//! log (`logs/vectorcraft.log`) and to `logs/hang-report-.txt`: the stage, a clipboard +//! call in progress, the last commands, the last frames' times, the platform, the window system, the +//! graphics processor and the present mode the app asked for, and how long the session has run with +//! how many documents open. The process holds a lock on the file until the interface thread answers +//! again; then the log says after how long and the file is removed. A file nobody holds at a later +//! launch was left by a session that was closed while it did not answer, and a locked one belongs to +//! another instance that is stalled now and is left alone. That launch writes the report to the log, +//! moves the newest abandoned file to `hang-report.1.txt` and removes the others, says so in the +//! status bar, and Help › Copy Troubleshooting Info copies the reports. Where the file system has no +//! file locks, the file is written and taken without one. +//! +//! No native stack is recorded: the marks are what the report has. The report holds command ids and +//! counts, never document contents or file paths. [`STALL`] is VectorCraft's own value. +//! +//! A stall in the renderer is timed only after a frame that had input in any window: input asks for +//! the next frame at once, so a frame that does not start then is late. After a frame without +//! input, the window waiting for input looks the same as one stuck drawing, so that time is not +//! timed. Nor is the time after a frame that minimizes or hides the main window or hands it to the +//! system to move or resize. A window the system stops redrawing while it is hidden can still look +//! like a stall after a frame with input; the report's stage says so. A system file dialog shown in +//! line (on Windows and Linux) and an open menu of the macOS menu bar wait for the user and are not +//! timed. + +use std::fs::File; +use std::io::{Read as _, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant, SystemTime}; + +#[cfg(target_os = "macos")] +use vectorcraft_ui_egui::hang_beacon::Activity; +use vectorcraft_ui_egui::hang_beacon::{BEACON, Beacon, FrameTime, Sample, Stage}; + +use super::logging::timestamp; + +/// How long the interface thread may stay in one stage before the report is written. +pub const STALL: Duration = Duration::from_secs(3); +/// How often the watching thread reads the marks. +pub const POLL: Duration = Duration::from_millis(500); +/// The report of a stall that has not ended, in the log folder: this, the process id, `.txt`. +pub const REPORT_PREFIX: &str = "hang-report-"; +/// At most this many report files are taken when a launch looks for abandoned ones; older abandoned +/// ones are removed. +const MAX_REPORT_FILES: usize = 16; +/// At most this many entries of the log folder are looked at for report files. +const MAX_SCANNED_ENTRIES: usize = 1024; +/// The report the last session left, moved here at launch. +pub const PREVIOUS_FILE: &str = "hang-report.1.txt"; +/// A report file larger than this is not read. +pub const MAX_REPORT_BYTES: u64 = 64 * 1024; +/// Environment values in the report are cut to this many characters. +const MAX_VALUE_CHARS: usize = 64; + +/// What [`Watch::check`] found. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Event { + /// The interface thread has been in the sample's stage, without a mark, for this long. + Stalled(Duration), + /// The interface thread made a mark again after a [`Event::Stalled`], about this long after + /// the stall began. + Answered(Duration), +} + +/// Decides from successive samples when the interface thread has stalled and when it answers +/// again. Time comes from the caller, so tests drive it without waiting. +#[derive(Debug)] +pub struct Watch { + stall: Duration, + /// The step seen in a busy stage and when it was first seen. + seen: Option<(u64, Duration)>, + reported: bool, +} + +impl Watch { + pub fn new(stall: Duration) -> Watch { + Watch { stall, seen: None, reported: false } + } + + /// The marks read at `now` (any monotonic clock that started before the first call). + pub fn check(&mut self, now: Duration, sample: Sample) -> Option { + let same = self.seen.is_some_and(|(step, _)| step == sample.step); + if same && sample.busy() { + let since = self.seen.map_or(now, |(_, since)| since); + let stalled = now.saturating_sub(since); + if !self.reported && stalled >= self.stall { + self.reported = true; + return Some(Event::Stalled(stalled)); + } + return None; + } + let answered = match (self.reported, self.seen) { + (true, Some((_, since))) => Some(Event::Answered(now.saturating_sub(since))), + _ => None, + }; + self.reported = false; + self.seen = sample.busy().then_some((sample.step, now)); + answered + } +} + +/// What the report says about the platform. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Facts { + /// The window system the window opened on: Wayland, X11, AppKit, Win32, other or unknown. + pub window_system: String, + /// `XDG_CURRENT_DESKTOP`. + pub desktop: Option, + /// `XDG_SESSION_TYPE`. + pub session_type: Option, + /// Running in a Flatpak sandbox. + pub flatpak: bool, + /// The graphics processor the window draws with. + pub graphics: Option, + /// The present mode and frame queue the app asked the window surface for. + pub surface: String, +} + +impl Facts { + /// The facts from the environment (`env`, `flatpak_info`: whether `/.flatpak-info` exists) and + /// what the app knows. + pub fn new(env: impl Fn(&str) -> Option, flatpak_info: bool, window_system: &str, graphics: Option, surface: String) -> Facts { + let value = |name: &str| env(name).map(|v| clean(&v)).filter(|v| !v.is_empty()); + Facts { + window_system: window_system.to_string(), + desktop: value("XDG_CURRENT_DESKTOP"), + session_type: value("XDG_SESSION_TYPE"), + flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()), + graphics, + surface, + } + } + + /// The facts as report lines. + pub fn lines(&self) -> String { + let or_unknown = |v: &Option| v.clone().unwrap_or_else(|| "unknown".to_string()); + format!( + "VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH, + self.window_system, + or_unknown(&self.desktop), + or_unknown(&self.session_type), + if self.flatpak { "yes" } else { "no" }, + or_unknown(&self.graphics), + self.surface, + ) + } +} + +/// `v` with control characters removed, cut to [`MAX_VALUE_CHARS`] characters. +fn clean(v: &str) -> String { + v.chars().filter(|c| !c.is_control()).take(MAX_VALUE_CHARS).collect::().trim().to_string() +} + +/// The marks other than the stage: the last commands, the last frames and the session. +fn activity_lines(beacon: &Beacon, uptime: Duration) -> String { + let commands = match beacon.recent_commands() { + Some(c) if c.is_empty() => "none".to_string(), + Some(c) => c.join(", "), + None => "unavailable (being written)".to_string(), + }; + let (work, total) = match beacon.recent_frames() { + Some(frames) => { + let list = |f: &dyn Fn(&FrameTime) -> Option| { + let times: Vec = frames.iter().filter_map(f).map(|ms| format!("{ms:.1}")).collect(); + if times.is_empty() { "none".to_string() } else { times.join(", ") } + }; + (list(&|t| Some(t.work_ms)), list(&|t| t.previous_total_ms)) + } + None => ("unavailable (being written)".to_string(), "unavailable (being written)".to_string()), + }; + format!( + "Recent commands, oldest first: {commands}\nApp work per frame (ms), oldest first: {work}\nWork and drawing per frame, without waiting for the display (ms), oldest first: {total}\nSession: running for {} s, {} documents open\n", + uptime.as_secs(), + beacon.documents(), + ) +} + +/// The report of a stall that has lasted `stalled` in `sample`'s stage, written at `at`. +pub fn report(at: SystemTime, stalled: Duration, sample: Sample, beacon: &Beacon, uptime: Duration, facts: &Facts) -> String { + let waiting = sample.activity.describe().map(|a| format!("Waiting on: {a}\n")).unwrap_or_default(); + format!( + "VectorCraft hang report, {}\nThe interface thread has not moved on for {:.1} s.\nStage: {}\n{waiting}{}{}No native stack is recorded: the stage and the activity are what the app marks.\n", + timestamp(at), + stalled.as_secs_f64(), + sample.stage.describe(), + activity_lines(beacon, uptime), + facts.lines(), + ) +} + +/// What the watching thread and Help › Copy Troubleshooting Info share. +pub struct Shared { + pub facts: Facts, + pub started: Instant, + /// This session's last report. + pub last: Mutex>, + /// The report the last session left ([`take_previous`]). + pub previous: Option, +} + +/// The text Help › Copy Troubleshooting Info copies. +pub fn troubleshooting(shared: &Shared, beacon: &Beacon, at: SystemTime) -> String { + let last = shared.last.lock().unwrap_or_else(PoisonError::into_inner).clone(); + format!( + "VectorCraft troubleshooting info, {}\n{}{}\nThis session's last hang report:\n{}\nThe hang report the last session left (it was closed while it did not answer):\n{}\n", + timestamp(at), + shared.facts.lines(), + activity_lines(beacon, shared.started.elapsed()), + last.as_deref().unwrap_or("none\n"), + shared.previous.as_deref().unwrap_or("none\n"), + ) +} + +/// The report file of this process in `dir`. +fn report_path(dir: &Path) -> PathBuf { + dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id())) +} + +/// A report file this process wrote and holds locked until the interface answers again. +#[derive(Debug)] +pub struct Held { + path: PathBuf, + _file: File, +} + +/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no +/// file locks, the file is written unlocked and the log says so. +fn write_report(dir: &Path, text: &str) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let path = report_path(dir); + let mut file = File::create(&path)?; + if let Err(e) = file.lock() { + log::warn!("the hang report file is written without a lock: {e}"); + } + file.write_all(text.as_bytes())?; + Ok(Held { path, _file: file }) +} + +/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file +/// system without file locks answers [`std::io::ErrorKind::Unsupported`], and its files count as +/// abandoned; any other error leaves the file alone. +fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool { + match locked { + Ok(()) => true, + Err(std::fs::TryLockError::Error(e)) => e.kind() == std::io::ErrorKind::Unsupported, + Err(std::fs::TryLockError::WouldBlock) => false, + } +} + +/// The report file at `path`, opened and locked, with its length, when it was abandoned +/// ([`abandoned`]) and is not empty (an empty one may be being written). +fn open_abandoned(path: &Path) -> Option<(File, u64)> { + let file = File::options().read(true).write(true).open(path).ok()?; + if !abandoned(file.try_lock()) { + return None; + } + let len = file.metadata().map_or(0, |m| m.len()); + (len > 0).then_some((file, len)) +} + +/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None` +/// when there are none. The newest file is moved to [`PREVIOUS_FILE`] and the others are removed +/// once read. Of more than [`MAX_REPORT_FILES`], the newest are taken and the older ones removed +/// unread; the first [`MAX_SCANNED_ENTRIES`] entries of `dir` are looked at. A report file another +/// process holds locked, or one still empty, is left alone. A file over [`MAX_REPORT_BYTES`] is +/// taken without being read. A file that can't be moved is removed, so no later launch offers it +/// again: the caller writes the reports to the log. Each file is opened once. +pub fn take_previous(dir: &Path) -> Option { + let mut found: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(dir) + .ok()? + .take(MAX_SCANNED_ENTRIES) + .filter_map(Result::ok) + .filter(|e| { + e.file_name() + .to_str() + .and_then(|n| n.strip_prefix(REPORT_PREFIX)?.strip_suffix(".txt")) + .is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())) + }) + .map(|e| (e.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH), e.path())) + .collect(); + found.sort(); + // Newest first: only abandoned reports count toward the limit. + let mut texts = Vec::new(); + for (_, path) in found.into_iter().rev() { + let Some((file, len)) = open_abandoned(&path) else { continue }; + if texts.len() == MAX_REPORT_FILES { + drop(file); + remove_quietly(&path); + continue; + } + let mut bytes = Vec::new(); + let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() { + String::from_utf8_lossy(&bytes).into_owned() + } else { + format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n") + }; + // Closed (and unlocked) before it is moved: Windows moves no open file. + drop(file); + if !texts.is_empty() { + remove_quietly(&path); + } else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) { + log::warn!("couldn't move the hang report file to {PREVIOUS_FILE}: {e}"); + remove_quietly(&path); + } + texts.push(text); + } + texts.reverse(); + (!texts.is_empty()).then(|| texts.join("\n")) +} + +/// Remove the report file at `path`; a failure goes to the log. +fn remove_quietly(path: &Path) { + if let Err(e) = std::fs::remove_file(path) { + log::warn!("couldn't remove the hang report file: {e}"); + } +} + +/// Set when the app closes normally ([`closing`]): the watching thread writes no report file after it. +pub static CLOSING: AtomicBool = AtomicBool::new(false); + +/// Remove `held`'s file, closing it first. → the error message; a file already gone is none. +fn remove(held: Held) -> Option { + let Held { path, _file: file } = held; + drop(file); + match std::fs::remove_file(&path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()), + _ => None, + } +} + +/// Act on what [`Watch::check`] found: write (and hold) or remove this process's report file in +/// `dir`, then log it. The file comes first: logging can wait on what the interface thread waits on. +#[allow(clippy::too_many_arguments)] +pub fn record( + event: Event, + sample: Sample, + beacon: &Beacon, + shared: &Shared, + dir: Option<&Path>, + held: &mut Option, + closing: &AtomicBool, + at: SystemTime, +) { + match event { + Event::Stalled(stalled) => { + let text = report(at, stalled, sample, beacon, shared.started.elapsed(), &shared.facts); + let mut failed = None; + if let Some(dir) = dir.filter(|_| !closing.load(Ordering::Acquire)) { + match write_report(dir, &text) { + Ok(file) => *held = Some(file), + Err(e) => failed = Some(e.to_string()), + } + // The app began to close while the file was written: it is not a report to leave. + if closing.load(Ordering::Acquire) { + failed = held.take().and_then(remove).or(failed); + } + } + *shared.last.lock().unwrap_or_else(PoisonError::into_inner) = Some(text.clone()); + log::warn!("the interface stopped answering:\n{}", text.trim_end()); + if let Some(e) = failed { + log::warn!("couldn't write or remove the hang report file: {e}"); + } + } + Event::Answered(after) => { + let failed = held.take().and_then(remove); + log::warn!("the interface answered again about {:.1} s after it stopped", after.as_secs_f64()); + if let Some(e) = failed { + log::warn!("couldn't remove the hang report file: {e}"); + } + } + } +} + +/// The app is closing normally: mark the interface thread idle on `beacon` (saving and teardown are +/// not timed), remove this process's report file in `dir` and have the watching thread write no +/// more. It does not wait for the watching thread. The file can be removed while that thread holds +/// it open and locked: the standard library opens files with `FILE_SHARE_DELETE` on Windows, and a +/// byte-range lock does not prevent deletion. Where Windows deletes a file only once its last +/// handle closes, the name goes when the process ends. +pub fn closing(dir: Option<&Path>, closing: &AtomicBool, beacon: &Beacon) { + beacon.enter(Stage::Idle); + closing.store(true, Ordering::Release); + if let Some(dir) = dir { + match std::fs::remove_file(report_path(dir)) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => log::warn!("couldn't remove the hang report file: {e}"), + _ => {} + } + } +} + +/// The window system `window` opened on, for [`Facts::window_system`]. +pub fn window_system(window: Option<&winit::window::Window>) -> &'static str { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + match window.and_then(|w| w.window_handle().ok()).map(|h| h.as_raw()) { + Some(RawWindowHandle::Wayland(_)) => "Wayland", + Some(RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) => "X11", + Some(RawWindowHandle::AppKit(_)) => "AppKit", + Some(RawWindowHandle::Win32(_)) => "Win32", + Some(_) => "other", + None => "unknown", + } +} + +/// The present mode and frame queue the app asked the window surface for, for [`Facts::surface`]; +/// `None` when the window has no wgpu renderer. +pub fn surface(config: Option<(String, Option)>) -> String { + match config { + Some((mode, Some(frames))) => format!("requested present mode {mode}, frame latency {frames}"), + Some((mode, None)) => format!("requested present mode {mode}"), + None => "no wgpu renderer".to_string(), + } +} + +/// Start the watching thread; the report file goes in `dir` (none: the log only). +pub fn start(dir: Option, shared: Arc) { + let spawned = std::thread::Builder::new().name("hang-watch".into()).spawn(move || { + let mut watch = Watch::new(STALL); + let mut held = None; + loop { + std::thread::sleep(POLL); + #[cfg_attr(not(target_os = "macos"), allow(unused_mut))] + let mut sample = BEACON.sample(); + // An open menu of the menu bar waits for the user. + #[cfg(target_os = "macos")] + if super::mac_menu::is_tracking() { + sample.activity = Activity::Menu; + } + if let Some(event) = watch.check(shared.started.elapsed(), sample) { + record(event, sample, &BEACON, &shared, dir.as_deref(), &mut held, &CLOSING, SystemTime::now()); + } + } + }); + if let Err(e) = spawned { + log::warn!("no hang report this session: the watching thread didn't start: {e}"); + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/vectorcraft/src/hang_watch/tests.rs b/apps/vectorcraft/src/hang_watch/tests.rs new file mode 100644 index 0000000000..09cf74e403 --- /dev/null +++ b/apps/vectorcraft/src/hang_watch/tests.rs @@ -0,0 +1,270 @@ +use super::*; +use std::time::UNIX_EPOCH; +use vectorcraft_ui_egui::hang_beacon::{Activity, Stage}; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn sample(step: u64, stage: Stage) -> Sample { + Sample { step, stage, activity: Activity::None } +} + +fn facts() -> Facts { + let env = |name: &str| match name { + "XDG_CURRENT_DESKTOP" => Some("KDE".to_string()), + "XDG_SESSION_TYPE" => Some("wayland\u{7}".to_string()), + _ => None, + }; + Facts::new(env, true, "Wayland", Some("Test GPU (Vulkan, DiscreteGpu)".to_string()), surface(Some(("AutoVsync".to_string(), Some(1))))) +} + +fn shared(previous: Option) -> Shared { + Shared { facts: facts(), started: Instant::now(), last: Mutex::new(None), previous } +} + +#[test] +fn a_stage_held_for_the_stall_time_is_reported_once_and_its_end_after_it() { + let mut w = Watch::new(STALL); + assert_eq!(w.check(ms(0), sample(5, Stage::Interface)), None); + assert_eq!(w.check(ms(2_999), sample(5, Stage::Interface)), None); + assert_eq!(w.check(ms(3_000), sample(5, Stage::Interface)), Some(Event::Stalled(ms(3_000)))); + assert_eq!(w.check(ms(9_000), sample(5, Stage::Interface)), None); + assert_eq!(w.check(ms(9_500), sample(6, Stage::Idle)), Some(Event::Answered(ms(9_500)))); + assert_eq!(w.check(ms(20_000), sample(6, Stage::Idle)), None); +} + +#[test] +fn frames_that_keep_moving_and_an_idle_window_are_never_reported() { + let mut w = Watch::new(STALL); + // A long animation: the step changes at every read. + for n in 0..100 { + assert_eq!(w.check(ms(n * 500), sample(n, Stage::Drawing)), None); + } + // A window waiting for input for a minute. + for n in 0..120 { + assert_eq!(w.check(ms(50_000 + n * 500), sample(1_000, Stage::Idle)), None); + } +} + +#[test] +fn a_file_dialog_shown_in_line_is_waiting_for_the_user_not_stalled() { + let mut w = Watch::new(STALL); + let dialog = Sample { step: 7, stage: Stage::Interface, activity: Activity::Dialog }; + for n in 0..60 { + assert_eq!(w.check(ms(n * 500), dialog), None); + } + // Back from the dialog, the command goes on and is timed again. + assert_eq!(w.check(ms(30_000), sample(8, Stage::Interface)), None); + assert_eq!(w.check(ms(33_000), sample(8, Stage::Interface)), Some(Event::Stalled(ms(3_000)))); +} + +#[test] +fn an_open_menu_bar_menu_is_waiting_for_the_user_not_stalled() { + let mut w = Watch::new(STALL); + let menu = Sample { step: 3, stage: Stage::Drawing, activity: Activity::Menu }; + for n in 0..60 { + assert_eq!(w.check(ms(n * 500), menu), None); + } +} + +#[test] +fn a_new_busy_step_starts_the_time_again() { + let mut w = Watch::new(STALL); + assert_eq!(w.check(ms(0), sample(1, Stage::Logic)), None); + assert_eq!(w.check(ms(2_500), sample(2, Stage::Interface)), None); + assert_eq!(w.check(ms(5_000), sample(2, Stage::Interface)), None); + assert_eq!(w.check(ms(5_500), sample(2, Stage::Interface)), Some(Event::Stalled(ms(3_000)))); + // A mark inside the stall (a clipboard read ending) is an answer. + assert_eq!(w.check(ms(6_000), sample(3, Stage::Interface)), Some(Event::Answered(ms(3_500)))); +} + +#[test] +fn the_report_names_the_stage_the_activity_the_commands_and_the_platform() { + let beacon = Beacon::new(); + beacon.command("edit.copy"); + beacon.command("edit.paste"); + beacon.frame(FrameTime { work_ms: 1.24, previous_total_ms: Some(3.5) }, 2); + let s = Sample { step: 9, stage: Stage::Interface, activity: Activity::ClipboardRead }; + let text = report(UNIX_EPOCH + Duration::from_secs(1_794_385_145), ms(3_240), s, &beacon, Duration::from_secs(754), &facts()); + for want in [ + "VectorCraft hang report, 2026-11-11T08:19:05.000Z", + "has not moved on for 3.2 s", + "Stage: running the interface", + "Waiting on: reading the system clipboard", + "Recent commands, oldest first: edit.copy, edit.paste", + "App work per frame (ms), oldest first: 1.2", + "without waiting for the display (ms), oldest first: 3.5", + "Session: running for 754 s, 2 documents open", + "Window system: Wayland; desktop: KDE; session type: wayland; Flatpak: yes", + "Graphics: Test GPU (Vulkan, DiscreteGpu); requested present mode AutoVsync, frame latency 1", + ] { + assert!(text.contains(want), "{want:?} missing from:\n{text}"); + } +} + +#[test] +fn environment_values_lose_control_characters_and_are_cut_short() { + let long = "x".repeat(500); + let env = |name: &str| (name == "XDG_CURRENT_DESKTOP").then(|| format!("A\nB{long}")); + let f = Facts::new(env, false, "X11", None, String::new()); + assert_eq!(f.desktop.as_deref().map(str::len), Some(MAX_VALUE_CHARS)); + assert!(f.desktop.as_deref().is_some_and(|d| d.starts_with("ABx"))); + assert!(!f.flatpak); + assert!(f.lines().contains("Graphics: unknown")); +} + +#[test] +fn a_stall_writes_the_report_file_and_its_end_removes_it() { + let dir = tempfile::tempdir().unwrap(); + let shared = shared(None); + let beacon = Beacon::new(); + let s = sample(4, Stage::Drawing); + let (mut held, open) = (None, AtomicBool::new(false)); + record(Event::Stalled(ms(3_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH); + let path = report_path(dir.path()); + // Windows refuses reads through another handle while the file is locked: the length is read. + let last = shared.last.lock().unwrap().clone().unwrap_or_default(); + assert!(last.contains("Stage: after a frame with input went to the renderer")); + assert_eq!(std::fs::metadata(&path).unwrap().len(), last.len() as u64); + // While the stall lasts, a launch of another instance leaves the file alone. + assert_eq!(take_previous(dir.path()), None); + assert!(path.exists()); + record(Event::Answered(ms(4_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH); + assert!(!path.exists()); + // This session's report stays for Copy Troubleshooting Info. + assert!(shared.last.lock().unwrap().is_some()); +} + +#[test] +fn closing_normally_removes_the_report_and_writes_no_more() { + let dir = tempfile::tempdir().unwrap(); + let shared = shared(None); + let beacon = Beacon::new(); + let (mut held, flag) = (None, AtomicBool::new(false)); + record(Event::Stalled(ms(3_000)), sample(4, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH); + let path = report_path(dir.path()); + assert!(path.exists()); + // The interface answered after a frame with input, and the app quit before the watching thread + // looked again: saving and teardown are not timed. + beacon.enter(Stage::Drawing); + closing(Some(dir.path()), &flag, &beacon); + assert_eq!(beacon.sample().stage, Stage::Idle); + assert!(!path.exists()); + assert_eq!(take_previous(dir.path()), None); + // The watching thread then sees the answer. + record(Event::Answered(ms(3_500)), sample(5, Stage::Idle), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH); + assert!(held.is_none()); + // A stall the watching thread finds while the app closes goes to the log only. + record(Event::Stalled(ms(3_000)), sample(9, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH); + assert!(!path.exists()); + assert!(held.is_none()); +} + +#[test] +fn the_next_launch_takes_a_left_report_once_and_keeps_a_copy() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(take_previous(dir.path()), None); + let left = dir.path().join(format!("{REPORT_PREFIX}4242.txt")); + std::fs::write(&left, "VectorCraft hang report, then\n").unwrap(); + // Other files in the log folder are not reports. + std::fs::write(dir.path().join(format!("{REPORT_PREFIX}notes.txt")), "x").unwrap(); + std::fs::write(dir.path().join(format!("{REPORT_PREFIX}17.txt")), "").unwrap(); + assert_eq!(take_previous(dir.path()).as_deref(), Some("VectorCraft hang report, then\n")); + assert!(!left.exists()); + assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "VectorCraft hang report, then\n"); + assert_eq!(take_previous(dir.path()), None); + // An empty file may be one being written: it stays. + assert!(dir.path().join(format!("{REPORT_PREFIX}17.txt")).exists()); +} + +#[test] +fn of_several_left_reports_the_newest_is_kept_and_all_are_offered_oldest_first() { + let dir = tempfile::tempdir().unwrap(); + for (pid, text, secs) in [(9, "newer\n", 2_000), (10, "older\n", 1_000)] { + let path = dir.path().join(format!("{REPORT_PREFIX}{pid}.txt")); + std::fs::write(&path, text).unwrap(); + let file = std::fs::File::options().write(true).open(&path).unwrap(); + file.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap(); + } + assert_eq!(take_previous(dir.path()).as_deref(), Some("older\n\nnewer\n")); + assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "newer\n"); +} + +#[test] +fn a_report_that_cannot_be_moved_is_offered_once() { + let dir = tempfile::tempdir().unwrap(); + // Something that is not a file is in the way. + std::fs::create_dir_all(dir.path().join(PREVIOUS_FILE).join("x")).unwrap(); + let left = dir.path().join(format!("{REPORT_PREFIX}5.txt")); + std::fs::write(&left, "kept\n").unwrap(); + assert_eq!(take_previous(dir.path()).as_deref(), Some("kept\n")); + assert!(!left.exists()); + assert_eq!(take_previous(dir.path()), None); +} + +#[test] +fn reports_beyond_the_newest_are_removed_not_left_for_a_later_launch() { + let dir = tempfile::tempdir().unwrap(); + let count = MAX_REPORT_FILES + 3; + for n in 0..count { + let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n)); + std::fs::write(&path, format!("report {n}\n")).unwrap(); + let file = std::fs::File::options().write(true).open(&path).unwrap(); + file.set_modified(UNIX_EPOCH + Duration::from_secs(1_000 + n as u64)).unwrap(); + } + let text = take_previous(dir.path()).unwrap(); + assert!(text.starts_with("report 3\n"), "{text}"); + assert!(text.ends_with(&format!("report {}\n", count - 1)), "{text}"); + assert!(!text.contains("report 2\n")); + assert_eq!(take_previous(dir.path()), None); + let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect(); + assert_eq!(left, vec![std::ffi::OsString::from(PREVIOUS_FILE)]); +} + +#[test] +fn newer_empty_files_do_not_push_out_an_abandoned_report() { + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join(format!("{REPORT_PREFIX}1.txt")); + std::fs::write(&old, "old\n").unwrap(); + std::fs::File::options().write(true).open(&old).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(1_000)).unwrap(); + for n in 0..MAX_REPORT_FILES + 1 { + let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n)); + std::fs::write(&path, "").unwrap(); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(2_000)).unwrap(); + } + assert_eq!(take_previous(dir.path()).as_deref(), Some("old\n")); +} + +#[test] +fn a_file_system_without_locks_does_not_hide_a_report() { + use std::io::{Error, ErrorKind}; + assert!(abandoned(Ok(()))); + assert!(!abandoned(Err(std::fs::TryLockError::WouldBlock))); + assert!(abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::Unsupported))))); + // Any other error may hide a live session's lock: the file is left alone. + assert!(!abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::PermissionDenied))))); +} + +#[test] +fn an_oversized_report_file_is_not_read() { + let dir = tempfile::tempdir().unwrap(); + let big = vec![b'x'; usize::try_from(MAX_REPORT_BYTES).unwrap() + 1]; + let left = dir.path().join(format!("{REPORT_PREFIX}7.txt")); + std::fs::write(&left, big).unwrap(); + let text = take_previous(dir.path()).unwrap(); + assert!(text.starts_with("The report was larger than")); + assert!(!left.exists()); +} + +#[test] +fn troubleshooting_info_holds_both_sessions_reports() { + let shared = shared(Some("VectorCraft hang report, last session\n".to_string())); + *shared.last.lock().unwrap() = Some("VectorCraft hang report, this session\n".to_string()); + let beacon = Beacon::new(); + let text = troubleshooting(&shared, &beacon, UNIX_EPOCH); + assert!(text.starts_with("VectorCraft troubleshooting info, 1970-01-01T00:00:00.000Z\n")); + assert!(text.contains("This session's last hang report:\nVectorCraft hang report, this session\n")); + assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n")); + assert!(text.contains("Recent commands, oldest first: none")); +} diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 187c42cde7..72d13db08f 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -120,7 +120,6 @@ fn make_folder(request: &PickRequest) { #[cfg(not(target_os = "macos"))] #[cfg_attr(windows, allow(unused_variables))] fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec { - make_folder(request); #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] if let PickRequest::Save(pick) = request && let Some(answer) = portal_save::pick(pick, parent.as_deref()) @@ -139,7 +138,30 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) /// Show the dialog for `request` over `parent` now → the paths picked. #[cfg(not(target_os = "macos"))] fn pick_now(request: PickRequest, parent: &Parent) -> Vec { - show_dialog(file_dialog(&request, parent), &request, parent) + let beacon = &vectorcraft_ui_egui::hang_beacon::BEACON; + marked_dialog(beacon, || make_folder(&request), || show_dialog(file_dialog(&request, parent), &request, parent)) +} + +/// Run `prepare` (making the dialog's folder), then `show`, marked on `beacon` as a dialog: the +/// dialog waits for the user and is not a stall for the hang report (`hang_watch`), while `prepare` +/// is still timed. +#[cfg(not(target_os = "macos"))] +fn marked_dialog(beacon: &vectorcraft_ui_egui::hang_beacon::Beacon, prepare: impl FnOnce(), show: impl FnOnce() -> T) -> T { + prepare(); + let _mark = beacon.activity(vectorcraft_ui_egui::hang_beacon::Activity::Dialog); + show() +} + +#[cfg(all(test, not(target_os = "macos")))] +#[test] +fn making_a_dialogs_folder_is_timed_and_the_dialog_is_not() { + use vectorcraft_ui_egui::hang_beacon::{Activity, Beacon}; + let beacon = Beacon::new(); + let mut preparing = None; + let showing = marked_dialog(&beacon, || preparing = Some(beacon.sample().activity), || beacon.sample().activity); + assert_eq!(preparing, Some(Activity::None), "making the folder is timed"); + assert_eq!(showing, Activity::Dialog, "the dialog is not"); + assert_eq!(beacon.sample().activity, Activity::None, "the mark ends with the dialog"); } /// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an @@ -239,6 +261,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti std::thread::Builder::new() .name("file-dialog".into()) .spawn(move || { + make_folder(&request); // The app gone meanwhile has no use for the answer. let _ = tx.send(show_dialog(dialog, &request, &parent)); ui.request_repaint(); @@ -355,7 +378,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // 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())), + exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())), // Background Save and Export write from a worker thread. write_shared: Some(std::sync::Arc::new(write_file)), // Native saves stream into the file as they are encoded. @@ -363,7 +386,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { fileio::write_file_with(p, fill).map_err(|e| e.to_string()) })), // Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event). - system_clipboard: Some(clipboard::system_clipboard(clip)), + // Its calls are marked for the hang report (`hang_watch`). + system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))), // Linux checks whether Paste has something to take on a background thread: an X11 clipboard // owner that never answers holds a read for up to 4 s. Windows only asks which formats the // clipboard holds and macOS asks the pasteboard server, so they check in line. diff --git a/apps/vectorcraft/src/mac_menu.rs b/apps/vectorcraft/src/mac_menu.rs index f90e4f7304..53b610a210 100644 --- a/apps/vectorcraft/src/mac_menu.rs +++ b/apps/vectorcraft/src/mac_menu.rs @@ -30,6 +30,9 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole, // AppKit can deliver window input while its system menu is still tracking (especially with // asynchronous menu presentation). Keep the native tracking state separate from egui popups. static TRACKING: AtomicBool = AtomicBool::new(false); +/// A tracking session began since the last [`Backend::drain`], which reports it as +/// [`Event::Opened`]. +static OPENED: AtomicBool = AtomicBool::new(false); pub(crate) fn is_tracking() -> bool { TRACKING.load(Ordering::Relaxed) @@ -46,9 +49,11 @@ fn observe_tracking(ctx: &egui::Context) { let block = RcBlock::new(move |_: std::ptr::NonNull| { TRACKING.store(tracking, Ordering::Relaxed); if tracking { + OPENED.store(true, Ordering::Relaxed); super::mac_cursor::release(); } - // Apply any deferred menu updates as soon as the tracking session ends. + // Report the opened menu and apply any deferred menu updates as soon as the + // tracking session ends. if !tracking { repaint.request_repaint(); } @@ -267,6 +272,9 @@ impl Backend for MacMenu { fn drain(&mut self) -> Vec { let mut out = Vec::new(); + if OPENED.swap(false, Ordering::Relaxed) { + out.push(Event::Opened); + } while let Ok(chosen) = self.rx.try_recv() { cancel_tracking(); // Ids that aren't ours are AppKit's own items (Services, Zoom…), already handled. diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index bb94bad1cc..33e03b1f72 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -30,6 +30,7 @@ mod control_server; mod cursor_theme; #[cfg(feature = "wgpu")] mod gpu; +mod hang_watch; #[cfg(target_os = "linux")] mod linux_stylus; mod logging; @@ -123,6 +124,8 @@ struct App { held_files: Vec, /// The time and UI zoom of the last monitor list ([`window::monitors_due`]). monitors_listed: Option<(f64, f32)>, + /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). + frame_start: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -293,6 +296,11 @@ fn main() -> std::process::ExitCode { None => logger.no_file(), } } + // The report a session left when it was closed while it did not answer (`hang_watch`). + let previous_hang = log_dir().filter(|_| prefs_enabled()).and_then(|dir| hang_watch::take_previous(&dir)); + if let Some(report) = &previous_hang { + log::warn!("the last session was closed while it did not answer; its report:\n{}", report.trim_end()); + } // The roots confine the control channel: a bad one keeps the app from starting rather than // leaving agents unconfined. Without a control port there is nothing to confine. let roots = if control_port.is_none() { @@ -437,6 +445,9 @@ fn main() -> std::process::ExitCode { open_documents::install(); #[cfg(feature = "wgpu")] let created = startup.clone(); + // For the hang report (`hang_watch`). + #[cfg(feature = "wgpu")] + let requested_surface = options.wgpu_options.surface; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -537,6 +548,36 @@ fn main() -> std::process::ExitCode { let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone()); rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}"))); } + // The hang report and Help › Copy Troubleshooting Info (`hang_watch`). + // The surface settings the options asked for; the driver resolves the present mode. + #[cfg(feature = "wgpu")] + let surface = cc + .wgpu_render_state + .as_ref() + .map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency)); + #[cfg(not(feature = "wgpu"))] + let surface = None; + let hang = std::sync::Arc::new(hang_watch::Shared { + facts: hang_watch::Facts::new( + |name| std::env::var(name).ok(), + std::path::Path::new("/.flatpak-info").exists(), + hang_watch::window_system(winit_window.as_deref()), + app.graphics_adapter.clone(), + hang_watch::surface(surface), + ), + started: std::time::Instant::now(), + last: std::sync::Mutex::new(None), + previous: previous_hang.clone(), + }); + vectorcraft_ui_egui::hang_beacon::watch_input(&vectorcraft_ui_egui::hang_beacon::BEACON, &cc.egui_ctx); + hang_watch::start(log_dir().filter(|_| prefs_enabled()), hang.clone()); + app.services.troubleshooting = Some(Box::new(move || { + hang_watch::troubleshooting(&hang, &vectorcraft_ui_egui::hang_beacon::BEACON, std::time::SystemTime::now()) + })); + // A message about the graphics processor, or a stopped plug-in, comes first. + if previous_hang.is_some() && app.ui.status.is_empty() { + vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app); + } app.titlebar_from_env = titlebar_from_env(); app.custom_titlebar = custom_titlebar; app.desktop_frame = !custom_titlebar; @@ -583,6 +624,7 @@ fn main() -> std::process::ExitCode { maximize_tries: 8, held_files, monitors_listed: None, + frame_start: None, })) }), ) diff --git a/apps/vectorcraft/tests/it/automation_args.rs b/apps/vectorcraft/tests/it/automation_args.rs index 93b33fa16d..4a1e6f524c 100644 --- a/apps/vectorcraft/tests/it/automation_args.rs +++ b/apps/vectorcraft/tests/it/automation_args.rs @@ -1,8 +1,6 @@ use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft"); - /// Invalid roots must exit before desktop initialization on every platform, including a CI /// machine with no display. A regression must fail rather than hang with a window open. fn rejects(args: &[&str], message: &str) { @@ -10,7 +8,7 @@ fn rejects(args: &[&str], message: &str) { } fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(args) .env_remove("VECTORCRAFT_CONTROL_PORT") .env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT") @@ -62,7 +60,7 @@ fn missing_empty_or_option_operands_fail_before_startup() { #[test] fn repeated_roots_are_accepted_for_both_spellings() { for flag in ["--automation-read-root", "--automation-write-root"] { - let out = Command::new(BIN).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap(); + let out = Command::new(crate::bin()).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap(); assert!(out.status.success(), "{flag}: {}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION"))); assert!(out.stderr.is_empty()); @@ -73,7 +71,8 @@ fn repeated_roots_are_accepted_for_both_spellings() { #[test] fn explicit_dash_folder_does_not_consume_version() { - let out = Command::new(BIN).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap(); + let out = + Command::new(crate::bin()).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION"))); assert!(out.stderr.is_empty()); @@ -95,7 +94,7 @@ fn control_without_a_valid_port_fails_before_startup() { #[test] fn version_wins_over_a_bad_control_port_variable() { - let out = Command::new(BIN).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap(); + let out = Command::new(crate::bin()).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION"))); } diff --git a/apps/vectorcraft/tests/it/help.rs b/apps/vectorcraft/tests/it/help.rs index ece66b98ab..d82475b9ff 100644 --- a/apps/vectorcraft/tests/it/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -6,12 +6,10 @@ use std::process::{Command, Output, Stdio}; use std::sync::mpsc; use std::time::{Duration, Instant}; -const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft"); - /// Runs the desktop binary without a display and with a control port it cannot parse, so a /// regression exits with that error instead of opening a window. fn run(args: &[&str], env: &[(&str, &str)]) -> Output { - let mut child = Command::new(BIN) + let mut child = Command::new(crate::bin()) .args(args) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") diff --git a/apps/vectorcraft/tests/it/main.rs b/apps/vectorcraft/tests/it/main.rs index d9dcf39cbb..658f4d49f6 100644 --- a/apps/vectorcraft/tests/it/main.rs +++ b/apps/vectorcraft/tests/it/main.rs @@ -4,3 +4,11 @@ mod automation_args; mod help; + +/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner. +fn bin() -> std::path::PathBuf { + std::env::var_os("NEXTEST_BIN_EXE_vectorcraft") + .or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft")) + .map(std::path::PathBuf::from) + .unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into()) +} diff --git a/assets/icons/dc-grad-conic.svg b/assets/icons/dc-grad-conic.svg new file mode 100644 index 0000000000..f6e49150be --- /dev/null +++ b/assets/icons/dc-grad-conic.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-grad-diamond.svg b/assets/icons/dc-grad-diamond.svg new file mode 100644 index 0000000000..2efeca27e9 --- /dev/null +++ b/assets/icons/dc-grad-diamond.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/graduation-cap.svg b/assets/icons/graduation-cap.svg new file mode 100644 index 0000000000..fbce25edcc --- /dev/null +++ b/assets/icons/graduation-cap.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index c335c7b16c..798b0734f5 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-affinity" -description = "Bounded reader for native Affinity documents: archive, object stream and document model" +description = "craft-affinity under its old name, for the corpus tests and fuzz targets" version.workspace = true edition.workspace = true license.workspace = true @@ -11,13 +11,13 @@ workspace = true [features] # Synthetic-container builders for tests and fuzz seeds; not an Affinity exporter. -synth = [] +synth = ["craft-affinity/synth"] [dependencies] -crc32fast = { workspace = true } -flate2 = { workspace = true } -image = { workspace = true } -ruzstd = "0.9.1" +craft-affinity = { workspace = true } [dev-dependencies] proptest = { workspace = true } +# The tests build containers and decode previews. +crc32fast = { workspace = true } +image = { workspace = true } diff --git a/crates/affinity/README.md b/crates/affinity/README.md index fd2d6dc71a..38c096cbcc 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -1,5 +1,7 @@ # vectorcraft-affinity +The reader is [`craft-affinity`](https://github.com/storytold/craft-libs/tree/main/crates/affinity) in craft-libs; this crate re-exports it under its old name for the corpus tests and fuzz targets. The engine maps its document onto VectorCraft art (`crates/engine/src/cmd/fileio/affinity`), as described below. + An independent, bounded Rust reader for native Affinity documents: `.af` from Affinity 3 and `.afdesign`, `.afphoto` and `.afpub` from Affinity 1 and 2 (container versions 8 to 12). It reads the archive, the tagged object stream in `doc.dat` and the part of the document model listed below, @@ -35,7 +37,7 @@ Affinity files. Everything else is reported in the import warnings, one line per kind with a count, never dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold, -transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial), +transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than round or straight, stars with rounded points, several fills or strokes on one object (the active one is used), skewed or flipped text, characters of different transparency in one text, text fields such as page numbers, text threading, frames with diff --git a/crates/affinity/src/access.rs b/crates/affinity/src/access.rs deleted file mode 100644 index 0b60ed7dbd..0000000000 --- a/crates/affinity/src/access.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Typed reads of [`Stream`] objects. Every accessor returns `None` when a field is missing or has -//! another type, so the document mapping treats odd data as absent rather than failing. - -use crate::stream::{ObjId, Object, Stream, Tag, Value}; - -impl Stream { - pub fn object(&self, id: ObjId) -> Option<&Object> { - self.objects.get(id) - } - - pub fn field(&self, id: ObjId, tag: &[u8; 4]) -> Option<&Value> { - self.object(id)?.get(Tag::of(tag)) - } - - pub fn class(&self, id: ObjId) -> Option { - self.object(id).map(|o| o.class) - } - - pub fn is(&self, id: ObjId, class: &[u8; 4]) -> bool { - self.class(id) == Some(Tag::of(class)) - } - - /// A child object (shared, linked or inline); `None` for null or missing. - pub fn obj(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Obj(o) => *o, - _ => None, - } - } - - /// An array of objects (nulls skipped). - pub fn objs(&self, id: ObjId, tag: &[u8; 4]) -> Vec { - match self.field(id, tag) { - Some(Value::Array(a)) => a.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }).collect(), - _ => Vec::new(), - } - } - - pub fn f64(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Float(f) if f.is_finite() => Some(*f), - _ => None, - } - } - - pub fn int(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Int(i) => Some(*i), - Value::UInt(u) => i64::try_from(*u).ok(), - _ => None, - } - } - - pub fn bool(&self, id: ObjId, tag: &[u8; 4]) -> Option { - match self.field(id, tag)? { - Value::Bool(b) => Some(*b), - _ => None, - } - } - - pub fn str(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> { - match self.field(id, tag)? { - Value::Str(s) => Some(s), - _ => None, - } - } - - pub fn enumeration(&self, id: ObjId, tag: &[u8; 4]) -> Option<(u16, u16)> { - match self.field(id, tag)? { - Value::Enum { id, version } => Some((*id, *version)), - _ => None, - } - } - - /// A fixed vector of `N` finite floats (points, rectangles, transforms). - pub fn floats(&self, id: ObjId, tag: &[u8; 4]) -> Option<[f64; N]> { - match self.field(id, tag)? { - Value::Floats(v) if v.len() == N && v.iter().all(|f| f.is_finite()) => { - let mut a = [0.0; N]; - a.copy_from_slice(v); - Some(a) - } - _ => None, - } - } - - pub fn bytes(&self, id: ObjId, tag: &[u8; 4]) -> Option<&[u8]> { - match self.field(id, tag)? { - Value::Bytes(b) | Value::Blob(b) => Some(b), - _ => None, - } - } - - pub fn entry(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> { - match self.field(id, tag)? { - Value::Entry(s) => Some(s), - _ => None, - } - } - - /// Untagged fields of a positional object, in order. - pub fn positional(&self, id: ObjId) -> impl Iterator { - self.object(id).into_iter().flat_map(|o| o.fields.iter().map(|(_, v)| v)) - } -} diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs deleted file mode 100644 index f26948e919..0000000000 --- a/crates/affinity/src/container.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! The Affinity archive: header, the chain of file allocation tables (one per save) and -//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles. - -use std::collections::{HashMap, HashSet}; -use std::io::Read; - -use crate::Error; - -pub const MAGIC: &[u8; 4] = b"\x00\xffKA"; -/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8, -/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists. -pub const VERSIONS: std::ops::RangeInclusive = 8..=12; -/// `Prsn` (stored byte-reversed): documents. Asset, brush and style libraries share the magic. -const DOCUMENT_KIND: &[u8; 4] = b"nsrP"; - -/// A save appends one table; real files have one to a few hundred. -const MAX_TABLES: usize = 4096; -/// Allocation records read over the whole table chain. Each save lists every entry again, so a -/// document with a few hundred saves of a few thousand entries stays far below; tables whose -/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work. -const MAX_INDEX_RECORDS: usize = 1 << 22; -/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name). -/// Real names (`doc.dat`, `d/12`) are a few bytes each. -const MAX_INDEX_NAME_BYTES: usize = 16 << 20; -/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes. -const MAX_ZSTD_WINDOW: u64 = 64 << 20; - -/// Decompression budget for one import. Every entry declares its size, which is checked against -/// these limits before anything is allocated, and the decoded length must match it exactly. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Limits { - /// Largest single entry (`doc.dat` or one tile). - pub max_entry: usize, - /// Total bytes extracted over the whole import. - pub max_total: usize, -} - -impl Default for Limits { - fn default() -> Self { - Self { max_entry: 256 << 20, max_total: 1 << 30 } - } -} - -/// The container header, all integers little-endian. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Header { - pub version: u16, - /// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected. - pub flags: u16, - pub(crate) fat_offset: u64, - pub(crate) thumbnail_offset: u64, - /// Save time in Unix seconds, as written by the application. - pub saved: u32, -} - -/// One FAT record, as of the newest table that mentions its id. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Entry { - pub id: u32, - pub name: String, - offset: u64, - size: u64, - compressed: u64, - crc: u32, - compression: u8, -} - -impl Entry { - /// Decompressed size declared by the table. - pub fn size(&self) -> u64 { - self.size - } -} - -#[derive(Debug)] -pub struct Archive<'a> { - bytes: &'a [u8], - pub header: Header, - /// Head revision of every named, non-deleted entry. - entries: HashMap, - /// Number of tables (saves) in the chain. - pub revisions: usize, - extracted: usize, - limits: Limits, - /// Entries whose extraction failed after their size was charged: asked again, they fail - /// again without being decompressed again. - failed: HashMap, -} - -pub(crate) struct Cursor<'a> { - bytes: &'a [u8], - pub(crate) pos: usize, -} - -impl<'a> Cursor<'a> { - pub(crate) fn new(bytes: &'a [u8], pos: usize) -> Self { - Self { bytes, pos } - } - pub(crate) fn remaining(&self) -> usize { - self.bytes.len().saturating_sub(self.pos) - } - pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Error> { - let end = self.pos.checked_add(n).ok_or(Error::Malformed("length overflow"))?; - let s = self.bytes.get(self.pos..end).ok_or(Error::Malformed("truncated data"))?; - self.pos = end; - Ok(s) - } - pub(crate) fn array(&mut self) -> Result<[u8; N], Error> { - let s = self.take(N)?; - let mut a = [0u8; N]; - a.copy_from_slice(s); - Ok(a) - } - pub(crate) fn u8(&mut self) -> Result { - Ok(self.array::<1>()?[0]) - } - pub(crate) fn u16(&mut self) -> Result { - Ok(u16::from_le_bytes(self.array()?)) - } - pub(crate) fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.array()?)) - } - pub(crate) fn u64(&mut self) -> Result { - Ok(u64::from_le_bytes(self.array()?)) - } -} - -fn offset(v: u64) -> Result { - usize::try_from(v).map_err(|_| Error::Malformed("offset beyond addressable memory")) -} - -/// True when `bytes` start with the Affinity container signature (documents and libraries). -pub fn is_affinity(bytes: &[u8]) -> bool { - bytes.starts_with(MAGIC) -} - -/// Check the signature, version and document kind. -pub fn header(bytes: &[u8]) -> Result { - if !is_affinity(bytes) { - return Err(Error::Malformed("missing container signature")); - } - let mut c = Cursor::new(bytes, 4); - let version = c.u16()?; - let flags = c.u16()?; - if !VERSIONS.contains(&version) { - return Err(Error::Unsupported("unknown container version")); - } - if flags & 3 != 0 { - return Err(Error::Unsupported("container variant")); - } - if c.take(4)? != DOCUMENT_KIND { - return Err(Error::Unsupported("this Affinity file is a library (assets, brushes or styles), not a document")); - } - if c.take(4)? != b"#Inf" { - return Err(Error::Malformed("missing information header")); - } - let fat_offset = c.u64()?; - let thumbnail_offset = c.u64()?; - c.take(16)?; - let saved = u32::try_from(c.u64()?).unwrap_or(0); - c.take(8)?; - if c.take(4)? != b"Prot" { - return Err(Error::Malformed("missing protocol header")); - } - Ok(Header { version, flags, fat_offset, thumbnail_offset, saved }) -} - -impl<'a> Archive<'a> { - pub fn open(bytes: &'a [u8], limits: Limits) -> Result { - Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES) - } - - /// [`Archive::open`] reading at most `max_records` allocation records and keeping at most - /// `max_name_bytes` bytes of entry names, both over the whole table chain. - pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result { - let header = header(bytes)?; - let mut records_left = max_records; - let mut name_bytes_left = max_name_bytes; - // Newest record per id: (table date, table index, record). - let mut latest: HashMap)> = HashMap::new(); - let mut names: HashMap = HashMap::new(); - let mut seen = HashSet::new(); - let mut next = header.fat_offset; - let mut tables = 0usize; - while next != 0 { - if !seen.insert(next) { - return Err(Error::Malformed("allocation tables form a cycle")); - } - tables += 1; - if tables > MAX_TABLES { - return Err(Error::Limit("too many saved revisions")); - } - let mut c = Cursor::new(bytes, offset(next)?); - let tag = c.array::<4>()?; - let level = match &tag { - b"#FAT" => 1, - b"#FT2" => 2, - b"#FT3" => 3, - b"#FT4" => 4, - _ => return Err(Error::Malformed("missing allocation table")), - }; - next = c.u64()?; - let date = c.u64()?; - c.take(24)?; - let files = c.u32()?; - c.take(8)?; - let dirs = c.u16()?; - c.take(1)?; - for _ in 0..files { - records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; - let id = c.u32()?; - let flag = c.u8()?; - let mut record = None; - match flag { - 0 | 1 => { - let offset = c.u64()?; - let size = c.u64()?; - let compressed = c.u64()?; - let crc = c.u32()?; - let stored = c.u8()?; - if level >= 2 { - c.take(4)?; - } - if level >= 4 { - c.take(4)?; - } - // Old tables number the methods; newer ones store the method byte itself. - let compression = if level <= 2 { - match stored { - 1 => 0x01, - 2 => 0x41, - 3 => 0x81, - 4 => 0xC1, - _ => 0, - } - } else { - stored - }; - record = Some(Entry { id, name: String::new(), offset, size, compressed, crc, compression }); - } - 2 => {} - _ => return Err(Error::Malformed("unknown allocation record")), - } - if flag == 0 { - let len = usize::from(c.u16()?); - let raw = c.take(len)?; - // Only the first name of an id is kept: later ones are not even decoded. - if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) { - let name = String::from_utf8_lossy(raw); - name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?; - slot.insert(name.into_owned()); - } - } - // Equal dates: the first table in the chain (the newest) wins, as in afread. - let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d); - if replace { - latest.insert(id, (date, tables, record)); - } - } - for _ in 0..dirs { - records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; - let len = usize::from(c.u16()?); - c.take(10)?; - c.take(len)?; - } - } - let mut entries = HashMap::new(); - for (id, (_, _, record)) in latest { - if let (Some(mut e), Some(name)) = (record, names.remove(&id)) { - e.name = name; - entries.insert(e.name.clone(), e); - } - } - Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() }) - } - - pub fn entry(&self, name: &str) -> Option<&Entry> { - self.entries.get(name) - } - - pub fn entry_names(&self) -> impl Iterator { - self.entries.keys().map(String::as_str) - } - - /// Bytes extracted so far, counted against [`Limits::max_total`]. - pub fn extracted(&self) -> usize { - self.extracted - } - - /// Extract an entry by name: decompress, undo the byte predictor and verify the CRC. - /// What is left of the limits for documents embedded in this one. - pub(crate) fn remaining(&self) -> Limits { - Limits { max_entry: self.limits.max_entry, max_total: self.limits.max_total.saturating_sub(self.extracted) } - } - - /// Count `n` bytes extracted elsewhere (from embedded documents) against this import. - pub(crate) fn charge(&mut self, n: usize) -> Result<(), Error> { - let total = self.extracted.checked_add(n).ok_or(Error::Limit("document too large"))?; - if total > self.limits.max_total { - return Err(Error::Limit("document too large")); - } - self.extracted = total; - Ok(()) - } - - pub fn read(&mut self, name: &str) -> Result, Error> { - if let Some(e) = self.failed.get(name) { - return Err(*e); - } - let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?; - let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?; - if size > self.limits.max_entry { - return Err(Error::Limit("archive entry too large")); - } - let total = self.extracted.checked_add(size).ok_or(Error::Limit("document too large"))?; - if total > self.limits.max_total { - return Err(Error::Limit("document too large")); - } - // Charged before the work, and kept when it fails: an entry that fails its checksum - // can't be decompressed over and over for free. - self.extracted = total; - let result = extract(self.bytes, e, size); - if let Err(err) = result { - self.failed.insert(name.to_owned(), err); - } - result - } -} - -/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC. -fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result, Error> { - let mut c = Cursor::new(bytes, offset(e.offset)?); - if c.take(4)? != b"#Fil" { - return Err(Error::Malformed("archive entry has no data block")); - } - let method = e.compression & 3; - let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; - let data = c.take(offset(stored_len)?)?; - let mut out = match method { - 1 => inflate(data, size)?, - 2 => unzstd(data, size)?, - _ => data.to_vec(), - }; - if out.len() != size { - return Err(Error::Malformed("archive entry size mismatch")); - } - unpredict(&mut out, e.compression)?; - if crc32fast::hash(&out) != e.crc { - return Err(Error::Malformed("archive entry checksum mismatch")); - } - Ok(out) -} - -/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught -/// without unbounded allocation. -fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { - let mut out = Vec::with_capacity(size.min(64 << 20)); - let cap = u64::try_from(size).unwrap_or(u64::MAX).saturating_add(1); - r.by_ref().take(cap).read_to_end(&mut out).map_err(|_| Error::Malformed("corrupt compressed entry"))?; - Ok(out) -} - -fn inflate(data: &[u8], size: usize) -> Result, Error> { - read_bounded(flate2::read::ZlibDecoder::new(data), size) -} - -fn unzstd(data: &[u8], size: usize) -> Result, Error> { - let mut src = data; - let mut out = Vec::new(); - // Entries may hold several concatenated frames. - while !src.is_empty() { - let left = size.checked_sub(out.len()).ok_or(Error::Malformed("archive entry size mismatch"))?; - let decoder = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW) - .map_err(|_| Error::Malformed("corrupt compressed entry"))?; - let frame = read_bounded(decoder, left)?; - if frame.is_empty() { - return Err(Error::Malformed("corrupt compressed entry")); - } - out.extend_from_slice(&frame); - if out.len() > size { - return Err(Error::Malformed("archive entry size mismatch")); - } - } - Ok(out) -} - -/// Undo the byte predictor selected by the high bits of the compression byte. -fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> { - match (compression & 0xC0, compression & 0x20 != 0) { - (0x00, _) => {} - (0x40, _) => byte_delta(b), - (0x80, false) => { - let mut prev = 0u16; - for pair in b.as_chunks_mut::<2>().0.iter_mut() { - let v = u16::from_le_bytes([pair[0], pair[1]]).wrapping_add(prev); - pair.copy_from_slice(&v.to_le_bytes()); - prev = v; - } - } - (0x80, true) => { - byte_delta(b); - // A 64 KiB tile of 16-bit samples is stored as all high bytes, then all low bytes. - if b.len() == 0x10000 { - let planes = b.to_vec(); - let (hi, lo) = planes.split_at(0x8000); - for (i, out) in b.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2)) else { - return Err(Error::Malformed("tile size")); - }; - out.copy_from_slice(&[l[0], h[0], l[1], h[1]]); - } - } - } - _ => return Err(Error::Unsupported("archive entry predictor")), - } - Ok(()) -} - -fn byte_delta(b: &mut [u8]) { - let mut prev = 0u8; - for v in b { - *v = v.wrapping_add(prev); - prev = *v; - } -} diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs deleted file mode 100644 index bb1c45746b..0000000000 --- a/crates/affinity/src/geometry.rs +++ /dev/null @@ -1,360 +0,0 @@ -//! Outlines of curves (`PCvD` node lists), parametric shapes (`Shpe` objects) and compounds, in -//! node space. - -use crate::model::{Affine, Path, Point, Reader, SubPath}; -use crate::stream::{ObjId, Tag, Value}; - -/// Nodes per curve object. -const MAX_NODES: usize = 4_000_000; -/// A shared-object stream is bounded, but a compound graph can expand exponentially. Count -/// each visit and each curve record / generated contour / transformed segment across the whole -/// outline, including repeated references. Match the document reader's nesting limit. -const MAX_OUTLINE_DEPTH: usize = 128; -const MAX_OUTLINE_VISITS: usize = 100_000; - -struct OutlineBudget { - active: Vec, - visits: usize, - work: usize, - failed: bool, -} - -impl OutlineBudget { - fn fail(&mut self, r: &mut Reader, warning: &'static str) -> Option<()> { - if !self.failed { - r.warn(warning); - } - self.failed = true; - None - } - - fn spend(&mut self, r: &mut Reader, work: usize) -> Option<()> { - if work > self.work { - return self.fail(r, "compound outlines exceeding the geometry work limit"); - } - self.work -= work; - Some(()) - } - - fn path(&mut self, r: &mut Reader, path: &Path) -> Option<()> { - for subpath in &path.subpaths { - self.spend(r, 1)?; - self.spend(r, subpath.segments.len())?; - } - Some(()) - } -} - -/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd. -/// Instances (master-page or symbol copies) take the geometry of their master. -pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> { - let mut budget = OutlineBudget { active: Vec::new(), visits: MAX_OUTLINE_VISITS, work: MAX_NODES, failed: false }; - bounded_outline(r, id, class, world, &mut budget) -} - -fn bounded_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> { - if budget.active.contains(&id) { - budget.fail(r, "a compound outline that contains itself")?; - } - if budget.active.len() >= MAX_OUTLINE_DEPTH { - budget.fail(r, "compound outlines nested deeper than 128 levels")?; - } - if budget.visits == 0 { - budget.fail(r, "compound outlines exceeding the operand visit limit")?; - } - budget.visits -= 1; - budget.active.push(id); - let result = outline_inner(r, id, class, world, budget); - // The popped value is our own stack marker, and is no longer needed. - let _ = budget.active.pop(); - result -} - -fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> { - let s = r.s; - match &class.0.to_be_bytes() { - b"PCrv" | b"TxtC" => { - let crvs = s.obj(id, b"Crvs").or_else(|| s.obj(id, b"MCrM").and_then(|m| s.obj(m, b"Crvs")))?; - let path = curves(r, crvs, budget)?; - budget.path(r, &path)?; - let multi = path.subpaths.len() > 1; - Some((path, multi)) - } - b"Comp" => { - // One path of all the operands' contours in the compound's space, filled even-odd: this - // matches add and subtract operands in every public sample; a true union of overlapping - // added operands would differ. - let mut path = Path::default(); - for c in s.objs(id, b"Chld") { - let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - let class = s.class(c)?; - if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) { - r.warn("compound shapes that intersect or exclude (imported as add)"); - } - let child_world = local.then(world); - if !child_world.is_finite() { - budget.fail(r, "a compound operand with an invalid transform")?; - } - if let Some((mut p, _)) = bounded_outline(r, c, class, child_world, budget) { - // Charge before transforming or extending. Transform the owned path in place - // so nested compounds do not make an additional copy of every contour. - budget.path(r, &p)?; - for subpath in &mut p.subpaths { - subpath.start = local.apply(subpath.start); - for segment in &mut subpath.segments { - *segment = segment.map(|point| local.apply(point)); - } - } - path.subpaths.extend(p.subpaths); - } else if budget.failed { - // Never present a partial compound as complete after a cycle or budget limit. - return None; - } - } - Some((path, true)) - } - _ => { - let (shape, box_owner) = match s.obj(id, b"Shpe") { - Some(sh) => (sh, id), - None => { - let master = s.obj(id, b"ShpM")?; - (s.obj(master, b"Shpe")?, master) - } - }; - let b = s.floats::<4>(box_owner, b"ShpB")?; - let path = crate::shapes::shape(r, shape, b, world)?; - budget.path(r, &path)?; - Some((path, false)) - } - } -} - -/// `PCvD.Data`: positional `[u8, u32 count, then per subpath: bool closed, 18-byte records]`. -/// A record is (f64 x, f64 y, u8 kind, u8 role): role 0 is an anchor, 1 the out-handle of the -/// anchor before it, 2 the in-handle of the anchor after it. A closed subpath repeats its first -/// anchor at the end. `CnrD` live corners are rounded on the stored polyline. -fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option { - let s = r.s; - let data = s.obj(crvs, b"Data")?; - let mut fields = s.positional(data); - fields.next()?; - let count = match fields.next()? { - Value::UInt(n) => usize::try_from(*n).ok()?, - _ => return None, - }; - budget.spend(r, count)?; - let corners = s.obj(crvs, b"CnrD").and_then(|c| corner_radii(s.positional(c).collect())); - let mut path = Path::default(); - let mut seen = 0usize; - for index in 0..count { - let closed = match fields.next()? { - Value::Bool(b) => *b, - _ => return None, - }; - let Value::Array(records) = fields.next()? else { return None }; - seen = seen.checked_add(records.len())?; - if seen > MAX_NODES { - budget.fail(r, "curves with more than four million nodes")?; - } - budget.spend(r, records.len())?; - let anchors = anchors(records)?; - let radii = if index == 0 { corners.as_ref() } else { None }; - if let Some(sp) = subpath(&anchors, closed, radii) { - path.subpaths.push(sp); - } - } - if corners.is_some() && count > 1 { - r.warn("rounded corners on curves with several subpaths (only the first is rounded)"); - } - Some(path) -} - -/// Most segments a stroke's pressure curve may have; the curves in real documents have a handful. -const MAX_PRESSURE_SEGMENTS: usize = 256; - -/// Most regular samples of a pressure curve: each segment gets an equal share, at least 2 (its -/// middle and its end) and 8 at most. The points where a segment's width stops rising or falling -/// come on top (at most two per segment), so a curve has at most 1 + 4 × [`MAX_PRESSURE_SEGMENTS`] -/// points; the document's limit counts all of them. -const PRESSURE_POINTS: usize = 512; - -/// Most points one pressure curve can have (see [`PRESSURE_POINTS`]). A curve that can't be read -/// counts this many against the document's limit. -pub(crate) const MAX_PRESSURE_CURVE_POINTS: usize = 1 + 4 * MAX_PRESSURE_SEGMENTS; - -/// A stroke's pressure curve (`LDsc.LDeP`, a `CrvD` whose positional `Data` holds an array of -/// 18-byte records as in [`curves`]): x is the position along the path (0 to 1) and y the width as -/// a fraction of the stroke's weight. Each segment is sampled at 2 to 8 points, at most -/// [`PRESSURE_POINTS`] in all, and also where its width stops rising or falling (at most two more -/// points), so a dip between samples is kept → (position, width) in order along the path, -/// positions clamped into 0..1 and never going back, widths clamped into 0..1. `None` when the -/// curve can't be read or has more than [`MAX_PRESSURE_SEGMENTS`] segments. -pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option> { - let s = r.s; - let data = s.obj(crvd, b"Data")?; - let records = s.positional(data).find_map(|v| if let Value::Array(a) = v { Some(a) } else { None })?; - // Every segment takes at least an anchor record. - if records.len() > MAX_PRESSURE_SEGMENTS * 3 + 1 { - return None; - } - let curve = subpath(&anchors(records)?, false, None)?; - if curve.segments.len() > MAX_PRESSURE_SEGMENTS { - return None; - } - let steps = u32::try_from((PRESSURE_POINTS / curve.segments.len().max(1)).clamp(2, 8)).unwrap_or(2); - let mut samples = vec![(curve.start.x, curve.start.y)]; - let mut from = curve.start; - for [c1, c2, to] in &curve.segments { - let mut ts: Vec = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect(); - ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten()); - ts.sort_by(f64::total_cmp); - ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9); - for t in ts { - let u = 1.0 - t; - let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; - samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y))); - } - from = *to; - } - let mut last = 0.0f64; - Some( - samples - .into_iter() - .map(|(x, y)| { - last = x.clamp(last, 1.0); - (last, y.clamp(0.0, 1.0)) - }) - .collect(), - ) -} - -/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`, -/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into -/// -1..1 first, so huge ones can't overflow the discriminant. -fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option; 2] { - let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); - if !(scale.is_finite() && scale > 0.0) { - return [None, None]; - } - let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale); - let (d0, d1, d2) = (b - a, c - b, d - c); - let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); - let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t); - if qa.abs() < 1e-12 { - return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None]; - } - let disc = qb * qb - 4.0 * qa * qc; - if disc < 0.0 { - return [None, None]; - } - let root = disc.sqrt(); - [inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))] -} - -struct Anchor { - p: Point, - inh: Option, - out: Option, - /// Index of the anchor's record (live corners refer to records). - record: usize, -} - -fn record(v: &Value) -> Option<(Point, u8)> { - let Value::Bytes(b) = v else { return None }; - if b.len() != 18 { - return None; - } - let x = f64::from_le_bytes(b.get(0..8)?.try_into().ok()?); - let y = f64::from_le_bytes(b.get(8..16)?.try_into().ok()?); - if !x.is_finite() || !y.is_finite() { - return None; - } - Some((Point { x, y }, *b.get(17)?)) -} - -fn anchors(records: &[Value]) -> Option> { - let mut out: Vec = Vec::with_capacity(records.len() / 3 + 1); - let mut pending_in = None; - for (i, v) in records.iter().enumerate() { - let (p, role) = record(v)?; - match role { - 0 => { - out.push(Anchor { p, inh: pending_in.take(), out: None, record: i }); - } - 1 => { - // A leading out-handle without an anchor is edit state only. - if let Some(a) = out.last_mut() { - a.out = Some(p); - } - } - 2 => pending_in = Some(p), - _ => return None, - } - } - Some(out) -} - -fn subpath(anchors: &[Anchor], closed: bool, radii: Option<&Vec<(usize, f64)>>) -> Option { - let first = anchors.first()?; - if let Some(radii) = radii.filter(|r| !r.is_empty()) { - // The largest radius of each record, once (not a scan of all of them for each anchor). - let mut largest: std::collections::HashMap = std::collections::HashMap::new(); - for (rec, r) in radii { - let e = largest.entry(*rec).or_insert(0.0); - *e = e.max(*r); - } - let corner = |a: &Anchor| largest.get(&a.record).copied().unwrap_or(0.0); - let polyline = anchors.iter().all(|a| a.inh.is_none_or(|h| h == a.p) && a.out.is_none_or(|h| h == a.p)); - if polyline { - let mut pts: Vec<(Point, f64)> = anchors.iter().map(|a| (a.p, corner(a))).collect(); - // A closed subpath repeats its first anchor; its radius may be on either copy. - if closed - && pts.len() > 1 - && pts.first().map(|p| p.0) == pts.last().map(|p| p.0) - && let Some((_, r)) = pts.pop() - && let Some(f) = pts.first_mut() - { - f.1 = f.1.max(r); - } - return Some(crate::shapes::fillet(&pts, closed)); - } - } - let segments = anchors - .windows(2) - .filter_map(|w| { - let [a, b] = w else { return None }; - Some([a.out.unwrap_or(a.p), b.inh.unwrap_or(b.p), b.p]) - }) - .collect(); - Some(SubPath { start: first.p, segments, closed }) -} - -/// `CnrD`: positional `[u8, i32[] record indices, f64[] radii, u8[] types]`. -fn corner_radii(fields: Vec<&Value>) -> Option> { - let (Some(Value::Array(idx)), Some(Value::Array(rad))) = (fields.get(1), fields.get(2)) else { return None }; - Some( - idx.iter() - .zip(rad) - .filter_map(|(i, r)| match (i, r) { - (Value::Int(i), Value::Float(r)) if r.is_finite() && *r > 0.0 => Some((usize::try_from(*i).ok()?, *r)), - _ => None, - }) - .collect(), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn turning_points_of_huge_control_values_are_found() { - let small = turning_points(1.0, -3.0, 3.0, 1.0); - let huge = turning_points(1e200, -3e200, 3e200, 1e200); - assert!(small.iter().all(Option::is_some), "{small:?}"); - for (s, h) in small.iter().zip(&huge) { - let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") }; - assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}"); - } - } -} diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index 38d86a8990..e14c1439a7 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,52 +1,6 @@ -//! Reader for native Affinity documents (`.af`, and `.afdesign`/`.afphoto`/`.afpub` from -//! Affinity 1 and 2): the archive container, the tagged object stream in `doc.dat`, and the -//! subset of the document model VectorCraft imports. -//! -//! Layouts follow the MIT-licensed afread reference and were checked against public documents -//! saved by Affinity 1.x to 3.x (container versions 8 to 12); see the crate README for provenance -//! and the exact supported subset. Nothing here writes Affinity files. +//! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so +//! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use std::fmt; - -mod access; -pub mod container; -mod geometry; -pub mod model; -pub mod overlay; -pub mod paint; -pub mod preview; -mod raster; -mod shapes; -pub mod stream; -#[cfg(any(test, feature = "synth"))] -pub mod synth; -mod text; - -pub use container::{Archive, Limits, MAGIC, is_affinity}; -pub use model::{Document, read}; -pub use preview::{MAX_PREVIEW_BYTES, MAX_PREVIEW_DIMENSION, Preview, preview}; - -/// Why a file could not be read. Messages are short reasons; callers add advice. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Error { - Malformed(&'static str), - Unsupported(&'static str), - Limit(&'static str), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Malformed(s) => write!(f, "damaged Affinity file: {s}"), - Self::Unsupported(s) => write!(f, "unsupported Affinity file: {s}"), - Self::Limit(s) => write!(f, "Affinity file exceeds a safety limit: {s}"), - } - } -} - -impl std::error::Error for Error {} - -#[cfg(test)] -mod tests; +pub use craft_affinity::*; diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs deleted file mode 100644 index a6d18f339e..0000000000 --- a/crates/affinity/src/model.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! The document model the Craft apps import: spreads, artboards, layers, groups, curves, shapes, -//! text and images, with transforms composed into document space. Anything else is reported -//! by [`Document::warnings`] instead of being dropped silently. - -use std::collections::{BTreeMap, HashSet}; - -use crate::paint::{self, Paint, Stroke}; -use crate::stream::{ObjId, Stream, Tag}; -use crate::{Archive, Error, Limits, stream}; - -mod bounds; -mod read; - -pub(crate) use bounds::rect; -pub use bounds::{kind_bounds, nodes_bounds}; -pub(crate) use read::Reader; -pub use read::read; -#[cfg(test)] -pub(crate) use read::read_within; - -/// Affine map `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (kurbo's coefficient order). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Affine(pub [f64; 6]); - -impl Affine { - pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); - - /// Affinity's `Xfrm`, stored row by row: (a, c, e, b, d, f). - pub(crate) fn from_xfrm(m: [f64; 6]) -> Self { - Self([m[0], m[3], m[1], m[4], m[2], m[5]]) - } - - pub fn then(self, outer: Self) -> Self { - let [a, b, c, d, e, f] = self.0; - let [oa, ob, oc, od, oe, of] = outer.0; - Self([oa * a + oc * b, ob * a + od * b, oa * c + oc * d, ob * c + od * d, oa * e + oc * f + oe, ob * e + od * f + of]) - } - - pub fn apply(&self, p: Point) -> Point { - let [a, b, c, d, e, f] = self.0; - Point { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } - } - - /// Geometric mean of the axis scales: how much a stroke width or font size grows. - pub fn scale(&self) -> f64 { - let [a, b, c, d, ..] = self.0; - (a * d - b * c).abs().sqrt() - } - - pub fn is_finite(&self) -> bool { - self.0.iter().all(|v| v.is_finite()) - } -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Point { - pub x: f64, - pub y: f64, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Rect { - pub x0: f64, - pub y0: f64, - pub x1: f64, - pub y1: f64, -} - -/// One cubic Bézier subpath, in document pixels. -#[derive(Debug, Clone, PartialEq)] -pub struct SubPath { - pub start: Point, - /// (control 1, control 2, end) per segment. - pub segments: Vec<[Point; 3]>, - pub closed: bool, -} - -/// An outline in document pixels. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct Path { - pub subpaths: Vec, -} - -impl Path { - pub fn transformed(&self, m: Affine) -> Self { - Self { - subpaths: self - .subpaths - .iter() - .map(|s| SubPath { - start: m.apply(s.start), - segments: s.segments.iter().map(|seg| seg.map(|p| m.apply(p))).collect(), - closed: s.closed, - }) - .collect(), - } - } -} - -/// Affinity's blend modes, numbered by the `Blnd` enum. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Blend { - #[default] - Normal, - PassThrough, - Darken, - DarkerColor, - Multiply, - ColorBurn, - Lighten, - LighterColor, - Screen, - ColorDodge, - Add, - Overlay, - SoftLight, - HardLight, - VividLight, - PinLight, - LinearLight, - HardMix, - Difference, - Exclusion, - Subtract, - Hue, - Saturation, - Luminosity, - Color, - Average, - Negation, - Reflect, - Glow, - Erase, -} - -impl Blend { - /// The enum (id, version) pairs observed in a document whose layers are named after their mode. - fn from_enum(id: u16, version: u16) -> Option { - use Blend::*; - Some(match (id, version) { - (0, _) => Normal, - (1, 0) => Darken, - (2, 1) => DarkerColor, - (2, 0) => Multiply, - (3, 0) => ColorBurn, - (4, 0) => Lighten, - (6, 1) => LighterColor, - (5, 0) => Screen, - (6, 0) => ColorDodge, - (7, 0) => Add, - (8, 0) => Overlay, - (9, 0) => SoftLight, - (10, 0) => HardLight, - (11, 0) => VividLight, - (12, 0) => PinLight, - (15, 1) => LinearLight, - (13, 0) => HardMix, - (14, 0) => Difference, - (15, 0) => Exclusion, - (16, 0) => Subtract, - (17, 0) => Hue, - (18, 0) => Saturation, - (19, 0) => Luminosity, - (20, 0) => Color, - (21, 0) => Average, - (22, 0) => Negation, - (23, 0) => Reflect, - (24, 0) => Glow, - (25, 0) => Erase, - _ => return None, - }) - } -} - -/// A run of text with one set of character attributes. -#[derive(Debug, Clone, PartialEq)] -pub struct TextRun { - pub text: String, - /// PostScript name and family of the chosen font. - pub postscript: String, - pub family: String, - /// CSS weight (400 regular, 700 bold). - pub weight: i64, - pub italic: bool, - /// Boolean OpenType feature overrides, as tags or `-tag` for disabled features. - pub features: Vec, - pub all_caps: bool, - /// Underlined characters (`Ints` slot 0 is 1; identified on underlined words in a document its - /// owner made, all other characters there and in the public corpus have 0). - pub underline: bool, - /// Struck-through characters (`Ints` slot 1 is 1; identified the same way, on prices struck - /// through in another document its owner made). - pub strikethrough: bool, - /// Font size in document pixels, before the node's transform. - pub size: f64, - /// Tracking in em. - pub tracking: f64, - /// Horizontal scale of the glyphs (1 = as designed). - pub h_scale: f64, - /// Fixed line pitch in document pixels, when the run overrides automatic leading. - pub leading: Option, - pub fill: Paint, - /// Outlined characters: the outline's paint and width (node space). - pub stroke: Option, - /// The run's paragraph: alignment, indents and spacing. - pub paragraph: Paragraph, -} - -/// Paragraph alignment, indents, spacing and leading, in node space (document pixels before the -/// node's text scale). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Paragraph { - pub align: Align, - /// Indent of every line but the first, from the left. - pub left: f64, - pub right: f64, - /// Indent of the first line, from the left. - pub first: f64, - pub space_before: f64, - pub space_after: f64, - /// Fixed distance between baselines, when the paragraph sets one. - pub leading: Option, - /// Automatic leading as a multiple of the font's own line height (ascent plus descent). - pub auto_leading: f64, -} - -impl Default for Paragraph { - fn default() -> Self { - Self { align: Align::Left, left: 0.0, right: 0.0, first: 0.0, space_before: 0.0, space_after: 0.0, leading: None, auto_leading: 1.0 } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Align { - #[default] - Left, - Center, - Right, - Justify, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Text { - pub runs: Vec, - pub align: Align, - /// Artistic text: the first baseline's anchor point in node space (start, centre or end of the - /// line according to `align`). Frame text: the frame box in node space. - pub anchor: Point, - pub frame: Option, - /// Node space to document pixels. - pub transform: Affine, - /// Node space to document pixels for the type (its linear part matters): artistic text scales - /// with its node, frame text only with its frame's text scale. - pub text_transform: Affine, -} - -/// Vertical alignment of a table cell's text. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VAlign { - Top, - Center, - Bottom, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct TableCell { - pub runs: Vec, - /// Space between the cell edges and its text, in node space: left, top, right, bottom. - pub inset: [f64; 4], - pub valign: VAlign, - /// Part of the cell to its left (merged): it has no text of its own. - pub merged_left: bool, -} - -/// A table: a grid of cells with text, and a line on every cell edge. -#[derive(Debug, Clone, PartialEq)] -pub struct Table { - /// Column boundaries (one more than the columns), increasing, in node space. - pub columns: Vec, - /// Row boundaries (one more than the rows), increasing, in node space. - pub rows: Vec, - /// Row by row. - pub cells: Vec, - /// Vertical edges row by row, one more per row than the columns; `None` draws no line, and - /// the list is empty when the file's didn't match the grid. - pub vertical: Vec>, - /// Horizontal edges boundary by boundary (one more than the rows), one per column (empty - /// as `vertical` can be). - pub horizontal: Vec>, - /// Node space to document pixels. - pub transform: Affine, - /// Node space to document pixels for the cells' type: resizing a table moves its grid, not - /// its type. - pub text_transform: Affine, -} - -impl Table { - pub fn ncols(&self) -> usize { - self.columns.len().saturating_sub(1) - } - pub fn nrows(&self) -> usize { - self.rows.len().saturating_sub(1) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Pixels { - /// Straight-alpha RGBA, 8 bits per channel, row by row. - Rgba8(Vec), - /// A CMYK pixel layer: cyan, magenta, yellow and black ink amounts (0 none, 255 full) and - /// straight alpha, 8 bits each, row by row. Left in CMYK for the importer to show through a - /// colour profile: the profile-free formula turns the extra cyan of a separation's neutrals - /// into a blue cast. - Cmyka8(Vec), - /// The original file a placed image was made from (PNG, JPEG…), as embedded. - Encoded(Vec), -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Image { - pub width: u32, - pub height: u32, - pub pixels: Pixels, - /// Pixel space (0..w, 0..h) to document pixels. - pub transform: Affine, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Kind { - /// Layer container (`Scop`). - Layer, - Group, - /// Artboard: an export rectangle and vector outline that clips its children. - /// `background` paints behind them, and `strokes` over them. - Artboard { - rect: Rect, - /// Actual clipping outline in document pixels. The artboard's export rectangle is its - /// bounding box, but a rotated or non-rectangular board still clips to this outline. - path: Path, - even_odd: bool, - background: Vec, - strokes: Vec, - }, - /// Curve, parametric shape or compound shape: an outline with its fills and strokes. - /// Children of a shape are clipped by its outline (painted over its fills, under its strokes). - Shape { - path: Path, - fills: Vec, - strokes: Vec, - even_odd: bool, - }, - Text(Text), - Table(Table), - Image(Image), - /// A master page shown on this spread's pages: pages `page..page + count` show the master - /// spread [`Document::masters`]`[master]`'s pages from `master_page` on. - MasterInstance { - master: usize, - page: usize, - master_page: usize, - count: usize, - }, - /// Something this reader does not import; its children are still imported. - Unsupported, -} - -/// A layer effect. Lengths are document pixels; `angle` is the direction the shadow is offset in -/// (radians, clockwise from +x as y points down: π/2 puts it below). -#[derive(Debug, Clone, PartialEq)] -pub enum Effect { - DropShadow { - color: crate::paint::Color, - opacity: f64, - radius: f64, - distance: f64, - angle: f64, - }, - InnerShadow { - color: crate::paint::Color, - opacity: f64, - radius: f64, - distance: f64, - angle: f64, - }, - OuterGlow { - color: crate::paint::Color, - opacity: f64, - radius: f64, - }, - /// An outline of `width` around the node's shape: `align` 0 outside, 1 inside, 2 centred. - Outline { - color: crate::paint::Color, - opacity: f64, - width: f64, - align: u16, - }, - /// Bevel and emboss: lit and shaded edges `size` wide. `angle` is the light's azimuth - /// (radians, counter-clockwise from +x with y up), `depth` Affinity's depth (5 by default); - /// `inner` is false for the outer, emboss and pillow kinds. - Bevel { - size: f64, - depth: f64, - angle: f64, - highlight: crate::paint::Color, - highlight_opacity: f64, - shadow: crate::paint::Color, - shadow_opacity: f64, - inner: bool, - }, - /// Colour overlay: everything the node paints takes `color`, laid over it in `blend` mode at - /// `opacity` (the node's own alpha is kept). - ColorOverlay { - color: crate::paint::Color, - opacity: f64, - blend: Blend, - }, - /// Gradient overlay: a colour overlay whose colour comes from `gradient` (document pixels). - GradientOverlay { - gradient: crate::paint::Gradient, - opacity: f64, - blend: Blend, - }, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Node { - pub class: Tag, - pub name: String, - pub visible: bool, - pub locked: bool, - pub opacity: f64, - pub blend: Blend, - pub kind: Kind, - /// Vector mask in document pixels: the node shows only inside it (nonzero fill). - pub mask: Option, - /// Pixel mask: grey levels (white shows the node, black hides it); outside it the node is hidden. - pub pixel_mask: Option, - /// Layer effects the importer can show or bake in (others are reported). - pub effects: Vec, - /// Bottom to top. - pub children: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Spread { - /// Spread bounds in document pixels (the canvas, or the union of the artboards). - pub bounds: Rect, - /// Pages of a Publisher-style spread (one, or two facing pages), in document pixels. - pub pages: Vec, - /// Transparent background; otherwise the page is white. - pub transparent: bool, - /// Bottom to top. - pub nodes: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Document { - /// Pixels per inch: all geometry is in document pixels at this resolution. - pub dpi: f64, - pub spreads: Vec, - /// Master spreads, which [`Kind::MasterInstance`] nodes show on pages. - pub masters: Vec, - /// Application that last saved the file, as stored (`Affinity 3.0.2`), when present. - pub saved_by: Option, - /// Content that was not imported or was approximated, one line per kind, deduplicated. - pub warnings: Vec, - /// The document's CMYK colour profile (an ICC file), when it embeds one: the root's `CMYP`, - /// which each CMYK pixel layer's colour settings (`Prof`) also name, with relative - /// colorimetric intent and black-point compensation in every document checked. - pub cmyk_profile: Option>, -} diff --git a/crates/affinity/src/model/bounds.rs b/crates/affinity/src/model/bounds.rs deleted file mode 100644 index 7ef9fff0b2..0000000000 --- a/crates/affinity/src/model/bounds.rs +++ /dev/null @@ -1,142 +0,0 @@ -use super::read::MAX_TREE_DEPTH; -use super::{Affine, Kind, Node, ObjId, Point, Rect, Stream, Tag}; - -/// The bounds of what visible `nodes` draw (control points of outlines, corners of images, frames -/// and tables), in document pixels. -pub fn nodes_bounds(nodes: &[Node]) -> Option { - let mut out = None; - walk_bounds(nodes, true, 0, &mut out); - out -} - -/// The bounds of `node` and everything in it, hidden or not. -pub(super) fn tree_bounds(node: &Node) -> Option { - let mut out = None; - walk_bounds(std::slice::from_ref(node), false, 0, &mut out); - out -} - -fn walk_bounds(nodes: &[Node], visible_only: bool, depth: usize, out: &mut Option) { - if depth > MAX_TREE_DEPTH { - return; - } - for n in nodes.iter().filter(|n| n.visible || !visible_only) { - kind_points(&n.kind, &mut |p| add_point(out, p)); - walk_bounds(&n.children, visible_only, depth + 1, out); - } -} - -/// What a pixel mask over a node of `kind` with `children` is read over: the bounds of what they -/// draw, strokes included, or `None` (all of the mask) when some of it has no bounds known here: -/// artistic text, whose glyphs only the layout places. -pub(super) fn mask_extent(kind: &Kind, children: &[Node]) -> Option { - fn visit(kind: &Kind, children: &[Node], depth: usize, out: &mut Option) -> bool { - if depth > MAX_TREE_DEPTH || matches!(kind, Kind::Text(t) if t.frame.is_none()) { - return false; - } - let mut own = kind_bounds(kind); - if let (Some(r), Kind::Shape { strokes, .. } | Kind::Artboard { strokes, .. }) = (own, kind) { - // As far as a stroke can reach out of its path, miter joins included. - let reach = strokes.iter().map(|s| s.width * s.miter_limit.clamp(1.0, 10.0)).filter(|w| w.is_finite()).fold(0.0, f64::max); - own = Some(Rect { x0: r.x0 - reach, y0: r.y0 - reach, x1: r.x1 + reach, y1: r.y1 + reach }); - } - if let Some(r) = own { - *out = Some(out.map_or(r, |o| union(o, r))); - } - children.iter().filter(|n| n.visible).all(|n| visit(&n.kind, &n.children, depth + 1, out)) - } - let mut out = None; - if visit(kind, children, 0, &mut out) { out } else { None } -} - -/// The bounds of what one node's own kind draws (not its children): its outline's points, its -/// image's or frame's corners, or artistic text's anchor. -pub fn kind_bounds(kind: &Kind) -> Option { - let mut out = None; - kind_points(kind, &mut |p| add_point(&mut out, p)); - out -} - -fn add_point(out: &mut Option, p: Point) { - if p.x.is_finite() && p.y.is_finite() { - let r = Rect { x0: p.x, y0: p.y, x1: p.x, y1: p.y }; - *out = Some(out.map_or(r, |o| union(o, r))); - } -} - -fn kind_points(kind: &Kind, add: &mut dyn FnMut(Point)) { - let corners = |r: Rect, m: Affine| [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| m.apply(Point { x, y })); - match kind { - Kind::Shape { path, .. } | Kind::Artboard { path, .. } => { - for sp in &path.subpaths { - add(sp.start); - for seg in &sp.segments { - seg.iter().for_each(|p| add(*p)); - } - } - } - Kind::Image(img) => { - corners(Rect { x0: 0.0, y0: 0.0, x1: f64::from(img.width), y1: f64::from(img.height) }, img.transform).into_iter().for_each(add) - } - Kind::Text(t) => match t.frame { - Some(f) => corners(f, t.transform).into_iter().for_each(add), - None => add(t.transform.apply(t.anchor)), - }, - Kind::Table(t) => { - if let (Some(&x0), Some(&x1), Some(&y0), Some(&y1)) = (t.columns.first(), t.columns.last(), t.rows.first(), t.rows.last()) { - corners(Rect { x0, y0, x1, y1 }, t.transform).into_iter().for_each(add); - } - } - Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {} - } -} - -/// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC` -/// equal pages (Publisher 1 facing spreads). -pub(super) fn pages(s: &Stream, spread: ObjId) -> Vec { - if let Some(md) = s.obj(spread, b"SpMd") { - let v: Vec = - s.objs(md, b"PagR").into_iter().filter_map(|p| s.floats::<4>(p, b"rctp").map(rect)).filter(|r| r.x1 > r.x0 && r.y1 > r.y0).collect(); - if !v.is_empty() { - return v; - } - } - match (s.floats::<4>(spread, b"SprB").map(rect), s.int(spread, b"PagC")) { - (Some(b), Some(n @ 2..=16)) => { - let w = (b.x1 - b.x0) / n as f64; - (0..n).map(|i| Rect { x0: b.x0 + w * i as f64, x1: b.x0 + w * (i + 1) as f64, ..b }).collect() - } - _ => Vec::new(), - } -} - -pub(crate) fn union(a: Rect, b: Rect) -> Rect { - Rect { x0: a.x0.min(b.x0), y0: a.y0.min(b.y0), x1: a.x1.max(b.x1), y1: a.y1.max(b.y1) } -} - -pub(super) fn is_container(class: Tag) -> bool { - class == Tag::of(b"Scop") || class == Tag::of(b"Grup") -} - -pub(crate) fn rect(v: [f64; 4]) -> Rect { - Rect { x0: v[0], y0: v[1], x1: v[2], y1: v[3] } -} - -/// A readable name for a layer class in warnings. -pub(crate) fn describe(class: Tag) -> &'static str { - match &class.0.to_be_bytes() { - b"PCrv" => "curve", - b"ShpN" | b"SNEN" | b"SNRR" | b"ShRN" => "shape", - b"Comp" => "compound", - b"Rstr" => "pixel", - b"ImgN" => "image", - b"EmbN" => "embedded document", - b"MPIN" => "master page instance", - b"FRst" => "fill", - b"MRst" => "mask", - b"Slic" | b"SlcP" => "slice", - b"3DLA" => "3D", - [_, _, b'R', b'A'] => "adjustment", - _ => "unknown", - } -} diff --git a/crates/affinity/src/model/read.rs b/crates/affinity/src/model/read.rs deleted file mode 100644 index 80f4e0993b..0000000000 --- a/crates/affinity/src/model/read.rs +++ /dev/null @@ -1,685 +0,0 @@ -use super::bounds::{describe, is_container, mask_extent, nodes_bounds, pages, rect, tree_bounds, union}; -use super::{ - Affine, Archive, BTreeMap, Blend, Document, Effect, Error, HashSet, Image, Kind, Limits, Node, ObjId, Paint, Path, Point, Rect, Spread, Stream, - Tag, paint, stream, -}; - -/// Largest embedded colour profile kept (real CMYK profiles are a few megabytes). -const MAX_PROFILE_BYTES: usize = 32 << 20; - -/// Deepest layer nesting followed; deeper content is reported, not imported. -pub(super) const MAX_TREE_DEPTH: usize = 128; - -/// Total layer nodes imported. -const MAX_NODES: usize = 500_000; - -/// Pixels decoded from pixel layers over a whole document (2 GB as RGBA). The archive's limits -/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704). -const MAX_LAYER_PIXELS: u64 = 512 << 20; - -/// Embedded documents inside embedded documents are followed this deep. -const MAX_EMBED_DEPTH: usize = 4; - -/// Characters of all stories together (a story may be shared by many text layers). -const MAX_DOCUMENT_CHARS: usize = 16 << 20; - -/// Table cells of all tables together (each becomes a text object with its edge lines). -const MAX_DOCUMENT_CELLS: usize = 1 << 18; - -/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers). -const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20; - -/// Child references inspected, page rectangles produced, and outline segments retained, in all -/// (shared objects are visited once per link, so each visit is charged). Real documents stay -/// within a few times [`MAX_NODES`]; this leaves ~30x headroom over that. -const MAX_DOCUMENT_WORK: usize = 1 << 24; - -/// Owned layer-name characters kept in all (each visit of a shared object keeps its own copy). -const MAX_DOCUMENT_NAME_CHARS: usize = 16 << 20; - -/// What a whole read may still use. Shared objects can be linked from many layers, and embedded -/// documents are read with what their embedding document left, so linking or embedding the -/// same content many times can't multiply the work. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Budget { - /// Layer nodes ([`MAX_NODES`] in all). - pub(crate) nodes: usize, - /// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all). - pub(crate) pixels: u64, - /// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all). - pub(crate) chars: usize, - /// Table cells ([`MAX_DOCUMENT_CELLS`] in all). - pub(crate) cells: usize, - /// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all). - pub(crate) pressure: usize, - /// Child references, page rectangles and outline segments ([`MAX_DOCUMENT_WORK`] in all). - pub(crate) work: usize, - /// Layer-name characters ([`MAX_DOCUMENT_NAME_CHARS`] in all). - pub(crate) name_chars: usize, -} - -impl Budget { - pub(crate) const FULL: Budget = Budget { - nodes: MAX_NODES, - pixels: MAX_LAYER_PIXELS, - chars: MAX_DOCUMENT_CHARS, - cells: MAX_DOCUMENT_CELLS, - pressure: MAX_DOCUMENT_PRESSURE_POINTS, - work: MAX_DOCUMENT_WORK, - name_chars: MAX_DOCUMENT_NAME_CHARS, - }; - - /// Take `n` units of work, or fail the read. - pub(crate) fn spend(&mut self, n: usize) -> Result<(), Error> { - self.work = self.work.checked_sub(n).ok_or(Error::Limit("too much shared geometry or page data"))?; - Ok(()) - } -} - -/// Read a document: archive, `doc.dat` and the model. -pub fn read(bytes: &[u8], limits: Limits) -> Result { - read_within(bytes, limits, MAX_LAYER_PIXELS) -} - -/// [`read`], its pixel layers holding at most `pixels` pixels together. -pub(crate) fn read_within(bytes: &[u8], limits: Limits, pixels: u64) -> Result { - read_at(bytes, limits, &mut Budget { pixels, ..Budget::FULL }, Affine::IDENTITY, 0).document -} - -/// A document read by [`read_at`] (or why it couldn't be), with the bytes its archive extracted -/// either way. -struct ReadAt { - document: Result, - extracted: usize, -} - -/// Read a document whose spreads are placed by `base` (for embedded documents, nested `depth` -/// deep). What it uses is taken from `budget`, also when it fails part of the way. -/// The most characters of a layer's name kept. -const MAX_NAME_CHARS: usize = 1024; - -fn read_at(bytes: &[u8], limits: Limits, budget: &mut Budget, base: Affine, depth: usize) -> ReadAt { - let mut archive = match Archive::open(bytes, limits) { - Ok(a) => a, - Err(e) => return ReadAt { document: Err(e), extracted: 0 }, - }; - let document = read_archive(&mut archive, budget, base, depth); - ReadAt { document, extracted: archive.extracted() } -} - -fn read_archive(archive: &mut Archive, budget: &mut Budget, base: Affine, depth: usize) -> Result { - let doc = archive.read("doc.dat")?; - let s = stream::parse(&doc)?; - let mut reader = Reader::new(&s, archive, base, depth); - reader.budget = *budget; - let document = reader.document(); - *budget = reader.budget; - document -} - -pub(crate) struct Reader<'s, 'a, 'b> { - pub(crate) s: &'s Stream, - pub(crate) archive: &'b mut Archive<'a>, - pub(crate) dpi: f64, - pub(crate) warnings: BTreeMap, - active: HashSet, - /// Where the spreads go: the identity, or an embedding document's placement. - base: Affine, - /// The linear part of `base`, which also scales frame text. - pub(crate) type_base: Affine, - /// How deep inside embedded documents this one is. - depth: usize, - /// An embedded document's content, waiting to become its node's children. - pending: Option>, - /// The master spreads, in the order of [`Document::masters`]. - master_ids: Vec, - /// What the rest of the read may use. - pub(crate) budget: Budget, -} - -impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { - pub(crate) fn new(s: &'s Stream, archive: &'b mut Archive<'a>, base: Affine, depth: usize) -> Self { - let [a, b, c, d, ..] = base.0; - Self { - s, - archive, - dpi: 72.0, - warnings: BTreeMap::new(), - active: HashSet::new(), - base, - type_base: Affine([a, b, c, d, 0.0, 0.0]), - depth, - pending: None, - master_ids: Vec::new(), - budget: Budget::FULL, - } - } - - pub(crate) fn warn(&mut self, what: impl Into) { - *self.warnings.entry(what.into()).or_default() += 1; - } - - /// The document. - fn document(&mut self) -> Result { - let s = self.s; - let root = s.root; - self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0); - let saved_by = s.obj(root, b"NVer").map(|v| { - let product = s.str(v, b"Prod").unwrap_or("Affinity"); - match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) { - (Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"), - _ => product.to_string(), - } - }); - let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?; - self.master_ids = s.objs(doc, b"MpCh").into_iter().filter(|m| s.is(*m, b"Sprd")).collect(); - let mut spreads = Vec::new(); - for spread in s.objs(doc, b"Chld") { - if let Some(sp) = self.spread(doc, spread)? { - spreads.push(sp); - } - } - if spreads.is_empty() { - return Err(Error::Malformed("document has no pages")); - } - let mut masters = Vec::new(); - for master in self.master_ids.clone() { - match self.spread(doc, master)? { - Some(sp) => masters.push(sp), - // Keep the indices of `MasterInstance::master` valid. - None => masters.push(Spread { - bounds: Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 }, - pages: Vec::new(), - transparent: true, - nodes: Vec::new(), - }), - } - } - let cmyk_profile = s - .obj(root, b"CMYP") - .and_then(|p| s.bytes(p, b"Data")) - .filter(|b| b.len() <= MAX_PROFILE_BYTES && b.get(16..20) == Some(b"CMYK".as_slice())) - .map(<[u8]>::to_vec); - let warnings = std::mem::take(&mut self.warnings).into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect(); - Ok(Document { dpi: self.dpi, spreads, masters, saved_by, warnings, cmyk_profile }) - } - - /// A spread (`Sprd`) of the document `doc`, or of its master spreads. - fn spread(&mut self, doc: ObjId, spread: ObjId) -> Result, Error> { - let s = self.s; - if !s.is(spread, b"Sprd") { - self.warn("an unknown kind of page"); - return Ok(None); - } - let pages = pages(s, spread); - self.budget.spend(pages.len() + 1)?; - let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h }); - let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect { - x0: 0.0, - y0: 0.0, - x1: 0.0, - y1: 0.0, - }); - let transparent = s.bool(spread, b"SprT").unwrap_or(false); - let (nodes, mask) = self.children(spread, self.base, 0)?; - if mask.is_some() { - self.warn("mask layers directly on a page (imported without them)"); - } - Ok(Some(Spread { bounds, pages, transparent, nodes })) - } - - /// The children of `parent`, and the mask layer among them that masks the parent (with its - /// placement), read later over just what it masks. - #[allow(clippy::type_complexity)] - fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec, Option<(ObjId, Affine)>), Error> { - let s = self.s; - let mut out = Vec::new(); - let mut mask = None; - let kids = s.objs(parent, b"Chld"); - // Invisible masks and skipped children cost no node, so the visit is charged here. - self.budget.spend(kids.len())?; - for c in kids { - if s.is(c, b"MRst") { - // A mask layer inside a group or layer masks that container. - if s.bool(c, b"Visi") == Some(false) { - continue; - } - let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - if mask.is_none() { - mask = Some((c, local.then(world))); - } else { - self.warn("several pixel masks on one layer (only the first is used)"); - } - continue; - } - if let Some(n) = self.node(c, world, depth + 1)? { - out.push(n); - } - } - Ok((out, mask)) - } - - fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result, Error> { - let s = self.s; - if depth > MAX_TREE_DEPTH { - self.warn("layers nested deeper than 128 levels"); - return Ok(None); - } - let Some(left) = self.budget.nodes.checked_sub(1) else { - return Err(Error::Limit("too many layers")); - }; - self.budget.nodes = left; - // A node that contains itself (a shared object linked back into its own subtree). - if !self.active.insert(id) { - self.warn("a layer that contains itself"); - return Ok(None); - } - let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - let world = local.then(parent); - let class = s.class(id).unwrap_or(Tag(0)); - // A layer name is short; a long one is cut, as every visit of a shared object keeps a copy. - let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS.min(self.budget.name_chars)).collect(); - self.budget.name_chars -= name.chars().count(); - let visible = s.bool(id, b"Visi").unwrap_or(true); - let locked = s.bool(id, b"Edtb").is_some_and(|e| !e); - let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0)); - let blend = match s.enumeration(id, b"Blnd") { - None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough, - None => Blend::Normal, - Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| { - self.warn("an unknown blend mode (imported as Normal)"); - Blend::Normal - }), - }; - let kind = if !world.is_finite() { - self.warn("a layer with an invalid transform"); - Kind::Unsupported - } else { - self.kind(id, class, world, parent)? - }; - // This node's embedded content, before its children's `node` calls can take it. - let embedded = self.pending.take(); - // A compound's children are its operands, already merged into its outline. - let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? }; - if let Some(embedded) = embedded { - children.extend(embedded); - } - // Pixel masks are read only over what they mask (they can span a whole spread at print - // resolution, a gigapixel). - let over = mask_extent(&kind, &children); - let child_mask = match child_mask { - Some((c, at)) => crate::raster::mask(self, c, at, over)?, - None => None, - }; - let (mask, attached_mask) = self.attached_masks(id, world, over)?; - let pixel_mask = attached_mask.or(child_mask); - self.active.remove(&id); - let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children }; - // Gradient overlays are laid out over the node's bounds, also while it is hidden. - let bounds = tree_bounds(&node); - node.effects = self.effects(id, world, bounds); - Ok(Some(node)) - } - - fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result { - let s = self.s; - Ok(match &class.0.to_be_bytes() { - b"Scop" => Kind::Layer, - b"Grup" => Kind::Group, - b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => { - // Affinity 3.2.3's two-board public fixture marks board shapes with an `aprp` - // property object in `phrp`, while older documents use `ABEn`. Ordinary shapes - // in that fixture have neither. See the pinned corpus and validation audit. - if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) { - return Ok(self.artboard(id, world)); - } - let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else { - self.warn(format!("a {} that could not be read", describe(class))); - return Ok(Kind::Unsupported); - }; - self.budget.spend(local.subpaths.iter().map(|sp| sp.segments.len() + 1).sum())?; - let (fills, strokes) = paint::node_paint(self, id, world); - Kind::Shape { path: local.transformed(world), fills, strokes, even_odd } - } - b"TxtT" => match crate::text::table(self, id, world) { - Some(t) => Kind::Table(t), - None => { - self.warn("tables that could not be read"); - Kind::Unsupported - } - }, - b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) { - Some(t) => Kind::Text(t), - None => { - self.warn("text whose story could not be read (master-page text, or an unknown layout)"); - Kind::Unsupported - } - }, - b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? { - Some(img) => Kind::Image(img), - None => Kind::Unsupported, - }, - b"MPIN" => { - // `SLnk` links the instance with the master spread it shows. - let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default(); - let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o)); - let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096); - match master { - Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) }, - None => { - self.warn("master page instances without their master"); - Kind::Unsupported - } - } - } - b"EmbN" => match self.embedded_document(id, world) { - // The embedded document itself, as editable content. - Some(nodes) => { - self.pending = Some(nodes); - Kind::Group - } - None => match crate::raster::embedded(self, id, world)? { - Some(img) => { - self.warn("embedded documents and symbols (imported as pictures of them)"); - Kind::Image(img) - } - None => { - self.warn("embedded documents and symbols without a cached picture"); - Kind::Unsupported - } - }, - }, - b"FRst" => { - // A fill layer paints its whole bitmap area; its gradient lives in page space. - let b = s.obj(id, b"Bitm"); - let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0); - match (size(b"BmpW"), size(b"BmpH")) { - (Some(w), Some(h)) => { - let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] }; - let fills = paint::fills(self, id, parent, b"BFFl"); - Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false } - } - _ => { - self.warn("fill layers without an area"); - Kind::Unsupported - } - } - } - _ => { - self.warn(format!("{} layers", describe(class))); - Kind::Unsupported - } - }) - } - - /// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the - /// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below. - fn effects(&mut self, id: ObjId, world: Affine, bounds: Option) -> Vec { - let s = self.s; - let mut out = Vec::new(); - for e in s.objs(id, b"FiEf").into_iter().take(64) { - if s.bool(e, b"Enab") == Some(false) { - continue; - } - // "Scale with object": lengths follow the node's transform; otherwise they are absolute. - let k = if s.bool(e, b"SclO") == Some(true) { world.scale() } else { 1.0 }; - let len = |t: &[u8; 4]| s.f64(e, t).filter(|v| v.is_finite() && *v >= 0.0 && *v < 1e6).unwrap_or(0.0) * k; - let opacity = s.f64(e, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); - let angle = s.f64(e, b"Angl").filter(|v| v.is_finite()).unwrap_or(0.0); - let color = s.obj(e, b"Colr").and_then(|c| crate::paint::color(self, c)); - let class = s.class(e).map(|c| c.0.to_be_bytes()); - match (class.as_ref(), color) { - (Some(b"Shad"), Some(color)) => out.push(Effect::DropShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }), - (Some(b"InnS"), Some(color)) => out.push(Effect::InnerShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }), - (Some(b"OutG"), Some(color)) => out.push(Effect::OuterGlow { color, opacity, radius: len(b"Radi") }), - (Some(b"Strk"), Some(color)) if s.enumeration(e, b"Ftyp").is_none_or(|(t, _)| t == 0) => { - let align = s.enumeration(e, b"Alig").map_or(0, |(a, _)| a); - out.push(Effect::Outline { color, opacity, width: len(b"Radi"), align }); - } - (Some(b"Strk"), _) => self.warn("gradient outline effects (left out)"), - (Some(b"BevE" | b"EmbE"), _) => { - // No radius, no bevel (as Affinity draws it). - let size = len(b"Radi"); - if size > 0.0 { - let white = crate::paint::Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - let black = crate::paint::Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }; - let highlight = s.obj(e, b"HiCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(white); - let shadow = s.obj(e, b"ShCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(black); - let shadow_opacity = s.f64(e, b"ShOp").filter(|v| v.is_finite()).unwrap_or(0.75).clamp(0.0, 1.0); - let depth = s.f64(e, b"Dept").filter(|v| v.is_finite()).unwrap_or(5.0); - let azimuth = s.f64(e, b"Azim").filter(|v| v.is_finite()).unwrap_or(std::f64::consts::FRAC_PI_4 * 3.0); - let inner = s.enumeration(e, b"Beve").is_none_or(|(k, _)| k == 0); - out.push(Effect::Bevel { size, depth, angle: azimuth, highlight, highlight_opacity: opacity, shadow, shadow_opacity, inner }); - } - } - (Some(b"ColO"), Some(color)) => { - let blend = self.effect_blend(e); - out.push(Effect::ColorOverlay { color, opacity, blend }); - } - (Some(b"GrdO"), _) => { - let blend = self.effect_blend(e); - // The gradient's unit space spans the node's bounding box from -1 to 1, centred - // on it (y down): checked against the stored previews of real documents. - let space = - bounds.map(|b| Affine([(b.x1 - b.x0) / 2.0, 0.0, 0.0, (b.y1 - b.y0) / 2.0, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0])); - match (s.obj(e, b"GrFl"), space) { - (Some(fill), Some(space)) => match paint::descriptor(self, fill, space) { - Some(Paint::Gradient(gradient)) => out.push(Effect::GradientOverlay { gradient, opacity, blend }), - Some(Paint::Solid(color)) => out.push(Effect::ColorOverlay { color, opacity, blend }), - _ => {} - }, - // Nothing visible to lay it over. - (Some(_), None) => {} - (None, _) => self.warn("gradient overlay effects that could not be read (left out)"), - } - } - (Some(b"ColO"), None) => self.warn("colour overlay effects that could not be read (left out)"), - (Some(b"Gaus"), _) => self.warn("blur effects (left out)"), - _ => self.warn("layer effects of other kinds (left out)"), - } - } - for a in s.objs(id, b"AdCh") { - if let Some(effect) = self.attached_recolor(a) { - out.push(effect); - } - } - out - } - fn attached_recolor(&mut self, a: ObjId) -> Option { - let s = self.s; - if !s.is(a, b"RcRA") { - return None; - } - if s.bool(a, b"Visi") == Some(false) { - return None; - } - let adjp = s.obj(a, b"AdjP")?; - if !s.is(adjp, b"RecP") { - return None; - } - let h = s.f64(adjp, b"RecH").unwrap_or(0.0); - let sat = s.f64(adjp, b"RecS").unwrap_or(1.0); - let l = s.f64(adjp, b"RecL").unwrap_or(0.5); - let (r, g, b) = crate::paint::hsl(h, sat, l); - let color = crate::paint::Color::Rgb { r, g, b, a: 1.0 }; - let opacity = s.f64(a, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); - let blend = self.effect_blend(a); - Some(Effect::ColorOverlay { color, opacity, blend }) - } - - /// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned). - fn effect_blend(&mut self, e: ObjId) -> Blend { - match self.s.enumeration(e, b"BlnM") { - None => Blend::Normal, - Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| { - self.warn("an unknown blend mode (imported as Normal)"); - Blend::Normal - }), - } - } - - /// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines; - /// an attached mask layer is a pixel mask. Adjustments attached the same way are reported. - fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option) -> Result<(Option, Option), Error> { - let s = self.s; - let attached = s.objs(id, b"AdCh"); - let mut mask: Option = None; - let mut pixels: Option = None; - for a in attached { - let class = s.class(a).unwrap_or(Tag(0)); - if s.bool(a, b"Visi") == Some(false) { - continue; - } - if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") { - let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world); - if let Some((p, _)) = crate::geometry::outline(self, a, class, local) { - mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths); - } - } else if class == Tag::of(b"MRst") { - let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world); - match crate::raster::mask(self, a, local, over)? { - Some(m) if pixels.is_none() => pixels = Some(m), - Some(_) => self.warn("several pixel masks on one layer (only the first is used)"), - None => {} - } - } else if class == Tag::of(b"RcRA") { - // Handled in `effects` as a colour overlay. - } else { - self.warn(format!("{} layers attached to other layers (imported without them)", describe(class))); - } - } - Ok((mask, pixels)) - } - - /// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds - /// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes, - /// placed so the centre of its page, first artboard or content is the node's origin. - fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option> { - let s = self.s; - let entry = s.obj(id, b"Bitm").and_then(|b| s.obj(b, b"EmCn")).and_then(|c| s.entry(c, b"EmbC"))?.to_string(); - if entry.is_empty() { - return None; - } - if self.depth >= MAX_EMBED_DEPTH { - self.warn("embedded documents nested more than four deep"); - return None; - } - let data = self.archive.read(&entry).ok()?; - let inner = data.strip_prefix(b"EmDc").and_then(|d| d.get(4..))?; - if !crate::is_affinity(inner) { - return None; - } - // A first reading finds its page and resolution, the second places it. - // Both readings are charged to the budget and the archive's limits, also when they fail: - // each does the work. - let mut budget = self.budget; - let probe = read_at(inner, self.archive.remaining(), &mut budget, Affine::IDENTITY, self.depth + 1); - self.budget = budget; - if self.archive.charge(probe.extracted).is_err() { - self.warn("embedded documents beyond the size limit (left out)"); - return None; - } - let probe = match probe.document { - Ok(d) => d, - Err(e) => { - self.warn(format!("embedded documents that could not be read ({e})")); - return None; - } - }; - let spread = probe.spreads.first()?; - // `PBBx` 2 places the content's own bounds (as with a cached picture); otherwise its page. - let content = s.obj(id, b"Bitm").and_then(|b| s.enumeration(b, b"PBBx")).is_some_and(|(k, _)| k == 2); - let first_board = spread.nodes.iter().find_map(|n| if let Kind::Artboard { rect, .. } = &n.kind { Some(*rect) } else { None }); - let page = if content { None } else { spread.pages.first().copied().or(first_board) }; - let page = page.or_else(|| nodes_bounds(&spread.nodes)).unwrap_or(spread.bounds); - // Its pixels aren't needed any more: never hold both readings' at once. - drop(probe); - // Its document pixels are the node's units, whatever either document's resolution. - let k = 1.0; - let (cx, cy) = ((page.x0 + page.x1) / 2.0, (page.y0 + page.y1) / 2.0); - let base = Affine([k, 0.0, 0.0, k, -cx * k, -cy * k]).then(world); - if !base.is_finite() { - self.warn("embedded documents with an invalid placement"); - return None; - } - let mut budget = self.budget; - let placed = read_at(inner, self.archive.remaining(), &mut budget, base, self.depth + 1); - self.budget = budget; - if self.archive.charge(placed.extracted).is_err() { - self.warn("embedded documents beyond the size limit (left out)"); - return None; - } - let doc = placed.document.ok()?; - for w in doc.warnings { - self.warn(format!("{w} [in embedded documents]")); - } - if doc.spreads.len() > 1 { - self.warn("embedded documents with several pages (the first is used)"); - } - let mut nodes = doc.spreads.into_iter().next()?.nodes; - // Its master page instances count its own masters, which aren't kept: in this document - // they would show other masters. - fn strip_masters(nodes: &mut [Node], depth: usize) -> bool { - let mut found = false; - for n in nodes { - if matches!(n.kind, Kind::MasterInstance { .. }) { - n.kind = Kind::Unsupported; - found = true; - } - if depth < MAX_TREE_DEPTH { - found |= strip_masters(&mut n.children, depth + 1); - } - } - found - } - if strip_masters(&mut nodes, 0) { - self.warn("master pages of embedded documents (left out)"); - } - Some(nodes) - } - - fn artboard(&mut self, id: ObjId, world: Affine) -> Kind { - let s = self.s; - let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else { - self.warn("an artboard without valid bounds (its children are kept without clipping)"); - return Kind::Unsupported; - }; - let corners = - [Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p)); - let [a, b2, c, d, ..] = world.0; - if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 { - self.warn("a rotated or flipped artboard (export bounds are its bounding box; artwork keeps its outline)"); - } - let xs = corners.map(|p| p.x); - let ys = corners.map(|p| p.y); - let rect = Rect { - x0: xs.iter().copied().fold(f64::INFINITY, f64::min), - y0: ys.iter().copied().fold(f64::INFINITY, f64::min), - x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max), - y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max), - }; - if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) || rect.x1 <= rect.x0 || rect.y1 <= rect.y0 { - self.warn("an artboard with an invalid transformed size (its children are kept without clipping)"); - return Kind::Unsupported; - } - let class = s.class(id).unwrap_or(Tag::of(b"ShpN")); - let (path, even_odd) = crate::geometry::outline(self, id, class, world).unwrap_or_else(|| { - self.warn("an artboard whose outline could not be read (clipped to its rectangle)"); - (Path { subpaths: vec![crate::shapes::rectangle(b.x0, b.y0, b.x1, b.y1)] }, false) - }); - let (background, strokes) = paint::node_paint(self, id, world); - Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes } - } -} - -#[cfg(test)] -mod budget_tests { - use super::*; - - #[test] - fn shared_work_is_bounded() { - let mut b = Budget::FULL; - assert!(b.spend(MAX_DOCUMENT_WORK).is_ok()); - assert_eq!(b.spend(1), Err(Error::Limit("too much shared geometry or page data"))); - } -} diff --git a/crates/affinity/src/overlay.rs b/crates/affinity/src/overlay.rs deleted file mode 100644 index 80f54f68e9..0000000000 --- a/crates/affinity/src/overlay.rs +++ /dev/null @@ -1,675 +0,0 @@ -//! Colour and gradient overlays. VectorCraft has no such effect, so an overlay is baked into what -//! its node paints: fill, stroke and text colours, and pixels. The overlay lies over the node's -//! own paint in its blend mode at its opacity, inside the node's alpha (which it keeps). -//! -//! Blend modes follow the W3C Compositing and Blending formulas; the modes PDF lacks (Vivid -//! Light, Linear Light, Pin Light, Hard Mix, Add, Subtract, Average, Negation, Reflect, Glow, -//! Darker/Lighter Color) use their usual definitions. - -use std::borrow::Cow; - -use crate::model::{Affine, Blend, Effect, Image, Kind, Node, Pixels, Point}; -use crate::paint::{Color, Gradient, GradientKind, Paint, Stop, Stroke}; - -/// Deepest subtree an overlay is baked into (the reader bounds trees well below this). -const MAX_DEPTH: usize = 256; - -/// Most pixels an overlay is baked into per image. -const MAX_PIXELS: usize = 64 << 20; - -/// Work the overlays of one import may take together: each overlay counts the nodes and pixels -/// of the subtree it is baked into (which is copied once more for them all). Nested overlays -/// and shared content would otherwise multiply it; past it, overlays are left out and said. -pub const MAX_WORK: u64 = 1 << 29; - -#[derive(Clone, Copy)] -enum Source<'a> { - Solid(Color), - Gradient(&'a Gradient), -} - -#[derive(Clone, Copy)] -struct Overlay<'a> { - source: Source<'a>, - opacity: f64, - blend: Blend, -} - -/// `node` with its colour and gradient overlays baked in, and those of everything in it -/// (borrowed unchanged when `node` has none, or when what is left of `work`, see [`MAX_WORK`], -/// can't pay for copying it). `warn` hears what could only be approximated or was left out. -pub fn apply<'a>(node: &'a Node, work: &mut u64, warn: &mut dyn FnMut(&str)) -> Cow<'a, Node> { - if overlays(&node.effects).is_empty() { - return Cow::Borrowed(node); - } - let Some(left) = work.checked_sub(subtree_cost(node, *work, 0)) else { - warn("overlay effects beyond the work one import may take (left out)"); - return Cow::Borrowed(node); - }; - *work = left; - let mut out = node.clone(); - bake_tree(&mut out, work, 0, warn); - Cow::Owned(out) -} - -/// The visible colour and gradient overlays among `effects`. -fn overlays(effects: &[Effect]) -> Vec> { - effects - .iter() - .filter_map(|e| match e { - Effect::ColorOverlay { color, opacity, blend } => Some(Overlay { source: Source::Solid(*color), opacity: *opacity, blend: *blend }), - Effect::GradientOverlay { gradient, opacity, blend } => { - Some(Overlay { source: Source::Gradient(gradient), opacity: *opacity, blend: *blend }) - } - _ => None, - }) - .filter(|o| o.opacity > 0.0) - .collect() -} - -fn is_overlay(e: &Effect) -> bool { - matches!(e, Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. }) -} - -/// Bakes the overlays of `node` and its subtree into their paint, innermost first: an overlay -/// lies over what its node shows, its children's overlays included. Each overlay pays for the -/// subtree it is baked into out of `work`; past it, it is left out (and said). -fn bake_tree(node: &mut Node, work: &mut u64, depth: usize, warn: &mut dyn FnMut(&str)) { - if depth > MAX_DEPTH { - return; - } - for c in &mut node.children { - bake_tree(c, work, depth + 1, warn); - } - if !node.effects.iter().any(is_overlay) { - return; - } - let (effects, rest): (Vec, Vec) = std::mem::take(&mut node.effects).into_iter().partition(is_overlay); - node.effects = rest; - let overlays = overlays(&effects); - if overlays.is_empty() { - return; - } - let count = u64::try_from(overlays.len()).unwrap_or(u64::MAX); - let cost = subtree_cost(node, *work / count, 0).saturating_mul(count); - let Some(left) = work.checked_sub(cost) else { - warn("overlay effects beyond the work one import may take (left out)"); - return; - }; - *work = left; - for o in &overlays { - if matches!(o.blend, Blend::Erase | Blend::PassThrough) { - warn("overlay effects in a blend mode VectorCraft doesn't have (imported as Normal)"); - } - bake_node(node, o, 0, warn); - } -} - -/// Nodes and pixels in `node`'s subtree, counted only until they pass `limit`. -fn subtree_cost(node: &Node, limit: u64, depth: usize) -> u64 { - if depth > MAX_DEPTH { - return 0; - } - let mut cost: u64 = match &node.kind { - Kind::Image(img) => (u64::from(img.width) * u64::from(img.height)).saturating_add(1), - Kind::Text(t) => u64::try_from(t.runs.len()).unwrap_or(u64::MAX).saturating_add(1), - Kind::Table(t) => u64::try_from(t.cells.len()).unwrap_or(u64::MAX).saturating_add(1), - _ => 1, - }; - for c in &node.children { - if cost > limit { - break; - } - cost = cost.saturating_add(subtree_cost(c, limit - cost, depth + 1)); - } - cost -} - -fn bake_node(node: &mut Node, o: &Overlay, depth: usize, warn: &mut dyn FnMut(&str)) { - if depth > MAX_DEPTH { - return; - } - match &mut node.kind { - Kind::Shape { fills, strokes, .. } => { - for f in fills.iter_mut() { - *f = paint(f, o, warn); - } - strokes.iter_mut().for_each(|s| stroke(s, o, warn)); - } - Kind::Artboard { background, strokes, .. } => { - for f in background.iter_mut() { - *f = paint(f, o, warn); - } - strokes.iter_mut().for_each(|s| stroke(s, o, warn)); - } - Kind::Text(t) => { - for r in &mut t.runs { - r.fill = paint(&r.fill, o, warn); - if let Some(s) = &mut r.stroke { - stroke(s, o, warn); - } - } - } - Kind::Table(t) => { - for c in &mut t.cells { - for r in &mut c.runs { - r.fill = paint(&r.fill, o, warn); - if let Some(s) = &mut r.stroke { - stroke(s, o, warn); - } - } - } - for s in t.vertical.iter_mut().chain(t.horizontal.iter_mut()).flatten() { - stroke(s, o, warn); - } - } - Kind::Image(img) => { - if !pixels(img, o) { - warn("overlay effects on images too large to recolour (left out)"); - } - } - Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {} - } - for e in &mut node.effects { - match e { - Effect::Outline { color, .. } => *color = over(*color, o.source.at_solid(), o), - Effect::DropShadow { .. } | Effect::InnerShadow { .. } | Effect::OuterGlow { .. } | Effect::Bevel { .. } => {} - Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } => {} - } - } - for c in &mut node.children { - bake_node(c, o, depth + 1, warn); - } -} - -fn stroke(s: &mut Stroke, o: &Overlay, warn: &mut dyn FnMut(&str)) { - s.paint = paint(&s.paint, o, warn); -} - -/// A paint with the overlay over it. -fn paint(p: &Paint, o: &Overlay, warn: &mut dyn FnMut(&str)) -> Paint { - match (p, o.source) { - (Paint::None, _) => Paint::None, - (Paint::Solid(c), Source::Solid(s)) => Paint::Solid(over(*c, s, o)), - (Paint::Gradient(g), Source::Solid(s)) => { - Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(st.color, s, o), ..*st }).collect(), ..g.clone() }) - } - // Over one colour, the result is the overlay's gradient with each stop laid over it. - (Paint::Solid(c), Source::Gradient(g)) => { - Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(*c, st.color, o), ..*st }).collect(), ..g.clone() }) - } - (Paint::Gradient(base), Source::Gradient(g)) => { - if !(o.blend == Blend::Normal && o.opacity >= 1.0) { - warn("gradient overlays on gradients (approximated)"); - } - // Exact when the overlay covers it; otherwise over the base gradient's average colour. - let avg = average(base); - Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(avg, st.color, o), ..*st }).collect(), ..g.clone() }) - } - } -} - -impl Source<'_> { - /// One colour for the source (a gradient's average) where only one fits. - fn at_solid(&self) -> Color { - match self { - Source::Solid(c) => *c, - Source::Gradient(g) => average(g), - } - } -} - -fn average(g: &Gradient) -> Color { - let n = g.stops.len().max(1) as f64; - let (mut r, mut gr, mut b, mut a) = (0.0, 0.0, 0.0, 0.0); - for s in &g.stops { - let [sr, sg, sb] = rgb(s.color); - r += sr; - gr += sg; - b += sb; - a += s.color.alpha(); - } - Color::Rgb { r: r / n, g: gr / n, b: b / n, a: a / n } -} - -/// `source` laid over `base` in the overlay's mode and opacity; `base`'s alpha is kept. -fn over(base: Color, source: Color, o: &Overlay) -> Color { - let k = (o.opacity * source.alpha()).clamp(0.0, 1.0); - let alpha = base.alpha(); - // Normal mixes within the colour model when both share it, so CMYK stays CMYK. - if matches!(o.blend, Blend::Normal | Blend::PassThrough | Blend::Erase) { - let mix = |a: f64, b: f64| a + (b - a) * k; - match (base, source) { - (Color::Cmyk { c, m, y, k: kk, .. }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2, .. }) => { - return Color::Cmyk { c: mix(c, c2), m: mix(m, m2), y: mix(y, y2), k: mix(kk, k2), a: alpha }; - } - (Color::Gray { v, .. }, Color::Gray { v: v2, .. }) => return Color::Gray { v: mix(v, v2), a: alpha }, - (_, s) if k >= 1.0 => return with_alpha(s, alpha), - _ => {} - } - } - let b = rgb(base); - let s = rgb(source); - let blended = blend(o.blend, b, s); - let [r, g, bl] = [0, 1, 2].map(|i| b[i] + (blended[i] - b[i]) * k); - Color::Rgb { r, g, b: bl, a: alpha } -} - -fn with_alpha(c: Color, a: f64) -> Color { - match c { - Color::Rgb { r, g, b, .. } => Color::Rgb { r, g, b, a }, - Color::Cmyk { c, m, y, k, .. } => Color::Cmyk { c, m, y, k, a }, - Color::Gray { v, .. } => Color::Gray { v, a }, - Color::Lab { l, a: la, b, .. } => Color::Lab { l, a: la, b, alpha: a }, - } -} - -/// sRGB components (0..1) of a colour. CMYK uses the profile-free formula (the engine shows the -/// node's other CMYK colours through the document's profile), Lab its D50 sRGB colour. -fn rgb(c: Color) -> [f64; 3] { - let f = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - match c { - Color::Rgb { r, g, b, .. } => [f(r), f(g), f(b)], - Color::Gray { v, .. } => [f(v); 3], - Color::Cmyk { c, m, y, k, .. } => { - let w = 1.0 - f(k); - [(1.0 - f(c)) * w, (1.0 - f(m)) * w, (1.0 - f(y)) * w] - } - Color::Lab { l, a, b, .. } => lab_to_srgb(l, a, b).map(f), - } -} - -/// CIE L*a*b* (D50) to sRGB, through XYZ and the Bradford adaptation to D65. -fn lab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { - let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; - let (l, a, b) = (finite(l), finite(a), finite(b)); - let fy = (l + 16.0) / 116.0; - let (fx, fz) = (fy + a / 500.0, fy - b / 200.0); - let inv = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) }; - // D50 white. - let (x, y, z) = (0.964_22 * inv(fx), inv(fy), 0.825_21 * inv(fz)); - // XYZ (D50) to linear sRGB, Bradford-adapted. - let r = 3.133_856 * x - 1.616_867 * y - 0.490_615 * z; - let g = -0.978_768 * x + 1.916_142 * y + 0.033_454 * z; - let bl = 0.071_945 * x - 0.228_991 * y + 1.405_243 * z; - let gamma = |v: f64| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 }; - [gamma(r), gamma(g), gamma(bl)] -} - -/// Bake the overlay into an image's pixels. False if they couldn't be read or are too many. -fn pixels(img: &mut Image, o: &Overlay) -> bool { - let Some(n) = (img.width as usize).checked_mul(img.height as usize).filter(|n| *n <= MAX_PIXELS) else { return false }; - let Some(len) = n.checked_mul(4) else { return false }; - let mut px = match &img.pixels { - Pixels::Rgba8(p) => match p.get(..len) { - Some(p) => p.to_vec(), - None => return false, - }, - Pixels::Encoded(bytes) => match decode(bytes, img.width, img.height) { - Some(p) => p, - None => return false, - }, - // An overlay is blended in RGB: CMYK pixels take the profile-free formula here. - Pixels::Cmyka8(p) => match p.get(..n.saturating_mul(5)) { - Some(p) if p.len() == n * 5 => p - .as_chunks::<5>() - .0 - .iter() - .flat_map(|[c, m, y, k, a]| { - let w = 255 - u16::from(*k); - let ch = |v: u8| ((u16::from(255 - v) * w + 127) / 255) as u8; - [ch(*c), ch(*m), ch(*y), *a] - }) - .collect(), - _ => return false, - }, - }; - let width = img.width.max(1) as usize; - // A solid source is converted once; a gradient is sampled at each pixel's centre. - let solid = match o.source { - Source::Solid(c) => Some((rgb(c), c.alpha())), - Source::Gradient(_) => None, - }; - let to_unit = match o.source { - Source::Gradient(g) => match invert(g.transform) { - Some(m) => Some((img.transform.then(m), g, stop_reach(g))), - None => return false, - }, - Source::Solid(_) => None, - }; - for (i, p) in px.as_chunks_mut::<4>().0.iter_mut().enumerate() { - if p[3] == 0 { - continue; - } - let (s, sa) = match (solid, &to_unit) { - (Some(s), _) => s, - (None, Some((m, g, reach))) => { - let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 }); - let c = sample(g, reach, q); - (rgb(c), c.alpha()) - } - (None, None) => continue, - }; - let k = (o.opacity * sa).clamp(0.0, 1.0); - let b = [p[0], p[1], p[2]].map(|v| f64::from(v) / 255.0); - let m = blend(o.blend, b, s); - for c in 0..3 { - p[c] = ((b[c] + (m[c] - b[c]) * k).clamp(0.0, 1.0) * 255.0).round() as u8; - } - } - img.pixels = Pixels::Rgba8(px); - true -} - -/// An encoded original's RGBA pixels, decoded only if it is `width` × `height` as its layer says. -fn decode(bytes: &[u8], width: u32, height: u32) -> Option> { - let probe = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - if probe.into_dimensions().ok()? != (width, height) { - return None; - } - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - let mut limits = image::Limits::default(); - limits.max_image_width = Some(width); - limits.max_image_height = Some(height); - limits.max_alloc = u64::try_from(MAX_PIXELS).ok().map(|n| n * 8); - reader.limits(limits); - Some(reader.decode().ok()?.into_rgba8().into_raw()) -} - -/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`: -/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and -/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not. -fn stop_reach(g: &Gradient) -> Vec { - g.stops - .iter() - .skip(1) - .scan(f64::NEG_INFINITY, |m, s| { - *m = m.max(s.offset); - Some(*m) - }) - .collect() -} - -/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`). -fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color { - let t = match g.kind { - GradientKind::Linear => q.x, - GradientKind::Radial => q.x.hypot(q.y), - GradientKind::Conical => q.y.atan2(q.x).rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU, - }; - let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - let (Some(first), Some(last)) = (g.stops.first(), g.stops.last()) else { return Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } }; - if t <= first.offset { - return first.color; - } - let k = reach.partition_point(|r| *r < t); - if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) { - let span = b.offset - a.offset; - let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 }; - // Affinity's midpoint bias (see `Stop::half_point`). - let k = 1.0 + 8.0 * (a.bias - 0.5).abs(); - let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) }; - let (x, y) = (rgb(a.color), rgb(b.color)); - let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u); - return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u }; - } - last.color -} - -fn invert(m: Affine) -> Option { - let [a, b, c, d, e, f] = m.0; - let det = a * d - b * c; - if !(det.is_finite() && det.abs() > 1e-12) { - return None; - } - let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det); - Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)])) -} - -/// The blend of backdrop `b` and source `s` (sRGB, 0..1). -fn blend(mode: Blend, b: [f64; 3], s: [f64; 3]) -> [f64; 3] { - use Blend::*; - let sep = |f: fn(f64, f64) -> f64| [0, 1, 2].map(|i| f(b[i], s[i]).clamp(0.0, 1.0)); - match mode { - Normal | PassThrough | Erase => s, - Darken => sep(f64::min), - Lighten => sep(f64::max), - Multiply => sep(|b, s| b * s), - Screen => sep(screen), - ColorBurn => sep(burn), - ColorDodge => sep(dodge), - Blend::Overlay => sep(|b, s| hard_light(s, b)), - HardLight => sep(hard_light), - SoftLight => sep(soft_light), - Difference => sep(|b, s| (b - s).abs()), - Exclusion => sep(|b, s| b + s - 2.0 * b * s), - Add => sep(|b, s| b + s), - Subtract => sep(|b, s| b - s), - VividLight => sep(|b, s| if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) }), - LinearLight => sep(|b, s| b + 2.0 * s - 1.0), - PinLight => sep(|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) }), - HardMix => sep(|b, s| if b + s >= 1.0 { 1.0 } else { 0.0 }), - Average => sep(|b, s| (b + s) / 2.0), - Negation => sep(|b, s| 1.0 - (1.0 - b - s).abs()), - Reflect => sep(reflect), - Glow => sep(|b, s| reflect(s, b)), - DarkerColor => { - if lum(s) < lum(b) { - s - } else { - b - } - } - LighterColor => { - if lum(s) > lum(b) { - s - } else { - b - } - } - Hue => set_lum(set_sat(s, sat(b)), lum(b)), - Saturation => set_lum(set_sat(b, sat(s)), lum(b)), - Blend::Color => set_lum(s, lum(b)), - Luminosity => set_lum(b, lum(s)), - } -} - -fn screen(b: f64, s: f64) -> f64 { - b + s - b * s -} - -fn burn(b: f64, s: f64) -> f64 { - if b >= 1.0 { - 1.0 - } else if s <= 0.0 { - 0.0 - } else { - 1.0 - ((1.0 - b) / s).min(1.0) - } -} - -fn dodge(b: f64, s: f64) -> f64 { - if b <= 0.0 { - 0.0 - } else if s >= 1.0 { - 1.0 - } else { - (b / (1.0 - s)).min(1.0) - } -} - -fn hard_light(b: f64, s: f64) -> f64 { - if s <= 0.5 { b * 2.0 * s } else { screen(b, 2.0 * s - 1.0) } -} - -fn soft_light(b: f64, s: f64) -> f64 { - if s <= 0.5 { - b - (1.0 - 2.0 * s) * b * (1.0 - b) - } else { - let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() }; - b + (2.0 * s - 1.0) * (d - b) - } -} - -fn reflect(b: f64, s: f64) -> f64 { - if s >= 1.0 { 1.0 } else { (b * b / (1.0 - s)).min(1.0) } -} - -fn lum(c: [f64; 3]) -> f64 { - 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2] -} - -fn clip_color(c: [f64; 3]) -> [f64; 3] { - let l = lum(c); - let n = c[0].min(c[1]).min(c[2]); - let x = c[0].max(c[1]).max(c[2]); - c.map(|v| { - let mut v = v; - if n < 0.0 && l - n > 1e-12 { - v = l + (v - l) * l / (l - n); - } - if x > 1.0 && x - l > 1e-12 { - v = l + (v - l) * (1.0 - l) / (x - l); - } - v.clamp(0.0, 1.0) - }) -} - -fn set_lum(c: [f64; 3], l: f64) -> [f64; 3] { - let d = l - lum(c); - clip_color(c.map(|v| v + d)) -} - -fn sat(c: [f64; 3]) -> f64 { - c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2]) -} - -fn set_sat(c: [f64; 3], s: f64) -> [f64; 3] { - let max = c[0].max(c[1]).max(c[2]); - let min = c[0].min(c[1]).min(c[2]); - if max - min <= 1e-12 { - return [0.0; 3]; - } - c.map(|v| (v - min) * s / (max - min)) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn solid(c: Color, opacity: f64, blend: Blend) -> Node { - Node { - class: crate::stream::Tag::of(b"ShpN"), - name: String::new(), - visible: true, - locked: false, - opacity: 1.0, - blend: Blend::Normal, - kind: Kind::Shape { - path: Default::default(), - fills: vec![Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.0, a: 1.0 })], - strokes: vec![], - even_odd: false, - }, - mask: None, - pixel_mask: None, - effects: vec![Effect::ColorOverlay { color: c, opacity, blend }], - children: vec![], - } - } - - fn fill(n: &Node) -> Color { - match &n.kind { - Kind::Shape { fills, .. } => match fills.first() { - Some(Paint::Solid(c)) => *c, - other => panic!("{other:?}"), - }, - other => panic!("{other:?}"), - } - } - - #[test] - fn a_full_colour_overlay_replaces_the_fill_and_keeps_its_alpha() { - let white = Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - let n = apply(&solid(white, 1.0, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned(); - assert_eq!(fill(&n), white); - assert!(n.effects.is_empty(), "the overlay is baked, not kept"); - // Half way, mixed in RGB. - let n = apply(&solid(white, 0.5, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned(); - assert_eq!(fill(&n), Color::Rgb { r: 1.0, g: 0.75, b: 0.5, a: 1.0 }); - } - - #[test] - fn blend_modes_follow_their_formulas() { - let b = [0.25, 0.5, 1.0]; - assert_eq!(blend(Blend::Multiply, b, [0.5; 3]), [0.125, 0.25, 0.5]); - assert_eq!(blend(Blend::Screen, b, [0.5; 3]), [0.625, 0.75, 1.0]); - assert_eq!(blend(Blend::VividLight, [0.5; 3], [0.75; 3]), [1.0; 3]); - assert_eq!(blend(Blend::HardMix, [0.5; 3], [0.6; 3]), [1.0; 3]); - // Color keeps the backdrop's luminosity with the source's hue and saturation. - let c = blend(Blend::Color, [0.5; 3], [1.0, 0.0, 0.0]); - assert!((lum(c) - 0.5).abs() < 1e-9 && c[0] > c[1] && (c[1] - c[2]).abs() < 1e-9, "{c:?}"); - } - - #[test] - fn overlays_recolour_pixels_inside_their_alpha() { - let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal); - n.kind = Kind::Image(Image { width: 2, height: 1, pixels: Pixels::Rgba8(vec![255, 0, 0, 255, 255, 0, 0, 0]), transform: Affine::IDENTITY }); - let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned(); - let Kind::Image(img) = &out.kind else { panic!() }; - assert_eq!(img.pixels, Pixels::Rgba8(vec![0, 0, 255, 255, 255, 0, 0, 0])); - } - - #[test] - fn a_gradient_overlay_over_one_colour_becomes_that_gradient() { - let g = Gradient { - kind: GradientKind::Linear, - stops: vec![ - Stop { offset: 0.0, color: Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, bias: 0.5 }, - Stop { offset: 1.0, color: Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }, bias: 0.5 }, - ], - transform: Affine([10.0, 0.0, 0.0, 10.0, 0.0, 0.0]), - }; - let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, 1.0, Blend::Normal); - n.effects = vec![Effect::GradientOverlay { gradient: g.clone(), opacity: 1.0, blend: Blend::Normal }]; - let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned(); - let Kind::Shape { fills, .. } = &out.kind else { panic!() }; - assert_eq!(fills.first(), Some(&Paint::Gradient(g))); - } - - #[test] - fn a_group_overlay_lies_over_its_childrens_overlays() { - let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; - let blue = Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; - let mut group = solid(red, 0.5, Blend::Normal); - group.kind = Kind::Group; - group.children = vec![solid(blue, 1.0, Blend::Normal)]; - // The copy (2 nodes), the child's overlay (1) and the group's (2). - let mut work = 5; - let out = apply(&group, &mut work, &mut |_| {}).into_owned(); - assert_eq!(work, 0); - let child = out.children.first().unwrap(); - // Blue first, then half of the group's red over it. - assert_eq!(fill(child), Color::Rgb { r: 0.5, g: 0.0, b: 0.5, a: 1.0 }); - assert!(out.effects.is_empty() && child.effects.is_empty(), "both overlays are baked"); - // With no work left for the group's overlay, the child's still applies. - let mut warnings = Vec::new(); - let out = apply(&group, &mut { 4 }, &mut |w| warnings.push(w.to_string())).into_owned(); - assert_eq!(fill(out.children.first().unwrap()), blue); - assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}"); - } - - #[test] - fn overlays_stop_at_the_work_one_import_may_take() { - let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal); - n.kind = Kind::Image(Image { width: 4, height: 4, pixels: Pixels::Rgba8(vec![255; 64]), transform: Affine::IDENTITY }); - // 16 pixels and the node, for the copy and for the overlay: 34. - let mut work = 40; - let mut warnings = Vec::new(); - assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Owned(_))); - assert_eq!((work, warnings.len()), (6, 0)); - assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Borrowed(_))); - assert_eq!(work, 6); - assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}"); - } -} diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs deleted file mode 100644 index c7b2acbbd3..0000000000 --- a/crates/affinity/src/paint.rs +++ /dev/null @@ -1,403 +0,0 @@ -//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint, -//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index). - -use crate::model::{Affine, Reader}; -use crate::stream::{ObjId, Value}; - -/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless -/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Color { - Rgb { - r: f64, - g: f64, - b: f64, - a: f64, - }, - Cmyk { - c: f64, - m: f64, - y: f64, - k: f64, - a: f64, - }, - Gray { - v: f64, - a: f64, - }, - /// CIE L*a*b* (D50). - Lab { - l: f64, - a: f64, - b: f64, - alpha: f64, - }, -} - -impl Color { - pub fn alpha(&self) -> f64 { - match self { - Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a, - Color::Lab { alpha, .. } => *alpha, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum GradientKind { - Linear, - /// Elliptical and radial: distance from the centre in unit space. - Radial, - /// Angle around the centre. - Conical, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Stop { - pub offset: f64, - pub color: Color, - /// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend). - pub bias: f64, -} - -impl Stop { - /// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve - /// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`. - pub fn half_point(&self) -> f64 { - let k = 1.0 + 8.0 * (self.bias - 0.5).abs(); - let h = 0.5f64.powf(1.0 / k); - if self.bias >= 0.5 { h } else { 1.0 - h } - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Gradient { - pub kind: GradientKind, - pub stops: Vec, - /// Unit space to document pixels: linear runs from unit (0,0) to (1,0); radial is the unit - /// circle; conical starts along unit +x and turns towards unit +y. - pub transform: Affine, -} - -#[derive(Debug, Clone, PartialEq, Default)] -pub enum Paint { - #[default] - None, - Solid(Color), - Gradient(Gradient), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Cap { - Butt, - Round, - Square, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Join { - Miter, - Round, - Bevel, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Align { - Center, - Inside, - Outside, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Stroke { - pub paint: Paint, - /// Width in document pixels. - pub width: f64, - pub cap: Cap, - pub join: Join, - pub miter_limit: f64, - pub align: Align, - /// Dash and gap lengths in document pixels, and the phase. - pub dash: Option<(Vec, f64)>, - /// Painted below the fill instead of above it. - pub behind: bool, - /// The pressure curve: (position 0..1 along the path, width as a fraction of `width`) in - /// order along the path, `None` for a stroke of the same width all along. - pub profile: Option>, -} - -/// Gradient stops per gradient. -const MAX_STOPS: usize = 1024; - -/// Dash and gap lengths per dash pattern (a pattern has a few; strokes and text runs copy theirs). -const MAX_DASHES: usize = 64; - -fn floats(v: &Value) -> Option> { - match v { - Value::Floats(f) => Some(f.clone()), - Value::Bytes(b) if b.len() % 4 == 0 => Some(b.as_chunks::<4>().0.iter().map(|c| f64::from(f32::from_le_bytes(*c))).collect()), - _ => None, - } -} - -/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`). -pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option { - color_within(r, id, 0) -} - -/// The most spot colours that stand for one another followed. -const MAX_SPOT_CHAIN: u32 = 8; - -/// [`color`], `depth` spot colours deep: one that stands for itself (or a ring of them) ends here. -fn color_within(r: &mut Reader, id: ObjId, depth: u32) -> Option { - let s = r.s; - let class = s.class(id)?; - let col = || -> Option> { - let v = floats(s.field(id, b"_col")?)?; - v.iter().all(|f| f.is_finite()).then_some(v) - }; - Some(match &class.0.to_be_bytes() { - b"RGBA" => { - let v = col()?; - Color::Rgb { r: *v.first()?, g: *v.get(1)?, b: *v.get(2)?, a: v.get(3)?.clamp(0.0, 1.0) } - } - b"HSLA" => { - let v = col()?; - let (r2, g, b) = hsl(*v.first()?, *v.get(1)?, *v.get(2)?); - Color::Rgb { r: r2, g, b, a: v.get(3)?.clamp(0.0, 1.0) } - } - b"CMYK" => { - let v = col()?; - Color::Cmyk { c: *v.first()?, m: *v.get(1)?, y: *v.get(2)?, k: *v.get(3)?, a: v.get(4)?.clamp(0.0, 1.0) } - } - b"GRAY" => { - let v = col()?; - Color::Gray { v: *v.first()?, a: v.get(1)?.clamp(0.0, 1.0) } - } - b"LABA" => { - let b = s.bytes(id, b"_col")?; - let u = |i: usize| -> Option { Some(f64::from(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) / 65535.0) }; - Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? } - } - b"Pant" => { - r.warn("spot colours (imported as their RGB equivalent)"); - if depth >= MAX_SPOT_CHAIN { - return None; - } - return s - .obj(id, b"srgb") - .and_then(|c| color_within(r, c, depth + 1)) - .or_else(|| s.obj(id, b"base").and_then(|c| color_within(r, c, depth + 1))); - } - b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 }, - _ => { - r.warn("colours in an unknown model"); - return None; - } - }) -} - -pub(crate) fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { - let c = (1.0 - (2.0 * l - 1.0).abs()) * s; - let hp = (h.rem_euclid(1.0)) * 6.0; - let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); - let (r, g, b) = match hp as u32 { - 0 => (c, x, 0.0), - 1 => (x, c, 0.0), - 2 => (0.0, c, x), - 3 => (0.0, x, c), - 4 => (x, 0.0, c), - _ => (c, 0.0, x), - }; - let m = l - c / 2.0; - (r + m, g + m, b + m) -} - -/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's -/// space to document pixels. -pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option { - let s = r.s; - let (fill, unit) = if s.is(id, b"FDsc") { - let unit = s.floats::<6>(id, b"FDeX").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - (s.obj(id, b"FDeF")?, unit) - } else { - (id, Affine::IDENTITY) - }; - match &s.class(fill)?.0.to_be_bytes() { - b"FilN" => Some(Paint::None), - b"FilS" => Some(Paint::Solid(color(r, s.obj(fill, b"Colr")?)?)), - b"FilG" => { - let kind = match s.enumeration(fill, b"Type").map(|(i, _)| i) { - Some(0) | None => GradientKind::Linear, - Some(1 | 2) => GradientKind::Radial, - Some(3) => GradientKind::Conical, - Some(_) => { - r.warn("gradients of an unknown kind (imported as linear)"); - GradientKind::Linear - } - }; - let grad = s.obj(fill, b"Grad")?; - let cols = s.objs(grad, b"Cols"); - // Convert only the positions that pair with a colour, as shared attributes repeat this per run. - let posn: &[Value] = match s.field(grad, b"Posn") { - Some(Value::Array(a)) => a, - _ => &[], - }; - let mut stops = Vec::new(); - for (c, p) in cols.iter().zip(posn.iter().filter_map(floats)).take(MAX_STOPS) { - let color = color(r, *c)?; - let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0); - let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0); - stops.push(Stop { offset, color, bias }); - } - if stops.is_empty() { - return Some(Paint::None); - } - Some(Paint::Gradient(Gradient { kind, stops, transform: unit.then(local) })) - } - b"FilB" => { - r.warn("bitmap and pattern fills (left empty)"); - Some(Paint::None) - } - _ => { - r.warn("fills of an unknown kind (left empty)"); - Some(Paint::None) - } - } -} - -fn current(r: &Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> Option { - let items = r.s.objs(id, list); - let i = r.s.int(id, index).and_then(|i| usize::try_from(i).ok()).unwrap_or(0); - items.get(i).or_else(|| items.first()).copied() -} - -/// The fills of `list` (artboard backgrounds use `BFFl`). -pub(crate) fn fills(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> Vec { - let d = current(r, id, list, b"BFCr").or_else(|| r.s.obj(id, b"BFil")); - d.and_then(|d| descriptor(r, d, local)).filter(|p| *p != Paint::None).into_iter().collect() -} - -/// A node's fill and stroke. `local` maps the node's space to document pixels. -pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec, Vec) { - let s = r.s; - let fills = fills(r, id, local, b"BFFl"); - if r.s.objs(id, b"BFFl").len() > 1 || r.s.objs(id, b"LIFl").len() > 1 { - r.warn("several fills or strokes on one object (only the active one is imported)"); - } - if s.f64(id, b"FOpc").is_some_and(|o| o < 0.999) { - r.warn("fill opacity (imported at full fill opacity)"); - } - if s.obj(id, b"Trns").is_some() { - r.warn("transparency gradients (imported without them)"); - } - let (pen, style) = if s.field(id, b"LIFl").is_some() { - (current(r, id, b"LIFl", b"LICr"), current(r, id, b"LILn", b"LICr")) - } else { - (s.obj(id, b"PFil"), s.obj(id, b"LSty")) - }; - let behind = matches!(s.field(id, b"DrwO"), Some(Value::Array(a)) if a.first() == Some(&Value::Enum { id: 1, version: 0 })); - let stroke = match (pen, style) { - (Some(pen), Some(style)) => stroke(r, pen, style, local, behind), - _ => None, - }; - (fills, stroke.into_iter().collect()) -} - -pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option { - let s = r.s; - let paint = descriptor(r, pen, local)?; - if paint == Paint::None { - return None; - } - let lsty = if s.is(ldsc, b"LDsc") { s.obj(ldsc, b"LDeL")? } else { ldsc }; - let weight = s.f64(lsty, b"Wght").filter(|w| *w > 0.0 && *w < 1e7)?; - // "Scale with object": the weight follows the object's transform; otherwise it is absolute. - let scales = s.bool(ldsc, b"LDSc").unwrap_or(true); - let width = if scales { weight * local.scale() } else { weight }; - let data = s.bytes(lsty, b"Data").unwrap_or_default(); - // Byte 10 is the stroke's style: 0 none, 1 solid, 2 dashed, 3 a brush. A shape without a - // stroke still stores one (black, 1 px wide), with style 0. Identified on two documents their - // owner made, where every such stroke is invisible in Affinity's own PDF export, and checked - // against the public corpus's thumbnails. - if data.get(10) == Some(&0) { - return None; - } - let miter_limit = data.get(0..8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes).filter(|m| m.is_finite() && *m >= 1.0).unwrap_or(4.0); - // Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample; - // (2, 2) ends plain lines square and brush lines round; joins import round, which never - // looks wrong. - let (cap, join) = match (data.get(8).copied(), data.get(9).copied(), data.get(10).copied()) { - (Some(0), Some(0), _) => (Cap::Butt, Join::Miter), - (Some(0), Some(_), _) => (Cap::Butt, Join::Round), - (Some(2), Some(2), Some(3)) => (Cap::Round, Join::Round), - (Some(2), Some(2), _) => (Cap::Square, Join::Round), - _ => (Cap::Round, Join::Round), - }; - let align = match s.int(ldsc, b"LDSa") { - Some(1) => Align::Inside, - Some(2) => Align::Outside, - _ => Align::Center, - }; - let dash = match s.field(lsty, b"Patn") { - Some(Value::Array(a)) if a.len() > MAX_DASHES => { - r.warn("dash patterns of more than 64 lengths (imported as solid lines)"); - None - } - Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => { - let mut v: Vec = a.iter().filter_map(|x| if let Value::Float(f) = x { Some(*f) } else { None }).collect(); - while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) { - v.truncate(v.len() - 2); - } - let valid = !v.is_empty() && v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0); - valid.then(|| (v.iter().map(|x| x * width).collect(), s.f64(lsty, b"Phse").unwrap_or(0.0) * width)) - } - _ => None, - }; - if s.obj(lsty, b"Brus").is_some() { - r.warn("brush strokes (imported as plain strokes)"); - } - // The pressure curve sets the width along the path; one at full width all along is a plain - // stroke. Every curve read counts against the document's points: one at full width counts its - // points, and one that can't be read counts the most a curve may have. Once the points are - // used up the rest are not read. - const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)"; - let ldep = s.obj(ldsc, b"LDeP"); - if ldep.is_some() && r.budget.pressure == 0 { - r.warn(BEYOND); - } - let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) { - Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) { - Some(left) => { - r.budget.pressure = left; - (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points) - } - None => { - r.budget.pressure = 0; - r.warn(BEYOND); - None - } - }, - Some(None) => { - r.budget.pressure = r.budget.pressure.saturating_sub(crate::geometry::MAX_PRESSURE_CURVE_POINTS); - r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)"); - None - } - None => None, - }; - Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind, profile }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hsl_lightness_1_is_white_and_0_is_black() { - assert_eq!(hsl(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)); - assert_eq!(hsl(0.5, 1.0, 1.0), (1.0, 1.0, 1.0)); - assert_eq!(hsl(0.0, 1.0, 0.0), (0.0, 0.0, 0.0)); - let (r, g, b) = hsl(0.0, 1.0, 0.5); - assert!((r - 1.0).abs() < 1e-6 && g.abs() < 1e-6 && b.abs() < 1e-6); - } -} diff --git a/crates/affinity/src/preview.rs b/crates/affinity/src/preview.rs deleted file mode 100644 index d3341eeb1c..0000000000 --- a/crates/affinity/src/preview.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! The indexed PNG thumbnail Affinity stores next to the archive: Affinity's own render of the -//! document, at most 512 pixels on the long side in real files, never the document itself. - -use crate::Error; -use crate::container::header; - -pub const MAX_PREVIEW_BYTES: usize = 16 << 20; -pub const MAX_PREVIEW_DIMENSION: u32 = 4096; - -/// Borrowed embedded thumbnail, at its own dimensions, never the native document dimensions. -#[derive(Debug)] -pub struct Preview<'a> { - pub png: &'a [u8], - pub width: u32, - pub height: u32, -} - -fn bytes_at(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8], Error> { - let end = offset.checked_add(length).ok_or(Error::Malformed("offset overflow"))?; - bytes.get(offset..end).ok_or(Error::Malformed("truncated record")) -} - -fn le32(bytes: &[u8], offset: usize) -> Result { - let b = bytes_at(bytes, offset, 4)?; - Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?)) -} - -fn be32(bytes: &[u8], offset: usize) -> Result { - let b = bytes_at(bytes, offset, 4)?; - Ok(u32::from_be_bytes(b.try_into().map_err(|_| Error::Malformed("PNG integer"))?)) -} - -/// Read only the indexed `Thmb` record (identical in container versions 8 to 12), checking every PNG chunk CRC. Compressed -/// pixels must still be validated by the consuming image decoder, with allocation limits. -pub fn preview(bytes: &[u8]) -> Result, Error> { - let h = header(bytes)?; - if h.thumbnail_offset == 0 { - return Err(Error::Unsupported("no embedded preview")); - } - let offset = usize::try_from(h.thumbnail_offset).map_err(|_| Error::Malformed("thumbnail offset overflow"))?; - if offset < 72 { - return Err(Error::Malformed("thumbnail overlaps the file header")); - } - let record = bytes.get(offset..).ok_or(Error::Malformed("thumbnail offset outside file"))?; - if bytes_at(record, 0, 8)? != b"\xff\xff\xff\xffThmb" { - return Err(Error::Malformed("missing indexed thumbnail")); - } - if le32(record, 8)? != 1 || bytes_at(record, 28, 1)? != [1] { - return Err(Error::Unsupported("thumbnail record version or encoding")); - } - let size = usize::try_from(le32(record, 24)?).map_err(|_| Error::Limit("encoded size"))?; - if size > MAX_PREVIEW_BYTES { - return Err(Error::Limit("encoded preview exceeds 16 MiB")); - } - if le32(record, 16)? != 29 || le32(record, 20)? != 0 || u64::from(le32(record, 12)?) != size as u64 + 13 { - return Err(Error::Malformed("inconsistent thumbnail record lengths")); - } - let png = bytes_at(record, 29, size)?; - if bytes_at(png, 0, 8)? != b"\x89PNG\r\n\x1a\n" || be32(png, 8)? != 13 || bytes_at(png, 12, 4)? != b"IHDR" { - return Err(Error::Malformed("thumbnail is not a PNG")); - } - let width = be32(png, 16)?; - let height = be32(png, 20)?; - if width == 0 || height == 0 || width > MAX_PREVIEW_DIMENSION || height > MAX_PREVIEW_DIMENSION { - return Err(Error::Limit("preview dimensions must be 1..4096")); - } - // Bound work by bytes, not a file-supplied chunk count, and require exactly one complete PNG. - let mut pos = 8usize; - let (mut palette, mut image_data, mut image_data_ended) = (false, false, false); - loop { - let length = usize::try_from(be32(png, pos)?).map_err(|_| Error::Limit("PNG chunk length"))?; - let chunk_size = length.checked_add(12).ok_or(Error::Malformed("PNG chunk overflow"))?; - let chunk = bytes_at(png, pos, chunk_size)?; - let checksum_input = bytes_at(chunk, 4, chunk_size - 8)?; - if crc32fast::hash(checksum_input) != be32(chunk, chunk_size - 4)? { - return Err(Error::Malformed("PNG chunk checksum")); - } - let kind = bytes_at(chunk, 4, 4)?; - if !kind.iter().all(u8::is_ascii_alphabetic) { - return Err(Error::Malformed("PNG chunk type")); - } - match kind { - b"IHDR" if pos == 8 => {} - b"IHDR" => return Err(Error::Malformed("duplicate PNG header")), - b"PLTE" => { - if palette || image_data { - return Err(Error::Malformed("PNG palette order")); - } - palette = true; - } - b"IDAT" => { - if image_data_ended { - return Err(Error::Malformed("non-contiguous PNG image data")); - } - image_data = true; - } - b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")), - b"IEND" => {} - _ if kind.first().is_some_and(u8::is_ascii_uppercase) => { - return Err(Error::Unsupported("unknown critical PNG chunk")); - } - _ => {} - } - if image_data && kind != b"IDAT" { - image_data_ended = true; - } - // Native sample previews are plain, single-frame PNGs. Pixel allocation limits do not - // necessarily bound aggregate compressed metadata; leave these layouts unsupported. - if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") { - return Err(Error::Unsupported("compressed PNG metadata in the preview")); - } - if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") { - return Err(Error::Unsupported("animated PNG preview")); - } - pos = pos.checked_add(chunk_size).ok_or(Error::Malformed("PNG offset overflow"))?; - if kind == b"IEND" { - if length != 0 || pos != png.len() { - return Err(Error::Malformed("PNG end or trailing data")); - } - break; - } - } - Ok(Preview { png, width, height }) -} diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs deleted file mode 100644 index bb8c1c88b8..0000000000 --- a/crates/affinity/src/raster.rs +++ /dev/null @@ -1,650 +0,0 @@ -//! Pixel layers (`Rstr`) and placed images (`ImgN`). A placed image keeps its original file -//! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of -//! 256 bytes × 256 rows per channel, each its own archive entry. - -use std::collections::HashMap; - -use crate::Error; -use crate::model::{Affine, Image, Pixels, Reader}; -use crate::stream::{self, ObjId, Tag, Value}; - -/// Pixels decoded per layer (the content's bounding box, not the canvas). -const MAX_PIXELS: u64 = 64 << 20; -const TILE: usize = 256; -const TILE_BYTES: usize = TILE * TILE; - -struct CachedPixels { - tiles: HashMap>, - source: Option<(usize, Vec)>, -} - -pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(bitmap) = s.obj(id, b"Bitm") else { - r.warn("pixel layers without pixels"); - return Ok(None); - }; - if !s.is(bitmap, b"DyBm") { - r.warn("pixel layers stored in an unknown way"); - return Ok(None); - } - let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 { - return Ok(None); - } - // A placed image: the original file, byte for byte. - let has_tiles = s.field(bitmap, b"Sta1").is_some(); - if let Some(name) = s.entry(bitmap, b"Bckg").filter(|n| !n.is_empty()) - && (s.is(id, b"ImgN") || !has_tiles) - { - match original(r, name) { - // HEIF/HEIC (phone photos) and AVIF originals can't be decoded here: the same pixels - // stored as tiles are used instead (see `decode` when the tiles point back at the original). - Ok(bytes) if is_heif(&bytes) && has_tiles => {} - Ok(bytes) => return Ok(Some(Image { width, height, pixels: Pixels::Encoded(bytes), transform: world })), - Err(Error::Limit(e)) => return Err(Error::Limit(e)), - Err(_) => r.warn("an embedded image file that could not be read (its cached pixels were used)"), - } - } - // The content's bounding box, so a mostly empty canvas-sized layer stays small. - let crop = s - .field(id, b"BitR") - .and_then(|v| if let Value::Ints(i) = v { Some(i.clone()) } else { None }) - .filter(|v| v.len() == 4 && v[0] > i64::from(i32::MIN) + 1) - .map(|v| { - ( - v[0].clamp(0, i64::from(width)) as u32, - v[1].clamp(0, i64::from(height)) as u32, - v[2].clamp(0, i64::from(width)) as u32, - v[3].clamp(0, i64::from(height)) as u32, - ) - }) - .unwrap_or((0, 0, width, height)); - let source_tiles_only = - (1..=4).all(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|v| *v == Value::UInt(5)))); - if s.field(bitmap, b"Bckg").is_some() && has_tiles && !source_tiles_only && !s.is(id, b"ImgN") { - r.warn("edited placed images use their stored pixels"); - } - decode(r, bitmap, crop, world) -} - -/// An ISO base media file holding a HEIF image (HEIC, AVIF): `ftyp` with an image brand. -fn is_heif(bytes: &[u8]) -> bool { - bytes.get(4..8) == Some(b"ftyp".as_slice()) - && bytes.get(8..12).is_some_and(|brand| { - [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"mif1", b"msf1", b"avif", b"avis"].iter().any(|b| brand == b.as_slice()) - }) -} - -/// A mask layer (`MRst`): one channel of coverage as grey pixels (white shows, black hides), read -/// over `over` (document pixels) when given; outside its pixels a mask hides everything. -pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine, over: Option) -> Result, Error> { - let s = r.s; - let Some(bitmap) = s.obj(id, b"Bitm") else { return Ok(None) }; - let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 || !matches!(s.enumeration(bitmap, b"Frmt"), Some((6 | 7, _))) { - r.warn("pixel masks in an unknown format (imported without them)"); - return Ok(None); - } - let crop = match over.map(|o| crop_to(o, world, width, height)) { - Some(Some(c)) => c, - // What it masks lies outside it: all hidden, which one black pixel says as well. - Some(None) => return Ok(Some(Image { width: 1, height: 1, pixels: Pixels::Rgba8(vec![0, 0, 0, 255]), transform: world })), - None => (0, 0, width, height), - }; - decode(r, bitmap, crop, world) -} - -/// The bitmap pixels (x0, y0, x1, y1) of a `width` × `height` bitmap placed by `world` that cover -/// document rectangle `over`, one pixel wider all round; `None` if they don't overlap. -fn crop_to(over: crate::model::Rect, world: Affine, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> { - let inv = invert(world)?; - let pts = [(over.x0, over.y0), (over.x1, over.y0), (over.x1, over.y1), (over.x0, over.y1)].map(|(x, y)| inv.apply(crate::model::Point { x, y })); - let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); - for p in pts { - if !(p.x.is_finite() && p.y.is_finite()) { - return Some((0, 0, width, height)); - } - (x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)); - } - let clamp = |v: f64, max: u32| v.clamp(0.0, f64::from(max)) as u32; - let (cx0, cy0, cx1, cy1) = - (clamp(x0.floor() - 1.0, width), clamp(y0.floor() - 1.0, height), clamp(x1.ceil() + 1.0, width), clamp(y1.ceil() + 1.0, height)); - (cx1 > cx0 && cy1 > cy0).then_some((cx0, cy0, cx1, cy1)) -} - -fn invert(m: Affine) -> Option { - let [a, b, c, d, e, f] = m.0; - let det = a * d - b * c; - if !(det.is_finite() && det.abs() > 1e-12) { - return None; - } - let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det); - Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)])) -} - -/// An embedded document or symbol instance (`EmbN`), as the picture of it Affinity caches. -pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(cache) = s.obj(id, b"Bitm").and_then(|e| s.obj(e, b"Cach")) else { return Ok(None) }; - let Some(bbox) = s.obj(id, b"Bitm").and_then(|e| s.floats::<4>(e, b"ChBB")) else { return Ok(None) }; - let width = s.int(cache, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(cache, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 { - return Ok(None); - } - let [x0, y0, x1, y1] = bbox; - // The instance's origin is the centre of the embedded content (checked against the - // thumbnails of documents with embedded documents and SVG files). - let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); - let place = Affine([(x1 - x0) / f64::from(width), 0.0, 0.0, (y1 - y0) / f64::from(height), x0 - cx, y0 - cy]).then(world); - decode(r, cache, (0, 0, width, height), place) -} - -/// Decode the tiles of a bitmap inside `crop` (pixels), placed by `world` (bitmap pixels to document). -fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine) -> Result, Error> { - decode_within(r, bitmap, crop, world, MAX_PIXELS) -} - -/// [`decode`] with at most `max_pixels` decoded pixels. -fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine, max_pixels: u64) -> Result, Error> { - let s = r.s; - let (x0, y0, x1, y1) = crop; - if x1 <= x0 || y1 <= y0 { - return Ok(None); - } - let (w, h) = (x1 - x0, y1 - y0); - // Larger layers (mostly masks of whole spreads) are read at a half, a quarter… of their - // resolution: every `step`th pixel of every `step`th row. - let mut step = 1u32; - while u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step)) > max_pixels { - step *= 2; - if step > 1 << 12 { - r.warn("pixel layers too large to read (left out)"); - return Ok(None); - } - } - // Before anything is allocated: a layer's tiles can be flat colour, with nothing to extract. - let pixels = u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step)); - let Some(left) = r.budget.pixels.checked_sub(pixels) else { - r.warn("pixel layers beyond the pixels one document may hold"); - return Ok(None); - }; - r.budget.pixels = left; - let format = s.enumeration(bitmap, b"Frmt").map(|(f, _)| f); - let (channels, bps) = match format { - Some(0) => (4, 1), - Some(1) => (4, 2), - Some(6) => (1, 1), - Some(7) => (1, 2), - Some(4) => (5, 1), - _ => { - r.warn("pixel layers in grey, Lab or 32-bit formats"); - return Ok(None); - } - }; - let mut planes = Vec::with_capacity(channels); - // Current .af documents can keep level-zero tiles in their embedded JPEG/PNG instead of - // duplicating the pixels. State 5 is checked in the public Patchy embedded-jpeg fixture. - // Support only the observed, same-size RGBA8 image with a zero bitmap origin; other - // representations still receive the existing loss warning rather than guessing a mapping. - let needs_source = (1..=channels).any(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if a.contains(&Value::UInt(5)))); - let source = if needs_source && format == Some(0) && s.int(bitmap, b"LInf") == Some(0) && s.int(bitmap, b"TInf") == Some(0) { - if let Some(name) = s.entry(bitmap, b"Bckg") { - let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - // The whole source is decoded for every layer that reads it, so charge it all, not only the crop. - let Some(left) = r.budget.pixels.checked_sub(u64::from(width) * u64::from(height)) else { - return Err(Error::Limit("embedded image pixels")); - }; - r.budget.pixels = left; - match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) { - Ok(pixels) => Some((width as usize, pixels)), - Err(Error::Limit(e)) => return Err(Error::Limit(e)), - Err(_) => None, - } - } else { - None - } - } else { - None - }; - // Tiles kept only in an original that can't be decoded here are left empty (transparent). Where - // a tile's colour is in the original but its alpha is stored, as in CMYK layers, it would come - // out opaque white instead: such a layer (a HEIC photo in a CMYK document) is left out, and said. - if needs_source && source.is_none() && channels > 1 { - let states = |c: usize| match s.field(bitmap, &tag(b"Sta", c)) { - Some(Value::Array(a)) => a.clone(), - _ => Vec::new(), - }; - let alpha = states(channels); - let blank = (1..channels).any(|c| states(c).iter().enumerate().any(|(i, v)| *v == Value::UInt(5) && alpha.get(i) != Some(&Value::UInt(5)))); - if blank { - r.warn("placed images whose pixels are only in an original the reader can't decode, such as HEIC photos (left out)"); - return Ok(None); - } - } - if step > 1 { - // Its stored tiles must fit what is left of the import's extraction budget. - let stored: usize = (1..=channels).map(|c| tiles_in(s, bitmap, c, bps, (x0, y0, w, h)).len()).sum(); - if stored.saturating_mul(TILE_BYTES) > r.archive.remaining().max_total { - r.warn("pixel layers too large to read (left out)"); - return Ok(None); - } - r.warn("pixel layers larger than 64 megapixels (read at a lower resolution)"); - } - let mut cache = CachedPixels { tiles: HashMap::new(), source }; - for c in 1..=channels { - planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), step, &mut cache)?); - } - let (w, h) = (w.div_ceil(step), h.div_ceil(step)); - let n = (w as usize) * (h as usize); - let k = f64::from(step); - let transform = Affine([k, 0.0, 0.0, k, f64::from(x0), f64::from(y0)]).then(world); - if channels == 5 { - // Ink amounts and alpha as stored (8 bits), interleaved. - let mut cmyka = vec![0u8; n * 5]; - for (i, px) in cmyka.as_chunks_mut::<5>().0.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate() { - *v = planes.get(c).and_then(|p| p.get(i)).copied().unwrap_or(0); - } - } - return Ok(Some(Image { width: w, height: h, pixels: Pixels::Cmyka8(cmyka), transform })); - } - let mut rgba = vec![0u8; n * 4]; - let sample = |p: &Vec, i: usize| -> f64 { - if bps == 2 { - f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0 - } else { - f64::from(p.get(i).copied().unwrap_or(0)) / 255.0 - } - }; - for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let v: Vec = planes.iter().map(|p| sample(p, i)).collect(); - let (r2, g, b, a) = if channels == 1 { (v[0], v[0], v[0], 1.0) } else { (v[0], v[1], v[2], v[3]) }; - px.copy_from_slice(&[r2, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); - } - Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform })) -} - -/// The original image file: entry `c/N` is a stream whose root (`Blck`) holds it as `Data`. -fn original(r: &mut Reader, name: &str) -> Result, Error> { - let bytes = r.archive.read(name)?; - let s = stream::parse(&bytes)?; - let root = s.object(s.root).ok_or(Error::Malformed("embedded image"))?; - match root.get(Tag::of(b"Data")) { - Some(Value::Blob(b)) if !b.is_empty() => Ok(b.clone()), - _ => Err(Error::Malformed("embedded image without data")), - } -} - -/// Decode the source under the same pixel budget as tiled layers, checking its actual -/// dimensions before allocating decoded pixels. Only JPEG and PNG sources are supported. -fn source_pixels(bytes: &[u8], width: u32, height: u32) -> Result, Error> { - use image::{ImageFormat, ImageReader}; - use std::io::Cursor; - - if u64::from(width) * u64::from(height) > MAX_PIXELS { - return Err(Error::Limit("embedded image pixels")); - } - let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| Error::Malformed("embedded image format"))?; - if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png)) { - return Err(Error::Unsupported("embedded source pixel format")); - } - let dimensions = ImageReader::new(Cursor::new(bytes)) - .with_guessed_format() - .map_err(|_| Error::Malformed("embedded image format"))? - .into_dimensions() - .map_err(|_| Error::Malformed("embedded image dimensions"))?; - if dimensions != (width, height) || width == 0 || height == 0 { - return Err(Error::Malformed("embedded source and bitmap dimensions differ")); - } - let mut limits = image::Limits::default(); - limits.max_image_width = Some(width); - limits.max_image_height = Some(height); - limits.max_alloc = Some(MAX_PIXELS * 8); - reader.limits(limits); - let decoded = reader.decode().map_err(|e| match e { - image::ImageError::Limits(_) => Error::Limit("embedded image decoding"), - _ => Error::Malformed("embedded image decoding"), - })?; - Ok(decoded.into_rgba8().into_raw()) -} - -fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] { - [prefix[0], prefix[1], prefix[2], b'0' + c as u8] -} - -/// Channel `c`'s tile grid: (tiles across, tiles down, each tile's state). -fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usize, Vec) { - let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0); - let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE)); - let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE)); - // A grid larger than the bitmap has tiles no crop can reach: don't convert or scan them on every reference. - let tiles = width.saturating_mul(bps).div_ceil(TILE).saturating_mul(height.div_ceil(TILE)); - let states: Vec = match s.field(bitmap, &tag(b"Sta", c)) { - Some(Value::Array(a)) => a.iter().take(tiles).map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(), - _ => Vec::new(), - }; - (tw, th, states) -} - -/// The stored tiles (state 4) of channel `c` that overlap the crop, by their index in `Idx`. -fn tiles_in(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize, (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec { - let (tw, th, states) = grid(s, bitmap, c, bps); - let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps); - let (py0, py1) = (y0 as usize, (y0 + h) as usize); - let mut out = Vec::new(); - let mut next = 0usize; - for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) { - if *state != 4 { - continue; - } - let (ox, oy) = ((t % tw.max(1)) * TILE, (t / tw.max(1)) * TILE); - if !(ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0) { - out.push(next); - } - next += 1; - } - out -} - -/// One channel of level 0, cropped to (x0, y0, w, h) pixels and taking every `step`th pixel of -/// every `step`th row; `bps` bytes per sample. -fn plane( - r: &mut Reader, - bitmap: ObjId, - c: usize, - bps: usize, - (x0, y0, w, h): (u32, u32, u32, u32), - step: u32, - cache: &mut CachedPixels, -) -> Result, Error> { - let CachedPixels { tiles: cache, source } = cache; - let s = r.s; - let (tw, th, states) = grid(s, bitmap, c, bps); - let tiles = s.objs(bitmap, &tag(b"Idx", c)); - let at = Crop { bps, x0: x0 as usize, y0: y0 as usize, w: w as usize, h: h as usize, step: step.max(1) as usize }; - let row = at.w.div_ceil(at.step) * bps; - let mut out = vec![0u8; row * at.h.div_ceil(at.step)]; - let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps); - let (py0, py1) = (y0 as usize, (y0 + h) as usize); - let mut next = 0usize; - for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) { - let (ty, tx) = (t / tw.max(1), t % tw.max(1)); - let fill = match state { - 0 | 1 => None, - 2 => Some(0xFF), - 4 => { - let Some(blck) = tiles.get(next).copied() else { return Err(Error::Malformed("missing pixel tile")) }; - next += 1; - let (ox, oy) = (tx * TILE, ty * TILE); - if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 { - continue; - } - let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string(); - let read = |r: &mut Reader| -> Result, Error> { - let mut data = r.archive.read(&name)?; - // Older files wrap a tile in a one-field stream: header, then a 64 KiB blob. - if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") { - data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec(); - } - if data.len() != TILE_BYTES { - return Err(Error::Malformed("pixel tile size")); - } - Ok(data) - }; - // A layer read at a lower resolution is too large to keep its tiles around. - if at.step > 1 { - let tile = read(r)?; - copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); - continue; - } - if !cache.contains_key(&name) { - let data = read(r)?; - cache.insert(name.clone(), data); - } - let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?; - copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); - continue; - } - 3 => { - r.warn("32-bit pixel layers"); - None - } - 5 => { - if let Some((source_width, pixels)) = source.as_ref() { - let (ox, oy) = (tx * TILE, ty * TILE); - copy(&mut out, &at, (ox, oy), |x, y| pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0)); - continue; - } - r.warn("pixel layers drawn from an embedded image (left empty)"); - None - } - _ => return Err(Error::Malformed("unknown pixel tile state")), - }; - if let Some(v) = fill { - copy(&mut out, &at, (tx * TILE, ty * TILE), |_, _| v); - } - } - Ok(out) -} - -/// Where a plane's pixels come from: the crop (pixels) and the sampling step. -struct Crop { - bps: usize, - x0: usize, - y0: usize, - w: usize, - h: usize, - step: usize, -} - -/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane, keeping every -/// `step`th pixel of every `step`th row. -fn copy(out: &mut [u8], c: &Crop, (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) { - let row = c.w.div_ceil(c.step) * c.bps; - let (bx0, bx1) = (c.x0 * c.bps, (c.x0 + c.w) * c.bps); - for y in oy.max(c.y0)..(oy + TILE).min(c.y0 + c.h) { - if !(y - c.y0).is_multiple_of(c.step) { - continue; - } - let out_row = (y - c.y0) / c.step * row; - for x in ox.max(bx0)..(ox + TILE).min(bx1) { - let px = x / c.bps - c.x0; - if !px.is_multiple_of(c.step) { - continue; - } - if let Some(b) = out.get_mut(out_row + px / c.step * c.bps + x % c.bps) { - *b = at(x - ox, y - oy); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::Kind; - use crate::synth::{self, F, Method, tag}; - - #[test] - fn heif_originals_are_recognised_by_their_brand() { - assert!(is_heif(b"\0\0\0\x18ftypheic\0\0\0\0")); - assert!(is_heif(b"\0\0\0\x1cftypavif")); - assert!(!is_heif(b"\0\0\0\x18ftypisom"), "a video is not a photo"); - assert!(!is_heif(&png())); - assert!(!is_heif(b"ftyp")); - } - - fn png() -> Vec { - let pixels = image::RgbaImage::from_fn(300, 2, |x, y| image::Rgba([(x % 251) as u8, (y * 31) as u8, 77, 255])); - let mut bytes = std::io::Cursor::new(Vec::new()); - pixels.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); - bytes.into_inner() - } - - /// An original synthetic mixed source/cache bitmap. It exercises reader recovery, - /// not a claim that Affinity itself accepts the synthetic container. - fn fixture(source: &[u8], origin: i32) -> Vec { - fixture_in(source, origin, false) - } - - /// `cmyk`: a CMYK bitmap whose colour tiles are all in the source and whose alpha is stored. - fn fixture_in(source: &[u8], origin: i32, cmyk: bool) -> Vec { - let channels = if cmyk { 5 } else { 4 }; - let mut bitmap = vec![ - (tag(b"Frmt"), F::Enum(if cmyk { 4 } else { 0 }, 0)), - (tag(b"BmpW"), F::I32(300)), - (tag(b"BmpH"), F::I32(2)), - (tag(b"LInf"), F::I32(origin)), - (tag(b"TInf"), F::I32(0)), - (tag(b"Bckg"), F::Entry("c/1".into())), - ]; - for c in 1..=channels { - let states = match (cmyk, c) { - (false, _) => vec![5, 4], - (true, 5) => vec![4, 4], - (true, _) => vec![5, 5], - }; - bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(2))); - bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1))); - bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(states))); - bitmap.push(( - tag(&super::tag(b"Idx", c)), - F::Shared(vec![F::Def(c as u32, vec![tag(b"Blck")], vec![(tag(b"Data"), F::Entry(format!("d/{c}")))])]), - )); - } - let mut crop = vec![0x17]; - crop.extend(tag(b"BitR").0.to_le_bytes()); - crop.extend([250i32, 0, 270, 2].into_iter().flat_map(i32::to_le_bytes)); - let raster = F::Def( - 10, - vec![tag(b"Rstr")], - vec![ - (tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap)), - (tag(b"BitR"), F::Raw(crop)), - (tag(b"Xfrm"), F::F64s(vec![0.0, -2.0, 10.0, 2.0, 0.0, 20.0])), - ], - ); - let spread = F::Def(11, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared(vec![raster]))]); - let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); - let mut blob = vec![0x2d]; - blob.extend(tag(b"Data").0.to_le_bytes()); - blob.extend((source.len() as u32).to_le_bytes()); - blob.extend(source); - let block = synth::stream(&[(tag(b"Data"), F::Raw(blob))]); - let tiles: Vec<_> = [200u8, 10, 30, 255, 255].into_iter().map(|v| vec![v; TILE_BYTES]).collect(); - let names: Vec = (1..=channels).map(|c| format!("d/{c}")).collect(); - let mut entries = vec![("doc.dat", doc.as_slice(), Method::Zlib), ("c/1", block.as_slice(), Method::Zlib)]; - for (name, tile) in names.iter().zip(&tiles) { - entries.push((name.as_str(), tile.as_slice(), Method::Zlib)); - } - synth::container(&entries, None) - } - - #[test] - fn a_cmyk_layer_whose_colours_are_only_in_an_unreadable_original_is_left_out_not_white() { - let doc = crate::read(&fixture_in(b"\0\0\0\x18ftypheic not decodable", 0, true), crate::Limits::default()).unwrap(); - assert!(doc.warnings.iter().any(|w| w.starts_with("placed images whose pixels are only in an original")), "{:?}", doc.warnings); - assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported), "{:?}", doc.spreads[0].nodes[0].kind); - } - - #[test] - fn layers_over_the_pixel_budget_are_read_at_a_lower_resolution() { - let bytes = fixture(&png(), 0); - let mut archive = crate::Archive::open(&bytes, crate::Limits::default()).unwrap(); - let doc = archive.read("doc.dat").unwrap(); - let s = stream::parse(&doc).unwrap(); - let bitmap = s.objects.iter().position(|o| o.class == Tag::of(b"DyBm")).unwrap(); - let mut r = Reader::new(&s, &mut archive, Affine::IDENTITY, 0); - // 20 × 2 pixels over a budget of 10: every other pixel of every other row. - let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 10).unwrap().unwrap(); - assert_eq!((image.width, image.height), (10, 1)); - assert_eq!(image.transform, Affine([2.0, 0.0, 0.0, 2.0, 250.0, 0.0]), "each pixel covers two"); - let Pixels::Rgba8(pixels) = &image.pixels else { panic!() }; - for x in 0..10 { - let sx = 2 * x; - let expected = if sx + 250 < 256 { [((sx + 250) % 251) as u8, 0, 77, 255] } else { [200, 10, 30, 255] }; - assert_eq!(&pixels[x * 4..x * 4 + 4], &expected, "pixel {x}"); - } - assert!(r.warnings.contains_key("pixel layers larger than 64 megapixels (read at a lower resolution)")); - // Within budget, nothing changes. - let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 40).unwrap().unwrap(); - assert_eq!((image.width, image.height), (20, 2)); - } - - #[test] - fn source_tiles_and_cached_edits_survive_crop_rotation_and_tile_boundaries() { - let doc = crate::read(&fixture(&png(), 0), crate::Limits::default()).unwrap(); - assert_eq!(doc.warnings, ["edited placed images use their stored pixels"]); - let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() }; - assert_eq!((image.width, image.height), (20, 2)); - assert_eq!(image.transform, Affine([0.0, 2.0, -2.0, 0.0, 10.0, 520.0])); - let Pixels::Rgba8(pixels) = &image.pixels else { panic!() }; - for y in 0..2 { - for x in 0..20 { - let expected = if x + 250 < 256 { [((x + 250) % 251) as u8, (y * 31) as u8, 77, 255] } else { [200, 10, 30, 255] }; - assert_eq!(&pixels[(y * 20 + x) * 4..(y * 20 + x + 1) * 4], &expected); - } - } - } - - #[test] - fn unreadable_sources_and_unknown_origins_preserve_cached_edits_and_warn() { - for bytes in [fixture(b"invalid image", 0), fixture(&png(), 1)] { - let doc = crate::read(&bytes, crate::Limits::default()).unwrap(); - assert!(doc.warnings.iter().any(|w| w == "pixel layers drawn from an embedded image (left empty) (4×)")); - let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() }; - let Pixels::Rgba8(pixels) = &image.pixels else { panic!() }; - assert_eq!(&pixels[..4], &[0, 0, 0, 0]); - assert_eq!(&pixels[6 * 4..7 * 4], &[200, 10, 30, 255]); - } - } - - /// Pixel layers of one flat colour: nothing in the archive but `doc.dat` (state 2 is a tile - /// of 0xFF). Written by hand for the reader, like [`fixture`]. - fn flat_layers(count: u32, side: i32) -> Vec { - let layer = |i: u32| { - let mut bitmap = vec![(tag(b"Frmt"), F::Enum(0, 0)), (tag(b"BmpW"), F::I32(side)), (tag(b"BmpH"), F::I32(side))]; - for c in 1..=4 { - bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(1))); - bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1))); - bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(vec![2]))); - } - F::Def(10 + i, vec![tag(b"Rstr")], vec![(tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap))]) - }; - let spread = F::Def(1, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared((0..count).map(layer).collect()))]); - let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); - synth::container(&[("doc.dat", &doc, Method::Zlib)], None) - } - - /// #1704: the pixels of all pixel layers together are bounded, also when the archive holds - /// no data for them: the layers past the allowance are left out with a note. - #[test] - fn pixel_layers_share_one_allowance_for_the_whole_document() { - let file = flat_layers(5, 16); - let layers = |pixels: u64| { - let doc = crate::model::read_within(&file, crate::Limits::default(), pixels).unwrap(); - let n = doc.spreads[0].nodes.iter().filter(|n| matches!(n.kind, Kind::Image(_))).count(); - (n, doc.warnings) - }; - assert_eq!(layers(5 * 256), (5, vec![])); - let (kept, warnings) = layers(3 * 256 + 255); - assert_eq!(kept, 3); - assert_eq!(warnings.len(), 1); - assert!(warnings[0].contains("pixel layers beyond the pixels one document may hold"), "{warnings:?}"); - assert_eq!(crate::read(&file, crate::Limits::default()).unwrap().spreads[0].nodes.len(), 5); - } - - #[test] - fn embedded_source_dimensions_and_pixel_budget_are_checked_before_decode() { - let bytes = png(); - assert!(matches!(source_pixels(&bytes, 299, 2), Err(Error::Malformed(_)))); - assert!(matches!(source_pixels(&bytes, u32::MAX, u32::MAX), Err(Error::Limit(_)))); - assert_eq!(source_pixels(&bytes, 300, 2).unwrap().len(), 300 * 2 * 4); - } -} diff --git a/crates/affinity/src/shapes.rs b/crates/affinity/src/shapes.rs deleted file mode 100644 index a2503539f4..0000000000 --- a/crates/affinity/src/shapes.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Parametric shapes: Affinity stores the shape's parameters and its box, never the outline. -//! Formulas were fitted to Affinity's own renders (the document thumbnails) of public files. - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -use crate::model::{Affine, Path, Point, Reader, SubPath}; -use crate::stream::{ObjId, Tag, Value}; - -/// Handle length of a quarter circle of radius 1. -const KAPPA: f64 = 0.552_284_749_830_793_4; -/// Vertices of a polygon or star. -const MAX_SIDES: i64 = 10_000; - -/// The last value of a tag: a shape changed from one kind to another keeps a stale first block. -fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> { - r.s.object(id)?.get_last(Tag::of(tag)) -} - -fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option { - match last(r, id, tag)? { - Value::Float(f) if f.is_finite() => Some(*f), - Value::UInt(u) => Some(*u as f64), - Value::Int(i) => Some(*i as f64), - _ => None, - } -} - -fn sides(r: &Reader, id: ObjId, tag: &[u8; 4], default: f64) -> usize { - let n = num(r, id, tag).unwrap_or(default).round(); - n.clamp(3.0, MAX_SIDES as f64) as usize -} - -fn pt(x: f64, y: f64) -> Point { - Point { x, y } -} - -fn polygon(pts: impl IntoIterator) -> Option { - let mut it = pts.into_iter(); - let start = it.next()?; - let segments = it.map(|p| [p, p, p]).collect(); - Some(SubPath { start, segments, closed: true }) -} - -/// Outline of `shape` (a `Shpe` object) in the node box `b` = (x0, y0, x1, y1). -pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option { - let [x0, y0, x1, y1] = b; - let (w, h) = (x1 - x0, y1 - y0); - let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, w / 2.0, h / 2.0); - let on_ellipse = |a: f64, f: f64| pt(cx + f * rx * a.cos(), cy + f * ry * a.sin()); - let class = r.s.class(shape)?; - let sub = match &class.0.to_be_bytes() { - b"ShNR" | b"ShRR" => { - // Only the four corners' entries can matter: longer arrays are read no further. - let types: Vec> = match last(r, shape, b"CTyp") { - Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), - _ => Vec::new(), - }; - let radii: Vec = match last(r, shape, b"ShCR") { - Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), - _ => Vec::new(), - }; - // Corners follow the first one (top left) unless they were unlocked; then each has - // its own radius and type, clockwise from the top left. - let locked = !matches!(last(r, shape, b"Lock"), Some(Value::Bool(false))); - let corners: [(f64, Option); 4] = std::array::from_fn(|i| { - let i = if locked { 0 } else { i }; - (radii.get(i).copied().unwrap_or(0.0), types.get(i).copied().flatten()) - }); - if types.is_empty() || corners.iter().all(|(f, _)| *f == 0.0) { - polygon([pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)])? - } else { - if corners.iter().any(|(f, t)| *f > 0.0 && !matches!(t, Some(0 | 1 | 4))) { - r.warn("rectangles with concave or other corner types (imported with round corners)"); - } - let absolute = r.s.bool(shape, b"AbSz") == Some(true); - let [a, b2, c, d, ..] = world.0; - let (sx, sy) = ((a * a + b2 * b2).sqrt(), (c * c + d * d).sqrt()); - cornered_rect( - b, - corners.map(|(f, t)| { - let (crx, cry) = if !absolute { - (f * w.min(h), f * w.min(h)) - } else if sx > 0.0 && sy > 0.0 { - // An absolute radius is in document pixels, whatever the node's scale. - (f / sx, f / sy) - } else { - (0.0, 0.0) - }; - (crx, cry, t == Some(1)) - }), - ) - } - } - b"ShpE" => ellipse(cx, cy, rx, ry), - b"ShPy" => { - let n = sides(r, shape, b"Side", 5.0); - let a = |i: usize| -FRAC_PI_2 + TAU * i as f64 / n as f64; - if r.s.object(shape).is_some_and(|_| matches!(last(r, shape, b"Smth"), Some(Value::Bool(true)))) { - // Smoothed: tangent handles of length curv·4/3·tan(π/2n) along the inscribed ellipse. - let k = num(r, shape, b"Curv").unwrap_or(0.0) * 4.0 / 3.0 * (PI / (2.0 * n as f64)).tan(); - let v = |i: usize| on_ellipse(a(i), 1.0); - let t = |i: usize| pt(-rx * a(i).sin(), ry * a(i).cos()); - let segments = (0..n) - .map(|i| { - let (p, q, tp, tq) = (v(i), v(i + 1), t(i), t(i + 1)); - [pt(p.x + k * tp.x, p.y + k * tp.y), pt(q.x - k * tq.x, q.y - k * tq.y), q] - }) - .collect(); - SubPath { start: v(0), segments, closed: true } - } else { - polygon((0..n).map(|i| on_ellipse(a(i), 1.0)))? - } - } - b"ShSt" => { - let n = sides(r, shape, b"Pnts", 5.0); - let q = num(r, shape, b"IRad").unwrap_or(0.382).clamp(0.0, 1.0); - if [b"CrcI", b"CrcO", b"CrvL", b"CrvR"].iter().any(|t| num(r, shape, t).is_some_and(|v| v.abs() > 1e-9)) { - r.warn("stars with rounded or curved points (imported with sharp points)"); - } - polygon((0..2 * n).map(|i| on_ellipse(-FRAC_PI_2 + PI * i as f64 / n as f64, if i % 2 == 0 { 1.0 } else { q })))? - } - b"ShSS" => { - let n = sides(r, shape, b"Side", 5.0); - let ri = num(r, shape, b"COut").unwrap_or(0.5).clamp(0.0, 1.0); - let step = PI / n as f64; - let (l, hw, inner) = (step.cos(), ri * step.sin(), ri * step.cos()); - polygon((0..n).flat_map(|k| { - let phi = -FRAC_PI_2 + step + TAU * k as f64 / n as f64; - let (c, s) = (phi.cos(), phi.sin()); - [(inner, -hw), (l, -hw), (l, hw), (inner, hw)].map(|(u, v)| pt(cx + rx * (u * c - v * s), cy + ry * (u * s + v * c))) - }))? - } - b"ShPi" => { - let raw_start = num(r, shape, b"AngS").unwrap_or(0.0); - let raw_end = num(r, shape, b"AngE").unwrap_or(TAU); - // Normalize in constant time. Repeatedly adding TAU can hang on finite values - // large enough that floating-point addition no longer changes the endpoint. - let start = raw_start.rem_euclid(TAU); - let delta = raw_end - raw_start; - let sweep = if raw_end >= raw_start { - delta.min(TAU) - } else if delta.is_finite() { - delta.rem_euclid(TAU) - } else { - (raw_end.rem_euclid(TAU) - start).rem_euclid(TAU) - }; - let inner = num(r, shape, b"IRad").unwrap_or(0.0).clamp(0.0, 1.0); - pie(cx, cy, rx, ry, start, start + sweep, inner) - } - b"ShpT" => { - let p = num(r, shape, b"Pos ").unwrap_or(0.5); - polygon([pt(x0 + p * w, y0), pt(x1, y1), pt(x0, y1)])? - } - b"ShTz" => { - let (l, rr) = (num(r, shape, b"PosL").unwrap_or(0.25), num(r, shape, b"PosR").unwrap_or(0.75)); - polygon([pt(x0 + l * w, y0), pt(x0 + rr * w, y0), pt(x1, y1), pt(x0, y1)])? - } - _ => { - r.warn("cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse)"); - ellipse(cx, cy, rx, ry) - } - }; - Some(Path { subpaths: vec![sub] }) -} - -pub(crate) fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { - SubPath { start: pt(x0, y0), segments: [pt(x1, y0), pt(x1, y1), pt(x0, y1)].map(|p| [p, p, p]).to_vec(), closed: true } -} - -fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let (kx, ky) = (KAPPA * rx, KAPPA * ry); - SubPath { - start: pt(cx + rx, cy), - segments: vec![ - [pt(cx + rx, cy + ky), pt(cx + kx, cy + ry), pt(cx, cy + ry)], - [pt(cx - kx, cy + ry), pt(cx - rx, cy + ky), pt(cx - rx, cy)], - [pt(cx - rx, cy - ky), pt(cx - kx, cy - ry), pt(cx, cy - ry)], - [pt(cx + kx, cy - ry), pt(cx + rx, cy - ky), pt(cx + rx, cy)], - ], - closed: true, - } -} - -/// A rectangle whose corners (top left, top right, bottom right, bottom left) are each rounded, -/// or cut straight across, by their (horizontal, vertical) radii. Two radii that don't fit along -/// one side shrink in proportion until they do. -fn cornered_rect([x0, y0, x1, y1]: [f64; 4], corners: [(f64, f64, bool); 4]) -> SubPath { - let fit = |r: f64, pair: f64, side: f64| if pair > side { side * (r / pair) } else { r }; - let [tl, tr, br, bl] = corners; - let (w, h) = (x1 - x0, y1 - y0); - let rx = [fit(tl.0, tl.0 + tr.0, w), fit(tr.0, tl.0 + tr.0, w), fit(br.0, bl.0 + br.0, w), fit(bl.0, bl.0 + br.0, w)]; - let ry = [fit(tl.1, tl.1 + bl.1, h), fit(tr.1, tr.1 + br.1, h), fit(br.1, tr.1 + br.1, h), fit(bl.1, tl.1 + bl.1, h)]; - let (kx, ky) = (rx.map(|r| (1.0 - KAPPA) * r), ry.map(|r| (1.0 - KAPPA) * r)); - // (where the corner leaves the previous side, its two handles, where it joins the next side) - let arcs = [ - [pt(x1 - rx[1], y0), pt(x1 - kx[1], y0), pt(x1, y0 + ky[1]), pt(x1, y0 + ry[1])], - [pt(x1, y1 - ry[2]), pt(x1, y1 - ky[2]), pt(x1 - kx[2], y1), pt(x1 - rx[2], y1)], - [pt(x0 + rx[3], y1), pt(x0 + kx[3], y1), pt(x0, y1 - ky[3]), pt(x0, y1 - ry[3])], - [pt(x0, y0 + ry[0]), pt(x0, y0 + ky[0]), pt(x0 + kx[0], y0), pt(x0 + rx[0], y0)], - ]; - let mut segments = Vec::with_capacity(8); - for ([s, c1, c2, e], straight) in arcs.into_iter().zip([tr.2, br.2, bl.2, tl.2]) { - segments.push([s, s, s]); - if s != e { - segments.push(if straight { [e, e, e] } else { [c1, c2, e] }); - } - } - SubPath { start: pt(x0 + rx[0], y0), segments, closed: true } -} - -/// Elliptical arc from angle `a0` to `a1` (radians, measured y-up as Affinity's pie angles are), -/// as cubic segments of at most a quarter turn. -fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, out: &mut Vec<[Point; 3]>) { - let n = ((a1 - a0).abs() / FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize; - let step = (a1 - a0) / n as f64; - let k = 4.0 / 3.0 * (step / 4.0).tan(); - let p = |a: f64| pt(cx + rx * a.cos(), cy - ry * a.sin()); - let d = |a: f64| pt(-rx * a.sin(), -ry * a.cos()); - for i in 0..n { - let (s, e) = (a0 + step * i as f64, a0 + step * (i + 1) as f64); - let (ps, pe, ds, de) = (p(s), p(e), d(s), d(e)); - out.push([pt(ps.x + k * ds.x, ps.y + k * ds.y), pt(pe.x - k * de.x, pe.y - k * de.y), pe]); - } -} - -fn pie(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, inner: f64) -> SubPath { - let start = pt(cx + rx * a0.cos(), cy - ry * a0.sin()); - let mut segments = Vec::new(); - arc(cx, cy, rx, ry, a0, a1, &mut segments); - if inner > 0.0 { - let p = pt(cx + inner * rx * a1.cos(), cy - inner * ry * a1.sin()); - segments.push([p, p, p]); - arc(cx, cy, inner * rx, inner * ry, a1, a0, &mut segments); - } else { - let c = pt(cx, cy); - segments.push([c, c, c]); - } - SubPath { start, segments, closed: true } -} - -/// A polyline with circular corners of the given radii (Affinity's live corners on curves). -pub(crate) fn fillet(pts: &[(Point, f64)], closed: bool) -> SubPath { - let n = pts.len(); - let get = |i: isize| -> Option { - if closed { pts.get(i.rem_euclid(n as isize) as usize).map(|p| p.0) } else { usize::try_from(i).ok().and_then(|i| pts.get(i)).map(|p| p.0) } - }; - let mut corners: Vec<(Point, Point, Point, Point)> = Vec::with_capacity(n); - for (i, (p, radius)) in pts.iter().enumerate() { - let (prev, next) = (get(i as isize - 1), get(i as isize + 1)); - let (Some(a), Some(b)) = (prev, next) else { - corners.push((*p, *p, *p, *p)); - continue; - }; - let (u1, l1) = unit(*p, a); - let (u2, l2) = unit(*p, b); - let cos = (u1.x * u2.x + u1.y * u2.y).clamp(-1.0, 1.0); - let phi = cos.acos(); - if *radius <= 0.0 || phi < 1e-6 || (PI - phi) < 1e-6 { - corners.push((*p, *p, *p, *p)); - continue; - } - let t = (radius / (phi / 2.0).tan()).min(l1 / 2.0).min(l2 / 2.0); - let r = t * (phi / 2.0).tan(); - let k = 4.0 / 3.0 * ((PI - phi) / 4.0).tan() * r; - let s = pt(p.x + u1.x * t, p.y + u1.y * t); - let e = pt(p.x + u2.x * t, p.y + u2.y * t); - corners.push((s, pt(s.x - u1.x * k, s.y - u1.y * k), pt(e.x - u2.x * k, e.y - u2.y * k), e)); - } - let Some(first) = corners.first().copied() else { return SubPath { start: pt(0.0, 0.0), segments: vec![], closed } }; - let mut segments = Vec::with_capacity(2 * n); - let mut cur = first.0; - let start = cur; - for (i, (s, c1, c2, e)) in corners.iter().enumerate() { - if i > 0 { - segments.push([cur, *s, *s]); - } - if s != e { - segments.push([*c1, *c2, *e]); - } - cur = *e; - } - if closed && cur != start { - segments.push([cur, start, start]); - } - SubPath { start, segments, closed } -} - -fn unit(from: Point, to: Point) -> (Point, f64) { - let (dx, dy) = (to.x - from.x, to.y - from.y); - let l = (dx * dx + dy * dy).sqrt(); - if l > 0.0 { (pt(dx / l, dy / l), l) } else { (pt(0.0, 0.0), 0.0) } -} diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs deleted file mode 100644 index 9d31f35e70..0000000000 --- a/crates/affinity/src/stream.rs +++ /dev/null @@ -1,491 +0,0 @@ -//! The tagged object stream inside `doc.dat`: a self-describing tree of objects whose fields carry -//! a type code and a four-character tag. Parsing needs no schema; unknown fields are kept, so the -//! document mapping can name what it could not import. - -use crate::Error; -use crate::container::Cursor; - -/// A four-character tag in its readable order (`Desc`, `Chld`). -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Tag(pub u32); - -impl Tag { - pub const fn of(s: &[u8; 4]) -> Self { - Self(u32::from_be_bytes(*s)) - } -} - -impl std::fmt::Debug for Tag { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", String::from_utf8_lossy(&self.0.to_be_bytes())) - } -} - -impl std::fmt::Display for Tag { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self, f) - } -} - -/// Index of an object in [`Stream::objects`]. -pub type ObjId = usize; - -#[derive(Debug, Clone, PartialEq)] -pub enum Value { - Int(i64), - UInt(u64), - Float(f64), - Bool(bool), - Enum { - id: u16, - version: u16, - }, - Str(String), - /// Fixed-length vectors of i32/f32/f64 (points, rectangles, transforms). - Ints(Vec), - Floats(Vec), - /// Fixed-size record (curve nodes, ids) or fixed-size struct (colour components). - Bytes(Vec), - Blob(Vec), - /// Name of another archive entry (raster tiles, embedded files). - Entry(String), - Flags(u64), - /// `None` is a null object. - Obj(Option), - Array(Vec), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Root, - /// Defined once and referenced by id elsewhere. - Shared, - Inline, - /// Untagged fields identified by position (curve data). - Positional, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Object { - pub class: Tag, - pub kind: Kind, - /// Class chain, most derived first (`ShpN`, `VNod`, `Node`). - pub chain: Vec, - /// Fields in stream order; positional fields have tag 0. - pub fields: Vec<(Tag, Value)>, - /// For objects with many fields: each tag with the positions of its first and last field, - /// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up - /// again on every visit). Built by [`Object::index`]; empty for small objects. - index: Vec<(Tag, u32, u32)>, -} - -/// Objects with more fields than this get an [`Object::index`]; fewer are scanned. -const INDEXED_FIELDS: usize = 16; - -impl Object { - pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { - let mut o = Self { class, kind, chain, fields, index: Vec::new() }; - o.index(); - o - } - - /// (Re)build the tag index after `fields` changed. - fn index(&mut self) { - self.index.clear(); - if self.fields.len() <= INDEXED_FIELDS { - return; - } - let mut index: Vec<(Tag, u32, u32)> = Vec::new(); - if index.try_reserve_exact(self.fields.len()).is_err() { - return; - } - // Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values. - index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i)))); - // Stable: equal tags stay in stream order, so the run of a tag starts at its first field. - index.sort_by_key(|(t, _, _)| *t); - index.dedup_by(|later, first| { - if later.0 == first.0 { - first.2 = later.2; - true - } else { - false - } - }); - index.shrink_to_fit(); - self.index = index; - } - - fn position(&self, tag: Tag, last: bool) -> Option { - if self.index.is_empty() { - let mut fields = self.fields.iter().enumerate(); - let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) }; - return hit.map(|(i, _)| i); - } - let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?; - let (_, first, end) = self.index.get(at)?; - usize::try_from(if last { *end } else { *first }).ok() - } - - /// The first field tagged `tag`. - pub fn get(&self, tag: Tag) -> Option<&Value> { - self.fields.get(self.position(tag, false)?).map(|(_, v)| v) - } - - /// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one). - pub fn get_last(&self, tag: Tag) -> Option<&Value> { - self.fields.get(self.position(tag, true)?).map(|(_, v)| v) - } -} - -#[derive(Debug)] -pub struct Stream { - pub root: ObjId, - pub objects: Vec, -} - -/// Deepest object nesting accepted; real documents stay well below (each layer level adds three). -pub const MAX_DEPTH: usize = 384; - -const MAX_OBJECTS: usize = 8_000_000; - -/// Most values (fields and array elements) one stream may decode. A value takes about 40 bytes -/// in memory however few it took in the file (a bool array packs eight in a byte), so the size -/// of the input alone doesn't bound what parsing allocates: a small compressed entry could -/// otherwise ask for tens of gigabytes. Real documents stay far below. -pub const MAX_VALUES: usize = 1 << 24; - -struct Parser<'a> { - c: Cursor<'a>, - objects: Vec, - /// Shared ids, defined at first use and referenced backwards. - shared: std::collections::HashMap, - depth: usize, - /// Values decoded so far, against [`MAX_VALUES`]. - values: usize, -} - -/// Parse a stream (`00 FF 4B 53` header). Bytes after the root's terminator are ignored. -pub fn parse(bytes: &[u8]) -> Result { - let mut c = Cursor::new(bytes, 0); - if c.take(4)? != b"\x00\xffKS" { - return Err(Error::Malformed("document stream signature")); - } - let version = c.u16()?; - if version > 2 { - return Err(Error::Unsupported("document stream version")); - } - let class = Tag(c.u32()?); - c.u16()?; - if version == 2 { - c.u32()?; - } - let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 }; - let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?; - let fields = p.fields(true, class)?; - if let Some(o) = p.objects.get_mut(root) { - o.fields = fields; - o.index(); - } - Ok(Stream { root, objects: p.objects }) -} - -impl Parser<'_> { - fn push(&mut self, o: Object) -> Result { - if self.objects.len() >= MAX_OBJECTS { - return Err(Error::Limit("too many objects")); - } - self.objects.push(o); - Ok(self.objects.len() - 1) - } - - /// Counts `n` more values against [`MAX_VALUES`], before anything is allocated for them. - fn spend(&mut self, n: usize) -> Result<(), Error> { - self.values = self.values.checked_add(n).filter(|&v| v <= MAX_VALUES).ok_or(Error::Limit("too many values in the document stream"))?; - Ok(()) - } - - /// An empty array with room for `n` values, paid for first; an allocation that still fails - /// is an error, not an abort. - fn vec(&mut self, n: usize) -> Result, Error> { - self.spend(n)?; - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| Error::Limit("not enough memory for the document stream"))?; - Ok(v) - } - - /// Element count of an array: each element takes at least `min` bytes, so a count the - /// remaining input cannot hold is rejected before anything is allocated. - fn count(&mut self, min: usize) -> Result { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - if n.checked_mul(min.max(1)).is_none_or(|bytes| bytes > self.c.remaining()) { - return Err(Error::Malformed("array longer than its data")); - } - Ok(n) - } - - fn fields(&mut self, tagged: bool, class: Tag) -> Result, Error> { - self.depth += 1; - if self.depth > MAX_DEPTH { - return Err(Error::Limit("objects nested too deeply")); - } - let mut out = Vec::new(); - loop { - let t = self.c.u8()?; - let code = t & 0x7F; - if code == 0 { - break; - } - self.spend(1)?; - let tag = if tagged { Tag(self.c.u32()?) } else { Tag(0) }; - let v = if t & 0x80 != 0 { self.array(code, class)? } else { self.scalar(code, tagged, class)? }; - out.push((tag, v)); - } - self.depth -= 1; - Ok(out) - } - - fn string(&mut self) -> Result { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("string length"))?; - Ok(String::from_utf8_lossy(self.c.take(n)?).into_owned()) - } - - fn floats(&mut self, n: usize, wide: bool) -> Result { - let mut v = Vec::with_capacity(n); - for _ in 0..n { - v.push(if wide { f64::from_le_bytes(self.c.array()?) } else { f64::from(f32::from_le_bytes(self.c.array()?)) }); - } - Ok(Value::Floats(v)) - } - - fn scalar(&mut self, code: u8, tagged: bool, class: Tag) -> Result { - let c = &mut self.c; - Ok(match code { - 0x01 => Value::UInt(c.u8()?.into()), - 0x02 => Value::UInt(c.u16()?.into()), - 0x03 | 0x2f | 0x34 => Value::UInt(c.u32()?.into()), - 0x04 => Value::UInt(c.u64()?), - 0x05 => Value::Int(i8::from_le_bytes(c.array()?).into()), - 0x06 => Value::Int(i16::from_le_bytes(c.array()?).into()), - 0x07 => Value::Int(i32::from_le_bytes(c.array()?).into()), - 0x08 => Value::Int(i64::from_le_bytes(c.array()?)), - 0x09 => Value::Float(f32::from_le_bytes(c.array()?).into()), - 0x0a => Value::Float(f64::from_le_bytes(c.array()?)), - 0x15..=0x19 => { - let n = usize::from(code - 0x13); - let mut v = Vec::with_capacity(n); - for _ in 0..n { - v.push(i32::from_le_bytes(c.array()?).into()); - } - Value::Ints(v) - } - 0x1f..=0x23 => return self.floats(usize::from(code - 0x1d), false), - 0x24..=0x28 => return self.floats(usize::from(code - 0x22), true), - 0x29 => Value::Bool(c.u8()? != 0), - 0x2a => Value::Enum { id: c.u16()?, version: c.u16()? }, - 0x2b | 0x2e => Value::Str(self.string()?), - 0x2c => { - let n = usize::from(c.u16()?); - Value::Bytes(c.take(n)?.to_vec()) - } - 0x35..=0x74 => Value::Bytes(c.take(usize::from(code - 0x34))?.to_vec()), - 0x2d => { - let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("blob length"))?; - Value::Blob(c.take(n)?.to_vec()) - } - 0x33 => { - c.u32()?; - let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("entry name length"))?; - Value::Entry(String::from_utf8_lossy(c.take(n)?).into_owned()) - } - 0x75 => { - c.u16()?; - let n = usize::from(c.u8()?); - if n > 8 { - return Err(Error::Malformed("flags wider than 64 bits")); - } - let mut b = [0u8; 8]; - b.get_mut(..n).ok_or(Error::Malformed("flags"))?.copy_from_slice(c.take(n)?); - Value::Flags(u64::from_le_bytes(b)) - } - 0x30 => { - let fields = self.fields(false, class)?; - let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?; - Value::Obj(Some(id)) - } - 0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")), - 0x31 => self.shared()?, - 0x32 => self.inline(None)?, - _ => return Err(Error::Unsupported("unknown field type in document stream")), - }) - } - - fn array(&mut self, code: u8, class: Tag) -> Result { - let min = match code { - 0x01 | 0x05 | 0x29 => 1, - 0x02 | 0x06 => 2, - 0x03 | 0x07 | 0x09 | 0x2f | 0x34 => 4, - 0x04 | 0x08 | 0x0a => 8, - 0x15..=0x19 => 4 * usize::from(code - 0x13), - 0x1f..=0x23 => 4 * usize::from(code - 0x1d), - 0x24..=0x28 => 8 * usize::from(code - 0x22), - 0x35..=0x74 => usize::from(code - 0x34), - _ => 1, - }; - match code { - 0x29 => { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - let bits = self.c.take(n.div_ceil(8))?; - let mut v = self.vec(n)?; - v.extend((0..n).map(|i| Value::Bool(bits.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0)))); - Ok(Value::Array(v)) - } - 0x2a => { - let n = self.count(2)?; - let version = self.c.u16()?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Enum { id: self.c.u16()?, version }); - } - Ok(Value::Array(v)) - } - 0x2b | 0x2e => { - self.c.u32()?; - let n = self.count(4)?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Str(self.string()?)); - } - Ok(Value::Array(v)) - } - 0x2c => { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - let size = usize::from(self.c.u16()?); - // Records of no bytes take nothing from the data, whatever their number. - if n > 0 && size == 0 { - return Err(Error::Malformed("array of records without bytes")); - } - if n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) { - return Err(Error::Malformed("array longer than its data")); - } - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Bytes(self.c.take(size)?.to_vec())); - } - Ok(Value::Array(v)) - } - 0x32 => { - let n = self.count(1)?; - let class = Tag(self.c.u32()?); - self.c.u16()?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(self.inline(Some(class))?); - } - Ok(Value::Array(v)) - } - 0x2d | 0x33 | 0x75 => Err(Error::Malformed("array of an unarrayable type")), - _ => { - let n = self.count(min)?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(self.scalar(code, true, class)?); - } - Ok(Value::Array(v)) - } - } - } - - /// Inline object; `class` is given once for a whole array of them. - fn inline(&mut self, class: Option) -> Result { - match self.c.u8()? { - 0 => return Ok(Value::Obj(None)), - 1 => {} - _ => return Err(Error::Malformed("object marker")), - } - let class = match class { - Some(c) => c, - None => { - let c = Tag(self.c.u32()?); - self.c.u16()?; - c - } - }; - let fields = self.fields(true, class)?; - let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?; - Ok(Value::Obj(Some(id))) - } - - fn shared(&mut self) -> Result { - let flag = self.c.u8()?; - if flag == 0 { - return Ok(Value::Obj(None)); - } - let key = self.c.u32()?; - match flag { - 2 => return self.shared.get(&key).map(|id| Value::Obj(Some(*id))).ok_or(Error::Malformed("reference to an undefined object")), - 1 => {} - _ => return Err(Error::Malformed("object marker")), - } - if self.shared.contains_key(&key) { - return Err(Error::Malformed("object defined twice")); - } - // Register before the fields: an object's own fields may refer back to it. - let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?; - self.shared.insert(key, id); - let mut chain = Vec::new(); - let mut fields = Vec::new(); - loop { - match self.c.u8()? { - 0 => { - let tag = Tag(self.c.u32()?); - self.c.u16()?; - chain.push(tag); - fields.extend(self.fields(true, tag)?); - } - 1 => { - chain.push(Tag(self.c.u32()?)); - break; - } - 2 => break, - _ => return Err(Error::Malformed("object class chain")), - } - if chain.len() > 64 { - return Err(Error::Limit("object class chain too long")); - } - } - let class = chain.first().copied().unwrap_or(Tag(0)); - fields.extend(self.fields(true, class)?); - if let Some(o) = self.objects.get_mut(id) { - *o = Object::new(class, Kind::Shared, chain, fields); - } - Ok(Value::Obj(Some(id))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() { - let tag = |i: u32| Tag(0x4100_0000 + i); - let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect(); - fields.push((tag(7), Value::Str("last".into()))); - let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone()); - assert!(!o.index.is_empty()); - // The index has one entry per distinct tag, not per field. - assert_eq!(o.index.len(), 300); - for t in 0..300 { - let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); - let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); - assert_eq!(o.get(tag(t)), first); - assert_eq!(o.get_last(tag(t)), last); - } - assert_eq!(o.get(tag(300)), None); - assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into()))); - let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]); - assert!(small.index.is_empty()); - assert_eq!(small.get(tag(1)), Some(&Value::Bool(true))); - assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false))); - } -} diff --git a/crates/affinity/src/synth.rs b/crates/affinity/src/synth.rs deleted file mode 100644 index 5b75ca0bff..0000000000 --- a/crates/affinity/src/synth.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Synthetic containers for tests and fuzz seeds (cargo feature `synth`). -//! -//! These builders write the layout the reader accepts, so tests can describe documents in a few -//! lines. They are **not** an Affinity exporter: nothing written here has been opened in Affinity. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use crate::stream::Tag; - -/// A field value to encode. -#[derive(Debug, Clone)] -pub enum F { - U8(u8), - U32(u32), - I32(i32), - F32(f32), - F64(f64), - Bool(bool), - Enum(u16, u16), - Str(String), - /// f64 vector of 2..6 values (points, rectangles, transforms). - F64s(Vec), - /// Fixed-size struct (colour components), 1..64 bytes. - Struct(Vec), - /// Array of fixed-size records, all `size` bytes. - Records(u16, Vec>), - U8s(Vec), - Entry(String), - /// Shared object: `Def` defines id with class chain and fields, `Ref` links back. - Def(u32, Vec, Vec<(Tag, F)>), - Ref(u32), - Null, - /// Inline object. - Obj(Tag, Vec<(Tag, F)>), - /// Positional (untagged) object. - Pos(Vec), - /// Array of shared objects / links. - Shared(Vec), - /// Array of inline objects of one class. - Objs(Tag, Vec>), - /// Raw bytes appended verbatim (malformed-input tests). - Raw(Vec), -} - -pub fn tag(s: &[u8; 4]) -> Tag { - Tag::of(s) -} - -fn put_tag(out: &mut Vec, t: Tag) { - out.extend(t.0.to_le_bytes()); -} - -fn code(f: &F) -> u8 { - match f { - F::U8(_) => 0x01, - F::U32(_) => 0x03, - F::I32(_) => 0x07, - F::F32(_) => 0x09, - F::F64(_) => 0x0a, - F::Bool(_) => 0x29, - F::Enum(..) => 0x2a, - F::Str(_) => 0x2b, - F::F64s(v) => 0x22 + v.len() as u8, - F::Struct(b) => 0x34 + b.len() as u8, - F::Records(..) => 0x80 | 0x2c, - F::U8s(_) => 0x80 | 0x01, - F::Entry(_) => 0x33, - F::Def(..) | F::Ref(_) => 0x31, - F::Null => 0x31, - F::Obj(..) => 0x32, - F::Pos(_) => 0x30, - F::Shared(_) => 0x80 | 0x31, - F::Objs(..) => 0x80 | 0x32, - F::Raw(_) => 0, - } -} - -fn payload(out: &mut Vec, f: &F) { - match f { - F::U8(v) => out.push(*v), - F::U32(v) => out.extend(v.to_le_bytes()), - F::I32(v) => out.extend(v.to_le_bytes()), - F::F32(v) => out.extend(v.to_le_bytes()), - F::F64(v) => out.extend(v.to_le_bytes()), - F::Bool(v) => out.push(u8::from(*v)), - F::Enum(id, ver) => { - out.extend(id.to_le_bytes()); - out.extend(ver.to_le_bytes()); - } - F::Str(s) => { - out.extend((s.len() as u32).to_le_bytes()); - out.extend(s.as_bytes()); - } - F::F64s(v) => v.iter().for_each(|x| out.extend(x.to_le_bytes())), - F::Struct(b) => out.extend(b), - F::Records(size, recs) => { - out.extend((recs.len() as u32).to_le_bytes()); - out.extend(size.to_le_bytes()); - recs.iter().for_each(|r| out.extend(r)); - } - F::U8s(v) => { - out.extend((v.len() as u32).to_le_bytes()); - out.extend(v); - } - F::Entry(name) => { - put_tag(out, tag(b"Data")); - out.extend((name.len() as u32).to_le_bytes()); - out.extend(name.as_bytes()); - } - F::Def(id, chain, fields) => { - out.push(1); - out.extend(id.to_le_bytes()); - // Class chain: each level but the last carries no fields here; the last ends the chain. - let (last, rest) = chain.split_last().expect("class chain"); - for t in rest { - out.push(0); - put_tag(out, *t); - out.extend(0u16.to_le_bytes()); - out.push(0); - } - out.push(1); - put_tag(out, *last); - fields_into(out, fields, true); - } - F::Ref(id) => { - out.push(2); - out.extend(id.to_le_bytes()); - } - F::Null => out.push(0), - F::Obj(class, fields) => { - out.push(1); - put_tag(out, *class); - out.extend(0u16.to_le_bytes()); - fields_into(out, fields, true); - } - F::Pos(items) => { - for f in items { - out.push(code(f)); - payload(out, f); - } - out.push(0); - } - F::Shared(items) => { - out.extend((items.len() as u32).to_le_bytes()); - items.iter().for_each(|f| payload(out, f)); - } - F::Objs(class, items) => { - out.extend((items.len() as u32).to_le_bytes()); - put_tag(out, *class); - out.extend(0u16.to_le_bytes()); - for fields in items { - out.push(1); - fields_into(out, fields, true); - } - } - F::Raw(b) => out.extend(b), - } -} - -fn fields_into(out: &mut Vec, fields: &[(Tag, F)], tagged: bool) { - for (t, f) in fields { - if let F::Raw(b) = f { - out.extend(b); - continue; - } - out.push(code(f)); - if tagged { - put_tag(out, *t); - } - payload(out, f); - } - out.push(0); -} - -/// A `doc.dat` stream with root class `Pers`. -pub fn stream(root: &[(Tag, F)]) -> Vec { - let mut out = b"\x00\xffKS".to_vec(); - out.extend(2u16.to_le_bytes()); - put_tag(&mut out, tag(b"Pers")); - out.extend(0u16.to_le_bytes()); - out.extend(30u32.to_le_bytes()); - fields_into(&mut out, root, true); - out -} - -/// How an entry is stored. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Method { - Stored, - Zlib, - Zstd, -} - -/// A version-12 container with one `#FT4` table holding `entries`, then an optional thumbnail record. -pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>) -> Vec { - let mut out = vec![0u8; 72]; - out[..4].copy_from_slice(crate::container::MAGIC); - out[4..6].copy_from_slice(&12u16.to_le_bytes()); - out[6..8].copy_from_slice(&4u16.to_le_bytes()); - out[8..12].copy_from_slice(b"nsrP"); - out[12..16].copy_from_slice(b"#Inf"); - out[64..68].copy_from_slice(b"Prot"); - let mut records = Vec::new(); - for (i, (name, data, method)) in entries.iter().enumerate() { - let packed = match method { - Method::Stored => data.to_vec(), - Method::Zlib => { - use std::io::Write; - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); - e.write_all(data).unwrap(); - e.finish().unwrap() - } - Method::Zstd => ruzstd::encoding::compress_to_vec(*data, ruzstd::encoding::CompressionLevel::Fastest), - }; - let offset = out.len() as u64; - out.extend(b"#Fil"); - out.extend(&packed); - let mut r = Vec::new(); - r.extend((i as u32 + 1).to_le_bytes()); - r.push(0); - r.extend(offset.to_le_bytes()); - r.extend((data.len() as u64).to_le_bytes()); - r.extend((packed.len() as u64).to_le_bytes()); - r.extend(crc32fast::hash(data).to_le_bytes()); - r.push(match method { - Method::Stored => 0, - Method::Zlib => 1, - Method::Zstd => 2, - }); - r.extend(0u32.to_le_bytes()); - r.extend(0u32.to_le_bytes()); - r.extend((name.len() as u16).to_le_bytes()); - r.extend(name.as_bytes()); - records.push(r); - } - let fat = out.len() as u64; - out.extend(b"#FT4"); - out.extend(0u64.to_le_bytes()); - out.extend(1_700_000_000u64.to_le_bytes()); - out.extend([0u8; 24]); - out.extend((records.len() as u32).to_le_bytes()); - out.extend([0u8; 8]); - out.extend(0u16.to_le_bytes()); - out.push(0); - records.iter().for_each(|r| out.extend(r)); - let thumb = out.len() as u64; - out[16..24].copy_from_slice(&fat.to_le_bytes()); - if let Some(png) = thumbnail_png { - out[24..32].copy_from_slice(&thumb.to_le_bytes()); - out.extend(b"\xff\xff\xff\xffThmb"); - out.extend(1u32.to_le_bytes()); - out.extend((png.len() as u32 + 13).to_le_bytes()); - out.extend(29u32.to_le_bytes()); - out.extend(0u32.to_le_bytes()); - out.extend((png.len() as u32).to_le_bytes()); - out.push(1); - out.extend(png); - } - out -} diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs deleted file mode 100644 index 75b6b7b146..0000000000 --- a/crates/affinity/src/tests.rs +++ /dev/null @@ -1,408 +0,0 @@ -//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents. - -mod preview { - use crate::container::header; - use crate::*; - use proptest::prelude::*; - - fn fixture() -> Vec { - let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); - png.extend(13u32.to_be_bytes()); - png.extend(b"IHDR"); - png.extend(2u32.to_be_bytes()); - png.extend(1u32.to_be_bytes()); - png.extend([8, 6, 0, 0, 0]); - png.extend(crc32fast::hash(&png[12..]).to_be_bytes()); - png.extend([0; 4]); - png.extend(b"IDAT"); - png.extend(crc32fast::hash(b"IDAT").to_be_bytes()); - png.extend([0; 4]); - png.extend(b"IEND"); - png.extend(crc32fast::hash(b"IEND").to_be_bytes()); - let mut b = vec![0; 72]; - b[..4].copy_from_slice(MAGIC); - b[4..6].copy_from_slice(&12u16.to_le_bytes()); - b[8..12].copy_from_slice(b"nsrP"); - b[12..16].copy_from_slice(b"#Inf"); - b[24..32].copy_from_slice(&72u64.to_le_bytes()); - b[64..68].copy_from_slice(b"Prot"); - b.extend(b"\xff\xff\xff\xffThmb"); - b.extend(1u32.to_le_bytes()); - b.extend((png.len() as u32 + 13).to_le_bytes()); - b.extend(29u32.to_le_bytes()); - b.extend(0u32.to_le_bytes()); - b.extend((png.len() as u32).to_le_bytes()); - b.push(1); - b.extend(png); - b - } - - #[test] - fn indexed_preview_and_header() { - let b = fixture(); - assert_eq!(header(&b).unwrap().version, 12); - let p = preview(&b).unwrap(); - assert_eq!((p.width, p.height), (2, 1)); - assert_eq!(p.png, &b[101..]); - } - - #[test] - fn every_truncation_is_rejected() { - let b = fixture(); - for end in 0..b.len() { - assert!(preview(&b[..end]).is_err(), "{end}"); - } - } - - #[test] - fn rejects_assets_versions_offsets_lengths_and_bombs() { - let b = fixture(); - for (offset, value) in [ - (4, 13u64.to_le_bytes().to_vec()), - (8, b"urBR".to_vec()), - (24, u64::MAX.to_le_bytes().to_vec()), - (24, 1u64.to_le_bytes().to_vec()), - (24, 0u64.to_le_bytes().to_vec()), - (84, u32::MAX.to_le_bytes().to_vec()), - (88, 30u32.to_le_bytes().to_vec()), - (96, u32::MAX.to_le_bytes().to_vec()), - (117, 5000u32.to_be_bytes().to_vec()), - ] { - let mut broken = b.clone(); - broken[offset..offset + value.len()].copy_from_slice(&value); - assert!(preview(&broken).is_err(), "offset {offset}"); - } - // Versions 8 to 11 store the same record (checked on public Affinity 1 and 2 files). - for version in 8..12 { - let mut legacy = b.clone(); - legacy[4..6].copy_from_slice(&(version as u16).to_le_bytes()); - assert!(preview(&legacy).is_ok()); - } - // Flags 4 and 8 occur in real files; the low two bits mark other container variants. - for (flags, ok) in [(4u16, true), (8, true), (1, false), (2, false)] { - let mut variant = b.clone(); - variant[6..8].copy_from_slice(&flags.to_le_bytes()); - assert_eq!(preview(&variant).is_ok(), ok, "flags {flags}"); - } - let mut old = b.clone(); - old[4..6].copy_from_slice(&7u16.to_le_bytes()); - assert!(matches!(preview(&old), Err(Error::Unsupported(_)))); - } - - #[test] - fn an_unindexed_png_or_resource_is_never_used() { - let mut b = fixture(); - b[24..32].copy_from_slice(&0u64.to_le_bytes()); - assert!(preview(&b).is_err()); - b[24..32].copy_from_slice(&72u64.to_le_bytes()); - b[76..80].copy_from_slice(b"Meta"); - assert!(preview(&b).is_err()); - } - - #[test] - fn every_chunk_checksum_including_the_end_is_checked() { - let b = fixture(); - for at in [130, b.len() - 1] { - let mut damaged = b.clone(); - damaged[at] ^= 1; - assert_eq!(preview(&damaged).unwrap_err(), Error::Malformed("PNG chunk checksum")); - } - let mut ancillary = vec![0; 4]; - ancillary.extend(b"tEXt"); - ancillary.extend(crc32fast::hash(b"tEXt").to_be_bytes()); - let mut with_ancillary = b.clone(); - let at = b.len() - 12; - with_ancillary.splice(at..at, ancillary); - let png_length = (with_ancillary.len() - 101) as u32; - with_ancillary[84..88].copy_from_slice(&(png_length + 13).to_le_bytes()); - with_ancillary[96..100].copy_from_slice(&png_length.to_le_bytes()); - assert!(preview(&with_ancillary).is_ok()); - with_ancillary[at + 8] ^= 1; - assert_eq!(preview(&with_ancillary).unwrap_err(), Error::Malformed("PNG chunk checksum")); - } - - #[test] - fn compressed_metadata_and_animation_are_not_preview_support() { - for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] { - let mut extra = vec![0; 4]; - extra.extend(kind); - extra.extend(crc32fast::hash(kind).to_be_bytes()); - let mut b = fixture(); - let at = b.len() - 12; - b.splice(at..at, extra); - let length = (b.len() - 101) as u32; - b[84..88].copy_from_slice(&(length + 13).to_le_bytes()); - b[96..100].copy_from_slice(&length.to_le_bytes()); - assert!(matches!(preview(&b), Err(Error::Unsupported(_)))); - } - } - - #[test] - fn critical_chunks_follow_a_single_complete_png_layout() { - fn with_chunks(kinds: &[&[u8; 4]]) -> Vec { - let original = fixture(); - let mut b = original[..134].to_vec(); // File, record and complete first IHDR. - for kind in kinds { - b.extend([0; 4]); - b.extend(*kind); - b.extend(crc32fast::hash(*kind).to_be_bytes()); - } - let length = (b.len() - 101) as u32; - b[84..88].copy_from_slice(&(length + 13).to_le_bytes()); - b[96..100].copy_from_slice(&length.to_le_bytes()); - b - } - assert!(preview(&with_chunks(&[b"IDAT", b"IDAT", b"IEND"])).is_ok()); - // PNG readers must not reject an otherwise valid unknown ancillary chunk just - // because its reserved (third-letter) bit is set; future versions can define it. - assert!(preview(&with_chunks(&[b"abct", b"IDAT", b"IEND"])).is_ok()); - for kinds in [ - vec![b"IEND"], - vec![b"IDAT", b"IHDR", b"IEND"], - vec![b"PLTE", b"PLTE", b"IDAT", b"IEND"], - vec![b"IDAT", b"PLTE", b"IEND"], - vec![b"IDAT", b"tEXt", b"IDAT", b"IEND"], - vec![b"ABCD", b"IDAT", b"IEND"], - vec![b"IDAT", b"IEND", b"tEXt"], - ] { - assert!(preview(&with_chunks(&kinds)).is_err(), "{kinds:?}"); - } - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(256))] - #[test] - fn arbitrary_input_never_panics(b in prop::collection::vec(any::(), 0..2048)) { - let _ = header(&b); - let _ = preview(&b); - } - #[test] - fn mutations_never_panic(edits in prop::collection::vec((0usize..200, any::()), 0..32)) { - let mut b = fixture(); - for (i, value) in edits { if let Some(v) = b.get_mut(i) { *v = value; } } - let _ = preview(&b); - } - } -} - -mod archive { - use crate::Error; - use crate::container::{Archive, Limits}; - use crate::stream::{self, Kind, Tag, Value}; - use crate::synth::{self, F, Method, tag}; - use proptest::prelude::*; - - fn doc() -> Vec { - synth::stream(&[ - (tag(b"Desc"), F::Str("Document".into())), - (tag(b"Visi"), F::Bool(true)), - (tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])), - (tag(b"Colr"), F::Def(7, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0u8; 16].to_vec()))])), - (tag(b"Same"), F::Ref(7)), - (tag(b"Null"), F::Null), - (tag(b"Kids"), F::Shared(vec![F::Def(8, vec![tag(b"Grup"), tag(b"Node")], vec![(tag(b"Desc"), F::Str("g".into()))]), F::Ref(8)])), - ( - tag(b"Crvs"), - F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(vec![F::U8(0), F::U32(1), F::Bool(true), F::Records(18, vec![vec![0; 18]; 4])]))]), - ), - (tag(b"Enum"), F::Enum(2, 1)), - (tag(b"Tile"), F::Entry("d/3".into())), - (tag(b"Stat"), F::U8s(vec![4, 0, 2])), - ]) - } - - #[test] - fn every_method_round_trips_with_checksums() { - let d = doc(); - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - let file = synth::container(&[("doc.dat", &d, method), ("d/3", b"tile", method)], None); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.header.version, 12); - assert_eq!(a.read("doc.dat").unwrap(), d); - assert_eq!(a.read("d/3").unwrap(), b"tile"); - assert_eq!(a.extracted(), d.len() + 4); - assert!(a.read("missing").is_err()); - } - } - - #[test] - fn the_stream_parses_into_shared_objects_and_links() { - let s = stream::parse(&doc()).unwrap(); - let root = &s.objects[s.root]; - assert_eq!(root.class, Tag::of(b"Pers")); - assert_eq!(root.get(Tag::of(b"Desc")), Some(&Value::Str("Document".into()))); - assert_eq!(root.get(Tag::of(b"Xfrm")), Some(&Value::Floats(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0]))); - let (Some(Value::Obj(Some(a))), Some(Value::Obj(Some(b)))) = (root.get(Tag::of(b"Colr")), root.get(Tag::of(b"Same"))) else { panic!() }; - assert_eq!(a, b); - assert_eq!(s.objects[*a].class, Tag::of(b"RGBA")); - assert_eq!(s.objects[*a].kind, Kind::Shared); - let Some(Value::Array(kids)) = root.get(Tag::of(b"Kids")) else { panic!() }; - assert_eq!(kids[0], kids[1]); - let Value::Obj(Some(g)) = kids[0] else { panic!() }; - assert_eq!(s.objects[g].chain, vec![Tag::of(b"Grup"), Tag::of(b"Node")]); - assert_eq!(root.get(Tag::of(b"Enum")), Some(&Value::Enum { id: 2, version: 1 })); - assert_eq!(root.get(Tag::of(b"Tile")), Some(&Value::Entry("d/3".into()))); - assert_eq!(root.get(Tag::of(b"Null")), Some(&Value::Obj(None))); - } - - #[test] - fn checksums_sizes_and_budgets_are_enforced() { - let d = doc(); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - // Flip a byte inside the compressed payload, past the "#Fil" tag at offset 72. - let mut broken = file.clone(); - broken[90] ^= 0x55; - let mut a = Archive::open(&broken, Limits::default()).unwrap(); - assert!(a.read("doc.dat").is_err()); - let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX }).unwrap(); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1 }).unwrap(); - a.read("doc.dat").unwrap(); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - } - - #[test] - fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() { - let d = doc(); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - let mut broken = file.clone(); - broken[90] ^= 0x55; - let mut a = Archive::open(&broken, Limits::default()).unwrap(); - let first = a.read("doc.dat").unwrap_err(); - // The work was done, so it counts against the import even though it failed. - assert_eq!(a.extracted(), d.len()); - assert_eq!(a.read("doc.dat").unwrap_err(), first); - assert_eq!(a.extracted(), d.len()); - // A budget that only covers one attempt is not exceeded by asking again. - let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap(); - assert!(a.read("doc.dat").is_err()); - assert_eq!(a.read("doc.dat").unwrap_err(), first); - } - - #[test] - fn the_table_index_has_a_budget_for_records_and_names() { - let d = doc(); - let long = "n".repeat(300); - let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None); - Archive::open_within(&file, Limits::default(), 2, 307).unwrap(); - assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries")); - assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long")); - } - - // Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's - // window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than - // the format permits for a block. 0.9.1 refuses it. - #[test] - fn a_zstd_block_larger_than_its_frames_window_is_refused() { - const LEN: u32 = 100_000; - let plain = vec![0x61u8; LEN as usize]; - let file = synth::container(&[("doc.dat", &plain, Method::Zstd)], None); - // A Zstandard frame with a 1 KiB window (descriptor byte 0, window byte 0) holding one RLE - // block, the last, that repeats a byte LEN times: block header = last | RLE << 1 | LEN << 3. - let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0x00, 0x00]; - frame.extend((1 | (1 << 1) | (LEN << 3)).to_le_bytes().get(..3).unwrap()); - frame.push(0x61); - // Swap it in for the entry's compressed bytes (they follow the "#Fil" tag at offset 72). - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - let old_len = u64::from_le_bytes(file[fat + 59 + 21..fat + 59 + 29].try_into().unwrap()) as usize; - let mut swapped = file[..76].to_vec(); - swapped.extend(&frame); - swapped.extend(&file[76 + old_len..]); - let new_fat = fat - old_len + frame.len(); - swapped[16..24].copy_from_slice(&(new_fat as u64).to_le_bytes()); - swapped[new_fat + 59 + 21..new_fat + 59 + 29].copy_from_slice(&(frame.len() as u64).to_le_bytes()); - let mut a = Archive::open(&swapped, Limits::default()).unwrap(); - assert!(a.read("doc.dat").is_err(), "a block of {LEN} bytes was decompressed from a frame with a 1 KiB window"); - } - - #[test] - fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() { - let big = vec![7u8; 1 << 20]; - let mut file = synth::container(&[("doc.dat", &big, Method::Zlib)], None); - // Rewrite the declared size in the table to 1 KiB: decoding must stop and fail. - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - let size_at = fat + 59 + 5 + 8; - file[size_at..size_at + 8].copy_from_slice(&1024u64.to_le_bytes()); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.read("doc.dat").unwrap_err(), Error::Malformed("archive entry size mismatch")); - } - - #[test] - fn libraries_and_cyclic_tables_are_rejected() { - let d = doc(); - let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None); - let mut library = file.clone(); - library[8..12].copy_from_slice(b"rAsA"); - assert!(matches!(Archive::open(&library, Limits::default()), Err(Error::Unsupported(_)))); - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()); - let at = fat as usize + 4; - file[at..at + 8].copy_from_slice(&fat.to_le_bytes()); - assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Malformed("allocation tables form a cycle")); - } - - #[test] - fn hostile_streams_fail_cleanly() { - let deep = (0..2000).fold(Vec::new(), |inner, _| vec![(tag(b"Chld"), F::Obj(tag(b"Grup"), inner))]); - assert_eq!(stream::parse(&synth::stream(&deep)).unwrap_err(), Error::Limit("objects nested too deeply")); - // An array claiming four billion elements in a few bytes. - let huge = synth::stream(&[(tag(b"Big_"), F::Raw(vec![0x81, b'_', b'g', b'i', b'B', 0xff, 0xff, 0xff, 0xff, 0]))]); - assert_eq!(stream::parse(&huge).unwrap_err(), Error::Malformed("array longer than its data")); - let forward = synth::stream(&[(tag(b"Link"), F::Ref(99))]); - assert!(stream::parse(&forward).is_err()); - let twice = synth::stream(&[(tag(b"A___"), F::Def(1, vec![tag(b"RGBA")], vec![])), (tag(b"B___"), F::Def(1, vec![tag(b"RGBA")], vec![]))]); - assert!(stream::parse(&twice).is_err()); - let unknown = synth::stream(&[(tag(b"X___"), F::Raw(vec![0x0b, 1, 2, 3, 4]))]); - assert!(matches!(stream::parse(&unknown), Err(Error::Unsupported(_)))); - let d = doc(); - for end in 0..d.len() { - assert!(stream::parse(&d[..end]).is_err(), "{end}"); - } - } - - #[test] - fn a_small_compressed_entry_cannot_make_the_stream_allocate_gigabytes() { - // Each decoded value takes about 40 bytes, and a bool array packs eight in a byte: 16 MiB - // of zero bits, a few KiB once compressed, would ask for 2^27 values (about 4 GiB). An - // array of one-byte values just past the budget fails the same way, before allocating. - let field = |code: u8, n: u32, data: usize| { - let mut f = vec![0x80 | code]; - f.extend(tag(b"Big_").0.to_le_bytes()); - f.extend(n.to_le_bytes()); - f.resize(f.len() + data, 0); - F::Raw(f) - }; - let bools = 1u32 << 27; - let bytes = u32::try_from(stream::MAX_VALUES).unwrap() + 1; - for f in [field(0x29, bools, (bools / 8) as usize), field(0x01, bytes, bytes as usize)] { - let d = synth::stream(&[(tag(b"Big_"), f)]); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - assert!(file.len() < d.len() / 100, "{} of {}", file.len(), d.len()); - let entry = Archive::open(&file, Limits::default()).unwrap().read("doc.dat").unwrap(); - assert_eq!(stream::parse(&entry).unwrap_err(), Error::Limit("too many values in the document stream")); - } - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(512))] - #[test] - fn mutated_containers_and_streams_never_panic(edits in prop::collection::vec((0usize..4096, any::()), 1..24)) { - let d = doc(); - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - let mut file = synth::container(&[("doc.dat", &d, method)], None); - for (i, v) in &edits { - let n = file.len(); - file[i % n] = *v; - } - if let Ok(bytes) = Archive::open(&file, Limits::default()).and_then(|mut a| a.read("doc.dat")) { - let _ = stream::parse(&bytes); - } - } - let mut s = d.clone(); - for (i, v) in &edits { - let n = s.len(); - s[i % n] = *v; - } - let _ = stream::parse(&s); - } - } -} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs deleted file mode 100644 index d2bb55ca0c..0000000000 --- a/crates/affinity/src/text.rs +++ /dev/null @@ -1,564 +0,0 @@ -//! Artistic and frame text: the story's characters with their font, size, colour, tracking and -//! leading, the paragraph alignment and the first baseline. Layout (line breaks in frames, kerning, -//! OpenType features) is left to the importing application. - -use crate::model::{Affine, Align, Paragraph, Point, Reader, Table, TableCell, Text, TextRun, VAlign, rect}; -use crate::paint::{self, Color, Paint}; -use crate::stream::{ObjId, Value}; - -/// Characters read per text node (stories are split into blocks; this caps hostile ones). -const MAX_CHARS: usize = 1 << 20; -/// Shared character attributes must not amplify into unbounded font/feature/gradient data. -const MAX_ATTRIBUTE_BYTES: usize = 16 << 20; - -/// Ends a table cell in a table's story (Affinity's break glyph of kind 4). -pub const CELL_BREAK: char = '\u{1F}'; - -pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { - let s = r.s; - let story = s.obj(id, b"StSt")?; - let frame = s.obj(id, b"TxtH")?; - let artistic = s.is(frame, b"ArFr"); - let bounds = s.floats::<4>(frame, b"FrmB").map(rect)?; - let (runs, align) = story_runs(r, story, world); - let first_baseline = bounds.y0 + s.f64(frame, b"ArtV").unwrap_or(0.0); - let anchor_x = match align { - Align::Center => (bounds.x0 + bounds.x1) / 2.0, - Align::Right => bounds.x1, - _ => bounds.x0, - }; - if !artistic { - if s.objs(frame, b"ColW").len() > 1 || matches!(s.field(frame, b"ColW"), Some(Value::Array(a)) if a.len() > 1) { - r.warn("text frames with several columns (imported as one column)"); - } - if s.class(id) == Some(crate::stream::Tag::of(b"TxtC")) { - r.warn("text frames with a curved outline (imported as rectangular frames)"); - } - } - let text_transform = if artistic { world } else { text_scale(r, id).then(r.type_base) }; - Some(Text { - runs, - align, - anchor: Point { x: anchor_x, y: first_baseline }, - frame: if artistic { None } else { Some(bounds) }, - transform: world, - text_transform, - }) -} - -/// Rows and columns a table may have. -const MAX_TABLE_LINES: usize = 4096; -/// Cells a table may have (rows × columns): each becomes a text object with its edge lines. -const MAX_TABLE_CELLS: usize = 1 << 16; - -/// Work charged for each copy of a run's formatting a table cell keeps. -const TABLE_RUN_COST: usize = 16; - -/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges. -pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option { - let s = r.s; - let story = s.obj(id, b"StSt")?; - let tabl = s.obj(id, b"TxtH").and_then(|h| s.obj(h, b"Tabl"))?; - let bounds = |pos: Option| -> Option> { - let Some(Value::Array(a)) = pos.and_then(|p| s.field(p, b"Posn")) else { return None }; - let v: Vec = a.iter().take(MAX_TABLE_LINES + 2).map(float).collect::>()?; - (v.len() >= 2 && v.len() <= MAX_TABLE_LINES + 1 && v.windows(2).all(|w| w[1] >= w[0])).then_some(v) - }; - let columns = bounds(s.obj(tabl, b"CPos"))?; - let rows = bounds(s.obj(tabl, b"RPos"))?; - let (ncols, nrows) = (columns.len() - 1, rows.len() - 1); - let count = ncols.checked_mul(nrows)?; - if count > MAX_TABLE_CELLS { - r.warn("tables with more than 65536 cells (left out)"); - return None; - } - let Some(left) = r.budget.cells.checked_sub(count) else { - r.warn("tables beyond the cells one document may hold (left out)"); - return None; - }; - r.budget.cells = left; - let cell_objs = s.obj(tabl, b"Cell").map(|c| s.objs(c, b"Cell")).unwrap_or_default(); - // Formatting that doesn't match the grid would land on the wrong cells (and merging them, - // move text between cells): only text then. - let cell_objs = if cell_objs.len() == count { - cell_objs - } else { - r.warn("tables whose cells don't match their grid (cell formatting left out)"); - Vec::new() - }; - let blank = || TableCell { runs: Vec::new(), inset: [0.0; 4], valign: VAlign::Top, merged_left: false }; - let mut cells: Vec = (0..count).map(|_| blank()).collect(); - for (i, (cell, obj)) in cells.iter_mut().zip(&cell_objs).enumerate() { - if let Some(inset) = s.floats::<4>(*obj, b"Inse").filter(|v| v.iter().all(|x| x.is_finite() && *x >= 0.0)) { - cell.inset = inset; - } - cell.valign = match s.enumeration(*obj, b"AliY").map(|(i, _)| i) { - Some(1) => VAlign::Center, - Some(2) => VAlign::Bottom, - _ => VAlign::Top, - }; - // A cell merged into the one on its left; the first column has nothing to its left. - cell.merged_left = i % ncols != 0 && s.bool(*obj, b"BrLf") == Some(true); - } - // The story holds the text of every cell that isn't merged away, row by row, each ended by a - // cell break. - let owner_list: Vec = (0..count).filter(|i| cells.get(*i).is_some_and(|c| !c.merged_left)).collect(); - let mut owners = owner_list.into_iter(); - let mut target = owners.next(); - let mut extra = false; - let (runs, _) = story_runs(r, story, world); - for run in runs { - let mut parts = run.text.split(CELL_BREAK).peekable(); - while let Some(part) = parts.next() { - if !part.is_empty() { - // Each cell keeps its own copy of the run's formatting, so each copy is charged. - match target.and_then(|i| cells.get_mut(i)) { - Some(cell) if r.budget.spend(TABLE_RUN_COST).is_ok() => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }), - _ => extra = true, - } - } - if parts.peek().is_some() { - target = owners.next(); - } - } - } - if extra { - r.warn("table text beyond its last cell (left out)"); - } - let mut edges = |tag: &[u8; 4], expected: usize| -> Vec> { - let objs = s.obj(tabl, tag).map(|e| s.objs(e, b"Edge")).unwrap_or_default(); - if objs.len() != expected { - r.warn("tables whose lines don't match their grid (lines left out)"); - return Vec::new(); - } - objs.into_iter() - .map(|e| match (s.obj(e, b"Fill"), s.obj(e, b"Line")) { - (Some(pen), Some(line)) => paint::stroke(r, pen, line, world, false), - _ => None, - }) - .collect() - }; - let vertical = edges(b"CEdg", (ncols + 1) * nrows); - let horizontal = edges(b"REdg", ncols * (nrows + 1)); - if let Some(format) = s.obj(tabl, b"TFmt") { - let filled = - s.objs(format, b"Clls").into_iter().filter_map(|c| s.obj(c, b"Fill")).any(|f| s.obj(f, b"FDeF").is_some_and(|d| !s.is(d, b"FilN"))); - if filled { - r.warn("table cell fills (left out)"); - } - } - let text_transform = text_scale(r, id).then(r.type_base); - Some(Table { columns, rows, cells, vertical, horizontal, transform: world, text_transform }) -} - -/// A story's character runs, each with its paragraph's format, and the first paragraph's -/// alignment. Table cells end with [`CELL_BREAK`]. -pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec, Align) { - let s = r.s; - let mut runs = Vec::new(); - let mut first_align = None; - let mut total = 0usize; - let mut placeholders = false; - let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES); - for block in s.objs(story, b"Blok") { - // Shared blocks and run lists are visited once per link, so every visit is charged, empty or not. - let paragraph_runs = s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default(); - let attribute_runs = s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default(); - if r.budget.spend(1 + paragraph_runs.len() + attribute_runs.len()).is_err() { - r.warn("text beyond the work one document may hold (truncated)"); - break; - } - let Some(glyphs) = s.obj(block, b"Glyp") else { - r.warn("a text block without readable characters (left out)"); - continue; - }; - // Bound collection itself, including placeholders, before allocating the character buffer: - // by the story's limit and by what the document's other stories left. - let budget = (MAX_CHARS - total).min(r.budget.chars.saturating_sub(total)); - - let mut chars: Vec = match s.str(glyphs, b"Utf8") { - Some(t) => t.chars().take(budget + 1).collect(), - None => { - // Inline objects (page numbers, anchors, cell ends) each take one index before - // the segment text. - let segments = s.objs(glyphs, b"Mixd"); - if segments.is_empty() { - r.warn("a text block without readable characters (left out)"); - continue; - } - let mut v = Vec::new(); - for seg in segments { - for inline in s.objs(seg, b"Glys") { - if v.len() > budget { - break; - } - if s.is(inline, b"BrGl") && s.enumeration(inline, b"HdBk").is_some_and(|(kind, _)| kind == 4) { - v.push(CELL_BREAK); - } else { - v.push('\u{FFFC}'); - placeholders = true; - } - } - v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take((budget + 1).saturating_sub(v.len()))); - if v.len() > budget { - break; - } - } - v - } - }; - let truncated = chars.len() > budget; - if truncated { - chars.truncate(budget); - if budget < MAX_CHARS - total { - r.warn("text beyond the characters one document may hold (truncated)"); - } else { - r.warn("text longer than a million characters (truncated)"); - } - } - total += chars.len(); - // Paragraph formats by end index; a run without an index covers the rest of the block. - let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new(); - let mut open: Option = None; - for run in paragraph_runs { - let Some(attrs) = s.obj(run, b"Item") else { continue }; - let a = paragraph(r, attrs); - first_align.get_or_insert(a.align); - match s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) { - Some(end) => paragraphs.push((end, a)), - None => match open { - None => open = Some(a), - Some(first) if first != a => r.warn("mixed paragraph formats in one block (the first is used)"), - _ => {} - }, - } - } - // Sorted by end (they are in order in every file), so both lookups below are binary - // searches: a block can have as many paragraphs and runs as characters. - paragraphs.sort_by_key(|(end, _)| *end); - let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default(); - let mut cuts: Vec = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect(); - cuts.dedup(); - let push = |r: &mut Reader, runs: &mut Vec, attrs: Option, from: usize, to: usize, budget: &mut Option| { - // Split at paragraph ends so every run has one paragraph format. - let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default(); - let mut a = from; - for &c in inside.iter().chain(std::iter::once(&to)) { - push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a)); - a = c; - } - }; - let mut start = 0usize; - for run in attribute_runs { - let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else { - r.warn("invalid text attribute range (bounded; unassigned characters use defaults)"); - continue; - }; - let end = index.min(chars.len()); - if index > chars.len() || end < start { - r.warn("invalid text attribute range (bounded; unassigned characters use defaults)"); - } - if end <= start { - continue; - } - push(r, &mut runs, s.obj(run, b"Item"), start, end, &mut attribute_budget); - start = end; - } - if start < chars.len() { - push(r, &mut runs, None, start, chars.len(), &mut attribute_budget); - } - if truncated { - break; - } - } - r.budget.chars = r.budget.chars.saturating_sub(total); - if placeholders { - r.warn("text fields such as page numbers (left out of the text)"); - } - (runs, first_align.unwrap_or(Align::Left)) -} - -fn characters(chars: &[char], start: usize, end: usize) -> String { - chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect() -} - -fn push_run( - r: &mut Reader, - runs: &mut Vec, - attrs: Option, - text: String, - world: Affine, - attribute_budget: &mut Option, - paragraph: Paragraph, -) { - if text.is_empty() { - return; - } - let run = match attrs { - Some(attrs) if attribute_budget.is_some() => TextRun { paragraph, ..run_attrs(r, attrs, text, world, attribute_budget) }, - _ => { - // This is a recovery policy, not an assertion about unspecified Affinity attributes. - if attrs.is_none() { - r.warn("text without character attributes (characters preserved with default attributes)"); - } - TextRun { - text, - postscript: String::new(), - family: String::new(), - weight: 400, - italic: false, - features: Vec::new(), - all_caps: false, - underline: false, - strikethrough: false, - size: 12.0 * r.dpi / 72.0, - tracking: 0.0, - h_scale: 1.0, - leading: None, - fill: Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }), - stroke: None, - paragraph, - } - } - }; - runs.push(run); -} - -fn slot(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option) -> Option { - match v? { - Value::Array(a) => a.get(i).and_then(f), - _ => None, - } -} - -fn float(v: &Value) -> Option { - match v { - Value::Float(f) if f.is_finite() => Some(*f), - _ => None, - } -} - -fn int(v: &Value) -> Option { - match v { - Value::Int(i) => Some(*i), - Value::UInt(u) => i64::try_from(*u).ok(), - _ => None, - } -} - -fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribute_budget: &mut Option) -> TextRun { - let s = r.s; - let doubles = s.field(attrs, b"Doub"); - let ints = s.field(attrs, b"Ints"); - let size = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 1e6).unwrap_or(12.0 * r.dpi / 72.0); - let tracking = slot(doubles, 4, float).unwrap_or(0.0); - let leading = (slot(ints, 4, int) == Some(1)).then(|| slot(doubles, 13, float)).flatten().filter(|v| *v > 0.0); - let objects = match s.field(attrs, b"Objs") { - Some(Value::Array(a)) => a.iter().take(8).map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(), - _ => Vec::new(), - }; - let mut fill = match objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)) { - Some(fill) => fill, - None => { - r.warn("text without readable fill attributes (default black used)"); - Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }) - } - }; - // A single descriptor decode is bounded by paint::MAX_STOPS. Charge its owned stop data - // before keeping it; subsequent runs skip attribute decoding once the budget is exhausted. - if let Paint::Gradient(gradient) = &fill { - let bytes = gradient.stops.len().saturating_mul(std::mem::size_of::()); - if !charge_attributes(r, attribute_budget, bytes) { - fill = Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }); - } - } - // Outlined characters: `Objs` 1 is the outline's paint, 2 its line style (as for shapes). - let mut stroke = match (attribute_budget.is_some(), objects.get(1).copied().flatten(), objects.get(2).copied().flatten()) { - (true, Some(pen), Some(style)) => paint::stroke(r, pen, style, Affine::IDENTITY, false), - _ => None, - }; - // Its gradient stops and dashes are owned data too, charged like the fill's. - if let Some(st) = &stroke { - let stops = match &st.paint { - Paint::Gradient(g) => g.stops.len().saturating_mul(std::mem::size_of::()), - _ => 0, - }; - let dash = st.dash.as_ref().map_or(0, |(d, _)| d.len().saturating_mul(std::mem::size_of::())); - if !charge_attributes(r, attribute_budget, stops.saturating_add(dash)) { - stroke = None; - } - } - // Underline (slot 0) and strikethrough (slot 1): 1 is a single line. - let mut decoration = |i: usize| match slot(ints, i, int) { - Some(1) => true, - Some(0) | None => false, - Some(_) => { - r.warn("text decorations of an unknown kind (left out)"); - false - } - }; - let (underline, strikethrough) = (decoration(0), decoration(1)); - let h_scale = slot(doubles, 10, float).filter(|h| *h > 0.0 && *h < 100.0).unwrap_or(1.0); - // A resolved font is populated on the emoji run of the public Affinity 3 text-runs file - // (Courier New requested, Segoe UI Emoji stored in RFnt). Empty RFnt records are common. - // Source: https://github.com/SethRobinson/Patchy/tree/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af - let requested = s.obj(attrs, b"DFnt"); - let resolved = - s.obj(attrs, b"RFnt").filter(|f| !s.str(*f, b"Famy").unwrap_or_default().is_empty() || !s.str(*f, b"Post").unwrap_or_default().is_empty()); - let font = resolved.or(requested); - if let Some(resolved) = resolved { - let differs = [b"Famy", b"Post"] - .iter() - .any(|tag| s.str(resolved, tag).unwrap_or_default() != requested.and_then(|f| s.str(f, tag)).unwrap_or_default()); - if differs { - r.warn("text uses a stored fallback font (imported with that font)"); - } - } - if font.and_then(|f| s.int(f, b"Widh")).is_some_and(|w| w != 5) { - r.warn("font width variants (exact face depends on the installed PostScript font)"); - } - let postscript = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default()); - let family = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default()); - let (features, all_caps) = font_features(r, objects.get(7).copied().flatten(), attribute_budget); - let weight = font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400); - let weight = if (1..=1000).contains(&weight) { - weight - } else { - r.warn("invalid font weight (imported as regular)"); - 400 - }; - TextRun { - text, - postscript, - family, - weight, - italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false), - features, - all_caps, - underline, - strikethrough, - size, - tracking, - h_scale, - leading, - fill, - stroke, - paragraph: Paragraph::default(), - } -} - -fn charge_attributes(r: &mut Reader, budget: &mut Option, bytes: usize) -> bool { - let Some(remaining) = *budget else { return false }; - match remaining.checked_sub(bytes) { - Some(remaining) => { - *budget = Some(remaining); - true - } - None => { - *budget = None; - r.warn("text attribute budget exceeded (excess font names, features and gradients left out)"); - false - } - } -} - -/// Longest font name kept (OpenType names are far shorter); every run and paragraph carries it. -const MAX_FONT_NAME: usize = 256; - -fn font_name(r: &mut Reader, budget: &mut Option, value: &str) -> String { - if value.len() > MAX_FONT_NAME { - r.warn("font names longer than 256 bytes (the default font is used)"); - return String::new(); - } - metadata_string(r, budget, value) -} - -fn metadata_string(r: &mut Reader, budget: &mut Option, value: &str) -> String { - let bytes = value.len().saturating_add(std::mem::size_of::()); - if value.is_empty() || !charge_attributes(r, budget, bytes) { String::new() } else { value.to_owned() } -} - -/// The public Affinity 3 caps fixture stores `smcp` and the private `CAP\x01` selector in -/// OtAt/Setn. Only the observed all-caps selector and boolean OpenType tags are mapped; other -/// values are reported, never guessed. Standard tag syntax: https://learn.microsoft.com/en-us/typography/opentype/spec/featuretags -fn font_features(r: &mut Reader, attrs: Option, attribute_budget: &mut Option) -> (Vec, bool) { - let mut features = Vec::new(); - let mut all_caps = false; - if attribute_budget.is_none() { - return (features, all_caps); - } - let s = r.s; - let Some(Value::Array(settings)) = attrs.and_then(|a| s.field(a, b"Setn")) else { return (features, all_caps) }; - for (index, setting) in settings.iter().take(257).enumerate() { - if index == 256 { - r.warn("more than 256 text feature settings (truncated)"); - break; - } - let Value::Obj(Some(setting)) = setting else { - r.warn("unreadable text feature settings (imported with defaults)"); - continue; - }; - let setting = *setting; - let tag = s.int(setting, b"Feat").and_then(|v| u32::try_from(v).ok()).map(u32::to_be_bytes); - let value = r.s.int(setting, b"Valu"); - match (tag, value) { - (Some([b'C', b'A', b'P', 1]), Some(0 | 1)) => all_caps = value == Some(1), - (Some(tag), Some(value @ (0 | 1))) if tag.iter().all(u8::is_ascii_alphanumeric) => { - if !charge_attributes(r, attribute_budget, std::mem::size_of::() + if value == 0 { 5 } else { 4 }) { - break; - } - let name = String::from_utf8_lossy(&tag); - features.push(if value == 0 { format!("-{name}") } else { name.into_owned() }); - } - _ => r.warn("text feature selectors or non-boolean OpenType settings (imported with defaults)"), - } - } - (features, all_caps) -} - -/// A paragraph's alignment, indents, spacing and leading. The `Doub` slots: 0 the automatic -/// leading as a multiple of the font's line height (1 in every document checked), 1 fixed leading -/// (when `Ints` slot 1 is 2; in every paragraph checked the two go together), 2 indent of the -/// lines after the first, 3 right indent, 4 indent of the first line, 5 space before, 6 space -/// after. Slots 2, 4, 5 and 6 were identified on the public MIT text-indent and text-para-spacing -/// fixtures (Patchy) by measuring their thumbnails, slot 1 by measuring the baseline pitch in the -/// thumbnail of a document whose owner made it earlier. -fn paragraph(r: &mut Reader, p: ObjId) -> Paragraph { - let doubles = r.s.field(p, b"Doub"); - let ints = r.s.field(p, b"Ints"); - let at = |i: usize| slot(doubles, i, float).filter(|v| v.abs() < 1e6).unwrap_or(0.0); - let align = match slot(ints, 0, int) { - Some(1) => Align::Center, - Some(2) => Align::Right, - Some(3) => Align::Justify, - Some(0) | None => Align::Left, - Some(_) => { - r.warn("an unknown paragraph alignment (imported as left)"); - Align::Left - } - }; - let leading = match slot(ints, 1, int) { - Some(2) => Some(at(1)).filter(|l| *l > 0.0), - Some(0) | None => None, - Some(_) => { - r.warn("paragraph leading of an unknown kind (imported as automatic)"); - None - } - }; - let auto_leading = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0); - Paragraph { align, left: at(2), right: at(3), first: at(4), space_before: at(5).max(0.0), space_after: at(6).max(0.0), leading, auto_leading } -} - -/// The scale a text frame or table gives its type (`FTxS`, stored like `Xfrm`): none unless set. -/// Neither the frame's own transform nor its groups' scale its type (checked against the -/// thumbnails of tables and frames inside scaled groups). -fn text_scale(r: &mut Reader, id: ObjId) -> Affine { - match r.s.floats::<6>(id, b"FTxS").map(Affine::from_xfrm) { - Some(m) if m.is_finite() && m.scale() > 1e-9 => Affine([m.0[0], m.0[1], m.0[2], m.0[3], 0.0, 0.0]), - Some(_) => { - r.warn("text frames with an invalid text scale (imported unscaled)"); - Affine::IDENTITY - } - None => Affine::IDENTITY, - } -} diff --git a/crates/affinity/tests/it/outline_limits.rs b/crates/affinity/tests/it/outline_limits.rs index 74151c192f..15e08eb6be 100644 --- a/crates/affinity/tests/it/outline_limits.rs +++ b/crates/affinity/tests/it/outline_limits.rs @@ -20,6 +20,10 @@ fn shape(id: u32, class: &[u8; 4], parameters: Vec<(vectorcraft_affinity::stream } fn read(definitions: Vec, top: u32) -> Document { + try_read(definitions, top).unwrap() +} + +fn try_read(definitions: Vec, top: u32) -> Result { let data = synth::stream(&[ (tag(b"Defs"), F::Shared(definitions)), ( @@ -39,7 +43,7 @@ fn read(definitions: Vec, top: u32) -> Document { ), ]); let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None); - vectorcraft_affinity::read(&bytes, Limits::default()).unwrap() + vectorcraft_affinity::read(&bytes, Limits::default()) } fn path(document: &Document) -> &Path { @@ -200,3 +204,79 @@ fn unlocked_rectangle_corners_keep_their_own_radius_and_type() { assert_eq!(sub.segments.len(), 8); assert_eq!(sub.segments[3][2], p(5.0, 20.0)); } + +/// The special shapes come in as their own outlines: one closed contour of finite points inside +/// (or, for a callout's tail, just below) the node's box, and none as the bounding ellipse. +#[test] +fn special_shapes_have_their_own_closed_outlines() { + for class in [b"ShCl", b"ShHt", b"ShCg", b"ShCR", b"ShCE", b"ShDA", b"ShDS", b"ShTr", b"ShCr", b"ShpD", b"ShSg"] { + let name = String::from_utf8_lossy(class).into_owned(); + let document = read(vec![shape(100, class, vec![])], 100); + assert!(!document.warnings.iter().any(|w| w.contains("bounding ellipse")), "{name}: {:?}", document.warnings); + let (Kind::Shape { path, even_odd, .. }, cog) = (&document.spreads[0].nodes[0].kind, class == b"ShCg") else { panic!("{name}: no shape") }; + // A cog is its teeth and its hole, filled even-odd. + assert_eq!((path.subpaths.len(), *even_odd), if cog { (2, true) } else { (1, false) }, "{name}"); + for sub in &path.subpaths { + assert!(sub.closed && sub.segments.len() >= 2, "{name}"); + for p in std::iter::once(sub.start).chain(sub.segments.iter().flatten().copied()) { + assert!(p.x.is_finite() && p.y.is_finite(), "{name}: {p:?}"); + assert!((-5.0..=15.0).contains(&p.x) && (-10.0..=30.0).contains(&p.y), "{name}: {p:?}"); + } + } + } + // A class the reader does not know is still its bounding ellipse, and said. + let document = read(vec![shape(100, b"ShZZ", vec![])], 100); + assert!(document.warnings.iter().any(|w| w.contains("unrecognized parametric shape")), "{:?}", document.warnings); +} + +fn group(id: u32, children: Vec) -> F { + F::Def(id, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared(children))]) +} + +/// A list's null slots yield no node, operand or segment, but each visit of a shared object scans +/// them all: they are charged to the document's work before the scan. +#[test] +fn null_slots_of_shared_lists_are_charged_for_every_visit() { + // A compound of a million null operands, placed 20 times: 20 million slots, over the 2^24. + let document = read(vec![compound(100, vec![F::Null; 1_000_000]), group(200, vec![F::Ref(100); 20])], 200); + assert!(document.warnings.iter().any(|w| w.contains("geometry work limit")), "{:?}", document.warnings); + let shapes = document.spreads[0].nodes[0].children.iter().filter(|n| matches!(n.kind, Kind::Shape { .. })).count(); + assert_eq!(shapes, 16, "each placement costs a million slots of the 2^24"); + // A group of a million null children, placed 20 times, fails the read like too many layers. + let result = try_read(vec![group(100, vec![F::Null; 1_000_000]), group(200, vec![F::Ref(100); 20])], 200); + assert!(matches!(result, Err(vectorcraft_affinity::Error::Limit(_))), "{:?}", result.map(|d| d.warnings)); + // Within the work of one document the same lists are read, nulls skipped. + let document = read(vec![group(100, vec![F::Null; 1_000]), group(200, vec![F::Ref(100); 20])], 200); + assert_eq!((document.spreads[0].nodes[0].children.len(), document.warnings.len()), (20, 0)); +} + +fn boxed(class: &[u8; 4], b: Vec) -> F { + F::Def(100, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(b)), (tag(b"Shpe"), F::Def(10_100, vec![tag(class)], vec![]))]) +} + +/// A callout rectangle (`ShCR`) whose box runs right to left (x0 > x1) panicked in `f64::clamp` +/// (min > max), found by the `stream` fuzz target. It reads, inside its box. +#[test] +fn callout_rectangle_with_a_reversed_box_reads_inside_it() { + for b in [vec![10.0_f64, 0.0, 0.0, 20.0], vec![6.8e38, 0.0, 10.0, 20.0]] { + let (lo, hi) = (b[0].min(b[2]), b[0].max(b[2])); + let document = read(vec![boxed(b"ShCR", b)], 100); + let sub = &path(&document).subpaths[0]; + let points = std::iter::once(&sub.start).chain(sub.segments.iter().flatten()); + assert!(points.into_iter().all(|q| q.x.is_finite() && q.y.is_finite() && (lo..=hi).contains(&q.x)), "{sub:?}"); + } +} + +/// A box with finite corners whose width overflows gave infinite and NaN outline points. Such a +/// shape imports as its box, with a warning. +#[test] +fn a_shape_too_large_to_compute_imports_as_its_box() { + for class in [b"ShCR", b"ShpE", b"ShCg"] { + let document = read(vec![boxed(class, vec![f64::MAX, 0.0, -f64::MAX, 20.0])], 100); + let sub = &path(&document).subpaths; + assert_eq!(sub.len(), 1, "{class:?}"); + let corners: Vec = std::iter::once(sub[0].start).chain(sub[0].segments.iter().map(|s| s[2])).collect(); + assert!(corners.iter().all(|p| p.x.abs() == f64::MAX && (p.y == 0.0 || p.y == 20.0)), "{class:?}: {corners:?}"); + assert!(document.warnings.iter().any(|w| w.contains("too large to compute")), "{:?}", document.warnings); + } +} diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 13e8f0c53a..79ed6df5ec 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -19,7 +19,7 @@ patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"] patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-shapes-2.af dpi=72;spreads=1;model_crc32=886e9852;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 62, "shapes": 12, "strokes": 0, "subpaths": 12};boards=[];fonts={};warnings=["cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse) (9×)"] +patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[] patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[] patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 2ea6dea4fb..34f77ec929 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-cad" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018)" +description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer" [lints] workspace = true diff --git a/crates/cad/src/hpgl.rs b/crates/cad/src/hpgl.rs new file mode 100644 index 0000000000..9494fbee46 --- /dev/null +++ b/crates/cad/src/hpgl.rs @@ -0,0 +1,202 @@ +//! HP-GL import: a plotter file (HP-GL/2, `.plt`, `.hpgl`, `.hgl`, `.hpg`) as a document. Older +//! HP-GL files are read by the HP-GL/2 rules for the instructions the two share. +//! +//! The pen's moves become paths: each run drawn with the pen down is one stroked path in the +//! selected pen's color and width (0.35 mm unless PW sets another), with the line type as a dash +//! pattern and the line attributes as caps and joins. Circles, arcs, wedges, rectangles and Bézier +//! curves are drawn as curves (the chord angle isn't used). Filled rectangles, wedges and polygons +//! (polygon mode, FP) become filled paths, edged ones stroked paths. Plotter units (1016 to the +//! inch, y up) become points, through user units (SC, IP, IR) and the rotation (RO). The artboard +//! is the bounds of what the art paints, its strokes included. +//! +//! VectorCraft's own rules where the device decides: before the first SP the pen is pen 1 (a +//! device draws nothing until SP), and the hard-clip limits are 11 × 8.5 in from the origin, so +//! P2 lies there when the file sets no scaling points. SP0 draws nothing. Labels, symbol mode's symbols and raster +//! images (HP RTL) aren't drawn, the input window doesn't clip, hatched fills are filled solid, +//! and the art of every page goes on one artboard; each comes back as a warning. Printer escape +//! sequences and PJL lines around the instructions are skipped. +//! +//! [`export`] writes the visible art over a region as an HP-GL or HP-GL/2 plot, and +//! [`export_regions`] one plot per region with one pen numbering: see [`write`]. +//! +//! - `lex`: the bytes as instructions, numbers, labels and PE data. +//! - `plot`: the instructions played on the pen, as shapes. +//! - `write`: the writer, paths to pen moves. + +mod lex; +mod plot; +pub mod write; + +pub use write::{HpglOptions, HpglOutput, Origin, Version, export, export_regions}; + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, FillLayer, LayerColor, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, PathData, Rect}; + +use crate::Imported; +use lex::Lexer; +use plot::Plot; + +/// Points per plotter unit. +const PT_PER_PLU: f64 = 72.0 / 1016.0; +/// The weight of a zero-width pen (one device dot), in points. +const THINNEST: f64 = 0.25; + +/// Instructions the reader knows and draws nothing for (their parameters are read and dropped). +const IGNORED: &[[u8; 2]] = &[ + *b"AC", *b"AD", *b"AF", *b"AH", *b"AP", *b"AS", *b"CA", *b"CF", *b"CM", *b"CP", *b"CS", *b"CT", *b"CV", *b"DC", *b"DI", *b"DL", *b"DP", *b"DR", + *b"DS", *b"DV", *b"EC", *b"ES", *b"FI", *b"FN", *b"FS", *b"GM", *b"IM", *b"IV", *b"KY", *b"LM", *b"LO", *b"MC", *b"MG", *b"MT", *b"NR", *b"OA", + *b"OC", *b"OD", *b"OE", *b"OF", *b"OG", *b"OH", *b"OI", *b"OL", *b"OP", *b"OS", *b"OT", *b"OW", *b"PB", *b"PP", *b"PS", *b"PT", *b"QL", *b"RF", + *b"RP", *b"SA", *b"SB", *b"SD", *b"SG", *b"SI", *b"SL", *b"SR", *b"SS", *b"ST", *b"SV", *b"TD", *b"TL", *b"TR", *b"UC", *b"VA", *b"VN", *b"VS", + *b"XT", *b"YT", +]; + +/// Instructions the reader plays. +const PLAYED: &[[u8; 2]] = &[ + *b"AA", *b"AR", *b"AT", *b"BL", *b"BP", *b"BR", *b"BZ", *b"CI", *b"CO", *b"CR", *b"DF", *b"DT", *b"EA", *b"EP", *b"ER", *b"EW", *b"FP", *b"FR", + *b"FT", *b"IN", *b"IP", *b"IR", *b"IW", *b"LA", *b"LB", *b"LT", *b"NP", *b"PA", *b"PC", *b"PD", *b"PE", *b"PG", *b"PM", *b"PR", *b"PU", *b"PW", + *b"RA", *b"RO", *b"RR", *b"RT", *b"SC", *b"SM", *b"SP", *b"UL", *b"WD", *b"WG", *b"WU", +]; + +/// Instructions a plot file starts with. +const FIRST: &[[u8; 2]] = &[ + *b"IN", *b"DF", *b"BP", *b"CO", *b"PS", *b"SP", *b"PU", *b"PD", *b"PA", *b"PR", *b"IP", *b"IR", *b"SC", *b"NP", *b"PC", *b"PW", *b"WU", *b"RO", + *b"QL", *b"MC", *b"PP", *b"TR", *b"CR", *b"LT", *b"LA", *b"FT", *b"VS", *b"FS", *b"AC", *b"PG", *b"PE", *b"DT", +]; + +/// Does `bytes` start like an HP-GL file? After any printer escapes and PJL lines (however long), +/// it must hold nothing but instructions the reader knows, the first one of those a plot file +/// starts with, up to the eighth instruction or 4 KB past the first. Their parameters must be +/// numbers, but for a comment's quoted string and the text, characters and encoded data of LB, BL, +/// WD, DT, SM and PE. An instruction the reader doesn't know counts when its numbers end with a +/// semicolon. +pub fn is_hpgl(bytes: &[u8]) -> bool { + holds_instructions(bytes, true) +} + +/// Does `bytes` hold HP-GL instructions as [`is_hpgl`] checks? When `strict` is false, any of them +/// may come first: a file picked by its extension may start with one a plot file seldom starts +/// with (`SI`, `DI`). Either way, at least one of the instructions checked must be one the reader +/// knows. +fn holds_instructions(bytes: &[u8], strict: bool) -> bool { + let mut lex = Lexer::new(bytes); + let mut terminator = lex::ETX; + let mut first = 0; + let mut any_known = false; + for n in 0..8 { + if n > 0 && lex.pos() > first + 4096 { + return any_known; + } + let Some(op) = lex.op(true) else { return n > 0 && any_known && lex.done() }; + if n == 0 { + first = lex.pos(); + } + if strict && n == 0 && !FIRST.contains(&op) { + return false; + } + let known = PLAYED.contains(&op) || IGNORED.contains(&op); + any_known |= known; + match &op { + b"CO" => { + if !lex.comment() { + return false; + } + } + b"LB" | b"BL" | b"WD" => lex.label(terminator), + b"DT" => { + terminator = lex.char().unwrap_or(lex::ETX); + lex.params(); + } + b"SM" => { + // The symbol character is read so it isn't taken for an instruction. + let _ = lex.char(); + } + b"PE" => lex.skip_pe(), + _ if known => lex.params(), + // An instruction the reader doesn't know (of an older or a device's own set) counts + // when numbers and a semicolon follow it. + _ => { + if !lex.closed_params() { + return false; + } + } + } + } + any_known +} + +/// Read an HP-GL file. It may start with any instruction the reader knows, or one of another set +/// that a semicolon ends; the rest of [`is_hpgl`]'s check applies, and at least one instruction the +/// reader knows must be among those it checks. +pub fn import(bytes: &[u8]) -> Result { + if !holds_instructions(bytes, false) { + return Err("not an HP-GL file".into()); + } + let mut lex = Lexer::new(bytes); + let mut plot = Plot::new(); + while !plot.full + && let Some(op) = lex.op(false) + { + plot.op(op, &mut lex); + } + Ok(build(plot.finish(lex.raster))) +} + +fn rgb(c: [u8; 3]) -> Paint { + Paint::solid(Color::rgb8(c[0], c[1], c[2])) +} + +/// The plot's shapes as paths on one layer, the artboard round what they paint. +fn build(plot: Plot) -> Imported { + // Plotter units, y up, to points, y down. + let flip = Affine::scale_non_uniform(PT_PER_PLU, -PT_PER_PLU); + let mut nodes: Vec = plot.shapes.iter().map(|s| node(s, flip)).collect(); + // The strokes' caps and miter joins included. + let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); + let frame = nodes.iter().filter_map(Node::visual_bounds).filter(finite).reduce(|a, b| a.union(b)).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0)); + let mut doc = Document::new(frame.width().max(1.0), frame.height().max(1.0)); + doc.layers.clear(); + let shift = Affine::translate(-frame.origin().to_vec2()); + for n in &mut nodes { + n.id = doc.alloc_id(); + if let NodeKind::Path { path, .. } = &mut n.kind { + path.transform(shift); + } + } + let mut layer = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + if let Some(c) = layer.children_mut() { + *c = nodes.into_iter().map(Arc::new).collect(); + } + doc.layers = vec![Arc::new(layer)]; + Imported { document: doc, warnings: plot.warnings } +} + +/// A shape as a path, its plotter units through `to_points`. +fn node(s: &plot::Shape, to_points: Affine) -> Node { + let mut path = s.path.clone(); + path.apply_affine(to_points); + let mut items = vec![]; + if let Some((c, _)) = s.fill { + items.push(AppearanceItem::Fill(FillLayer::new(rgb(c)))); + } + if let Some(st) = &s.stroke { + let mut layer = StrokeLayer::new(rgb(st.color), (st.width * PT_PER_PLU).max(THINNEST)); + (layer.cap, layer.join, layer.miter_limit) = (st.cap, st.join, st.miter); + layer.dash = st.dash.as_ref().map(|d| Dash { + pattern: d.pattern.iter().map(|v| v * PT_PER_PLU).collect(), + offset: d.offset * PT_PER_PLU, + align_corners: d.adaptive, + }); + items.push(AppearanceItem::Stroke(layer)); + } + let mut n = Node::path(NodeId(0), PathData::from_bezpath(&path), Appearance { items, ..Appearance::default() }); + if let (NodeKind::Path { rule, .. }, Some((_, r))) = (&mut n.kind, s.fill) { + *rule = r; + } + n +} + +#[cfg(test)] +mod tests; diff --git a/crates/cad/src/hpgl/lex.rs b/crates/cad/src/hpgl/lex.rs new file mode 100644 index 0000000000..5025d07c6f --- /dev/null +++ b/crates/cad/src/hpgl/lex.rs @@ -0,0 +1,428 @@ +//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow +//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the +//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped, +//! with the data their escapes carry. + +/// The end-of-text character, the default label terminator. +pub(super) const ETX: u8 = 3; +const ESC: u8 = 0x1b; + +/// The most digits of a number that count: longer ones are read as their first digits. +const MAX_DIGITS: usize = 18; + +/// What the bytes being read hold. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + /// HP-GL instructions. + Hpgl, + /// PCL or HP RTL: escape sequences and their data, nothing to draw. + Pcl, + /// After a Universal Exit Language: PJL lines until a language starts. + Pjl, +} + +/// One item of a PE (Polyline Encoded) instruction. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum PeItem { + /// Select pen. + Pen(i64), + /// Rectangle mode: the following coordinates come in fours. + Rect, + /// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`). + Point { x: f64, y: f64, up: bool, absolute: bool }, +} + +/// The state of one PE instruction being read. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Pe { + seven_bit: bool, + fraction_bits: u32, + up: bool, + absolute: bool, +} + +pub(super) struct Lexer<'a> { + b: &'a [u8], + at: usize, + mode: Mode, + /// The file holds HP RTL or PCL raster image data. + pub raster: bool, +} + +/// Is `c` a byte that separates numeric parameters (or white space between instructions)? +fn separator(c: u8) -> bool { + matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0) +} + +impl<'a> Lexer<'a> { + pub fn new(b: &'a [u8]) -> Self { + Self { b, at: 0, mode: Mode::Hpgl, raster: false } + } + + fn peek(&self) -> Option { + self.b.get(self.at).copied() + } + + /// Whether everything has been read. + pub fn done(&self) -> bool { + self.at >= self.b.len() + } + + /// How many bytes have been read. + pub fn pos(&self) -> usize { + self.at + } + + /// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and + /// escape sequences may come before it (anything else gives `None`, as the end does). + pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> { + loop { + let c = self.peek()?; + if c == ESC { + self.escape(); + continue; + } + match self.mode { + Mode::Pcl => { + self.at += 1; + continue; + } + Mode::Pjl => { + if separator(c) { + self.at += 1; + } else if c == b'@' { + self.pjl_line(); + } else { + self.mode = Mode::Hpgl; + } + continue; + } + Mode::Hpgl => {} + } + let next = self.b.get(self.at + 1).copied(); + if c.is_ascii_alphabetic() + && let Some(n) = next.filter(u8::is_ascii_alphabetic) + { + self.at += 2; + return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]); + } + if strict && !(separator(c) || c == b';' || c < 0x20) { + return None; + } + self.at += 1; + } + } + + /// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows. + fn pjl_line(&mut self) { + let rest = &self.b[self.at..]; + let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1); + // A command names its language within its first 256 bytes; longer lines aren't copied. + let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase(); + if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) { + self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl }; + } + self.at += end; + } + + /// An escape sequence at the current byte, with the data it carries. + fn escape(&mut self) { + self.at += 1; + let Some(c) = self.peek() else { return }; + self.at += 1; + match c { + // Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL, + // `ESC%#A` to PCL or HP RTL). + b'%' => { + let (_, end) = self.value(); + match end { + Some(b'X') => self.mode = Mode::Pjl, + Some(b'B') => self.mode = Mode::Hpgl, + Some(b'A') => self.mode = Mode::Pcl, + _ => {} + } + } + // Reset: PCL follows, until a language switch. + b'E' => self.mode = Mode::Pcl, + // HP-GL device control: `ESC.` and a letter, with parameters up to a colon. + b'.' => { + let Some(kind) = self.peek() else { return }; + self.at += 1; + if !b"()YZBEJKLORUX".contains(&kind) { + let rest = &self.b[self.at..self.b.len().min(self.at + 80)]; + if let Some(n) = rest.iter().position(|&c| c == b':') + && rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b',')) + { + self.at += n + 1; + } + } + } + // Parameterized PCL: a group character, then values each ending in a letter (upper case + // ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print + // data) are followed by that many bytes of data. Without a group character (`ESC(8U`, + // `ESC)0N`), one value and the letter ending it. + 0x21..=0x2f => { + let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else { + self.value(); + return; + }; + self.at += 1; + loop { + let (v, end) = self.value(); + let Some(end) = end else { return }; + let upper = end.to_ascii_uppercase(); + if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') { + let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize; + if (c, group) == (b'*', b'b') && n > 0 { + self.raster = true; + } + self.at += n; + } + if (c, group, end) == (b'*', b'r', b'A') { + self.raster = true; + } + if !end.is_ascii_lowercase() { + return; + } + } + } + // A two-character escape. + _ => {} + } + } + + /// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None` + /// when that is not a letter or `@` (which is then left unread). + fn value(&mut self) -> (f64, Option) { + let v = self.number_here().unwrap_or(0.0); + match self.peek() { + Some(c) if c.is_ascii_alphabetic() || c == b'@' => { + self.at += 1; + (v, Some(c)) + } + _ => (v, None), + } + } + + /// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit + /// (its sign and point are read all the same). + fn number_here(&mut self) -> Option { + let mut neg = false; + if let Some(c @ (b'+' | b'-')) = self.peek() { + neg = c == b'-'; + self.at += 1; + } + let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64); + let mut point = false; + while let Some(c) = self.peek() { + if c.is_ascii_digit() { + if digits < MAX_DIGITS { + if point { + scale /= 10.0; + v += f64::from(c - b'0') * scale; + } else { + v = v * 10.0 + f64::from(c - b'0'); + } + } else if !point { + // Past the digits that count, an integer part keeps its size. + v *= 10.0; + } + digits += 1; + } else if c == b'.' && !point { + point = true; + } else { + break; + } + self.at += 1; + } + let v = v.min(f64::MAX); + (digits > 0).then_some(if neg { -v } else { v }) + } + + /// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon + /// ending it is read). + pub fn number(&mut self) -> Option { + loop { + let c = self.peek()?; + if separator(c) { + self.at += 1; + } else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') { + if let Some(v) = self.number_here() { + return Some(v); + } + } else { + if c == b';' { + self.at += 1; + } + return None; + } + } + } + + /// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many. + pub fn numbers(&mut self, out: &mut [f64]) -> usize { + let mut n = 0; + while let Some(v) = self.number() { + if let Some(slot) = out.get_mut(n) { + *slot = v; + } + n += 1; + } + n.min(out.len()) + } + + /// Read and drop the parameters of the instruction being read: numbers and quoted strings. + pub fn params(&mut self) { + loop { + while self.number().is_some() {} + if self.peek() != Some(b'"') { + return; + } + self.quoted(); + } + } + + /// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader + /// doesn't know, written out in full). + pub fn closed_params(&mut self) -> bool { + while self.number().is_some() {} + self.at > 0 && self.b.get(self.at - 1) == Some(&b';') + } + + /// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it + /// is one. + pub fn comment(&mut self) -> bool { + while self.peek().is_some_and(separator) { + self.at += 1; + } + match self.peek() { + Some(b'"') => self.quoted(), + Some(b';') => { + self.at += 1; + true + } + None => true, + Some(_) => false, + } + } + + /// The text of a label, up to and including `terminator` (or the end). + pub fn label(&mut self, terminator: u8) { + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1); + } + + /// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether + /// there was one. + pub fn quoted(&mut self) -> bool { + while self.peek().is_some_and(separator) { + self.at += 1; + } + let found = self.peek() == Some(b'"'); + if found { + self.at += 1; + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1); + } + if self.peek() == Some(b';') { + self.at += 1; + } + found + } + + /// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end + /// (the semicolon is read). + pub fn char(&mut self) -> Option { + let c = self.peek()?; + self.at += 1; + (c != b';').then_some(c) + } + + /// The next item of a PE instruction, `None` at its end (its semicolon is read). + pub fn pe(&mut self, st: &mut Pe) -> Option { + loop { + let raw = self.peek()?; + let c = raw & 0x7f; + // Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored. + if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { + self.at += 1; + continue; + } + match c { + b';' => { + self.at += 1; + return None; + } + // Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up). + b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => { + self.at += 1; + match c { + b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()), + b'<' => st.up = true, + b'>' => match self.pe_value(st) { + Some(n) => st.fraction_bits = n.clamp(0, 52) as u32, + None => return self.end_pe(), + }, + b'=' => st.absolute = true, + b'7' => st.seven_bit = true, + _ => return Some(PeItem::Rect), + } + } + _ => { + let scale = 0.5f64.powi(st.fraction_bits as i32); + let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() }; + let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute }; + (st.up, st.absolute) = (false, false); + return Some(item); + } + } + } + } + + /// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`]. + fn end_pe(&mut self) -> Option { + self.skip_pe(); + None + } + + /// The data of a PE instruction, up to and including its semicolon, unread: its data is never + /// read as instructions. + pub fn skip_pe(&mut self) { + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1); + } + + /// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no + /// digit comes first, which is read). + fn pe_value(&mut self, st: &Pe) -> Option { + let (base, low, high): (u64, std::ops::RangeInclusive, std::ops::RangeInclusive) = + if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) }; + let (mut v, mut place) = (0u64, 1u64); + loop { + let raw = self.peek()?; + let c = if st.seven_bit { raw & 0x7f } else { raw }; + if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { + self.at += 1; + continue; + } + if c == b';' { + return None; + } + self.at += 1; + let (digit, last) = if low.contains(&c) { + (u64::from(c - 63), false) + } else if high.contains(&c) { + (u64::from(c - high.start()), true) + } else { + return None; + }; + v = v.saturating_add(digit.saturating_mul(place)); + place = place.saturating_mul(base); + if last { + // The low bit is the sign. + let n = i64::try_from(v >> 1).unwrap_or(i64::MAX); + return Some(if v & 1 == 1 { -n } else { n }); + } + } + } +} diff --git a/crates/cad/src/hpgl/plot.rs b/crates/cad/src/hpgl/plot.rs new file mode 100644 index 0000000000..2ee70da75c --- /dev/null +++ b/crates/cad/src/hpgl/plot.rs @@ -0,0 +1,1331 @@ +//! The HP-GL/2 instructions played on a model of the plotter: the coordinate system (scaling +//! points, user units, rotation), the pen (position, up or down, number, width, color), the line +//! and fill attributes and the polygon buffer. What the pen draws is collected as shapes in +//! rotated plotter units, y up. + +use std::collections::HashMap; + +use kurbo::{Affine, BezPath, PathEl, Point, Shape as _, Vec2}; +use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::FillRule; + +use super::lex::{ETX, Lexer, Pe, PeItem}; + +/// Plotter units per millimeter (0.025 mm each). +pub(super) const PLU_PER_MM: f64 = 40.0; +/// The hard-clip limits taken for P1 and P2 when the file sets none (plotter units): 11 × 8.5 in. +pub(super) const HARD_CLIP: Point = Point::new(11176.0, 8636.0); +/// The pen width after IN, in millimeters. +const DEFAULT_WIDTH_MM: f64 = 0.35; +/// The default line pattern length, in percent of the P1-P2 diagonal. +const DEFAULT_PATTERN: f64 = 4.0; +/// How far from the origin art may lie (plotter units, twice the range the format defines). +pub(super) const LIMIT: f64 = 16_777_216.0; +/// The widest pen (plotter units): 409.6 mm, the least a device must take before it draws its own +/// widest pen instead. +const MAX_WIDTH: f64 = 16_384.0; +/// The most objects an import makes. +const MAX_SHAPES: usize = 1 << 20; +/// The most path elements an import makes. +const MAX_ELEMENTS: usize = if cfg!(test) { 200_000 } else { 4_000_000 }; +/// The most pens a palette holds. +const MAX_PENS: i64 = 32_768; + +pub(super) const LABELS: &str = "labels were left out"; +pub(super) const SYMBOLS: &str = "symbols drawn at plotted points (symbol mode) were left out"; +pub(super) const RASTER: &str = "raster images in the file were left out"; +pub(super) const HATCHES: &str = "hatched and patterned fills are filled solid"; +pub(super) const WINDOW: &str = "the input window doesn't clip the art"; +pub(super) const PAGES: &str = "the art of later pages is drawn over the first page"; +pub(super) const FAR_AWAY: &str = "objects far outside the drawing were left out"; +pub(super) const TOO_MANY: &str = "the file has more than 1,048,576 objects: the rest are left out"; +pub(super) const TOO_MANY_POINTS: &str = "the file has more than 4,000,000 path points: the rest are left out"; + +/// The instructions polygon mode plays (the others are ignored there). +const POLYGON_MODE: &[[u8; 2]] = + &[*b"AA", *b"AR", *b"AT", *b"BP", *b"BR", *b"BZ", *b"CI", *b"CO", *b"DF", *b"IN", *b"PA", *b"PD", *b"PE", *b"PM", *b"PR", *b"PU", *b"RT"]; + +/// The colors of pens 0 to 7 until PC sets others. +const PALETTE: [[u8; 3]; 8] = [[255, 255, 255], [0, 0, 0], [255, 0, 0], [0, 255, 0], [255, 255, 0], [0, 0, 255], [255, 0, 255], [0, 255, 255]]; + +/// Line types 1 to 8: pen-down and pen-up lengths in percent of the pattern length. +const LINE_TYPES: [&[f64]; 8] = [ + &[0.0, 100.0], + &[50.0, 50.0], + &[70.0, 30.0], + &[80.0, 10.0, 0.0, 10.0], + &[70.0, 10.0, 10.0, 10.0], + &[50.0, 10.0, 10.0, 10.0, 10.0, 10.0], + &[70.0, 10.0, 0.0, 10.0, 0.0, 10.0], + &[50.0, 10.0, 0.0, 10.0, 10.0, 10.0, 0.0, 10.0], +]; + +/// A stroke as the pen draws it (lengths in plotter units). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Stroke { + pub color: [u8; 3], + pub width: f64, + pub cap: LineCap, + pub join: LineJoin, + pub miter: f64, + pub dash: Option, +} + +/// A line type as dashes (lengths in plotter units). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct LinePattern { + /// Dash, gap, dash, gap…: an even number of lengths. + pub pattern: Vec, + /// How far into the pattern each line starts. + pub offset: f64, + /// The pattern stretches to fit each line, half its first dash at each end (adaptive line + /// types). + pub adaptive: bool, +} + +impl LinePattern { + /// The pattern of `percent` (pen-down and pen-up stretches, in turn, starting pen down) of + /// `length`. A pen-down stretch of zero is a dot, a vector one plotter unit long that the gap + /// after it gives up. An odd count repeats with its last pen-down stretch running into the + /// first one, which the pattern then starts within. + fn new(percent: &[f64], length: f64, adaptive: bool) -> Self { + let mut pattern: Vec = percent.iter().map(|p| p / 100.0 * length).collect(); + for pair in pattern.chunks_mut(2) { + if let [dash, rest @ ..] = pair + && *dash == 0.0 + { + *dash = 1.0; + if let Some(gap) = rest.first_mut() { + *gap = (*gap - 1.0).max(0.0); + } + } + } + let mut offset = 0.0; + if pattern.len() % 2 == 1 { + match pattern.len() { + // One pen-down stretch: a solid line. + 1 => pattern.push(0.0), + _ => { + let last = pattern.pop().unwrap_or(0.0); + if let Some(first) = pattern.first_mut() { + *first += last; + } + offset = last; + } + } + } + Self { pattern, offset, adaptive } + } +} + +/// What the plot draws: an outline with a fill, a stroke or both. +#[derive(Clone, Debug)] +pub(super) struct Shape { + pub path: BezPath, + pub fill: Option<([u8; 3], FillRule)>, + pub stroke: Option, +} + +/// A piece of a line the pen moves along, by its end. +#[derive(Clone, Copy, Debug)] +enum Piece { + Line(Point), + Curve(Point, Point, Point), +} + +impl Piece { + fn end(self) -> Point { + match self { + Self::Line(p) | Self::Curve(_, _, p) => p, + } + } + + fn push(self, bp: &mut BezPath) { + match self { + Self::Line(p) => bp.line_to(p), + Self::Curve(a, b, c) => bp.curve_to(a, b, c), + } + } +} + +/// User units: an SC instruction in force. +#[derive(Clone, Copy, Debug)] +enum Scaling { + /// The user ranges mapped onto P1 and P2; isotropic with the left and bottom percentages. + Fit { x0: f64, x1: f64, y0: f64, y1: f64, iso: Option<(f64, f64)> }, + /// P1's user coordinates and the plotter units per user unit. + Factor { x0: f64, fx: f64, y0: f64, fy: f64 }, +} + +/// How areas are filled. +#[derive(Clone, Copy, Debug, PartialEq)] +enum FillKind { + Solid, + /// The pen's color at this percentage, on white. + Shade(f64), + /// Hatching and patterns, filled solid. + Pattern, +} + +/// The polygon buffer: its outline for filling (every edge) and for edging (pen-down edges only). +#[derive(Clone, Debug, Default)] +struct Poly { + fill: BezPath, + edge: BezPath, + /// A subpolygon is open, from `start`; its last point. + open: bool, + start: Point, + last: Point, + /// The open subpolygon's points, and where its elements start in `fill` and `edge`. + points: usize, + marks: (usize, usize), + /// Where the edge outline ends (`None`: it has to move before drawing). + edge_at: Option, + /// After PM1 or a circle: the next move starts a subpolygon. + fresh: bool, +} + +impl Poly { + fn add(&mut self, a: Point, pieces: &[Piece], down: bool) { + let Some(end) = pieces.last().map(|p| p.end()) else { return }; + // The move after PM1 goes to the next subpolygon's first point with the pen up, whatever + // the pen's state (an arc's first chord aside): it is neither filled nor edged. + if std::mem::take(&mut self.fresh) && matches!(pieces, [Piece::Line(_)]) { + (self.start, self.last) = (end, end); + return; + } + if !self.open { + self.marks = (self.fill.elements().len(), self.edge.elements().len()); + self.fill.move_to(a); + (self.start, self.open, self.points) = (a, true, 1); + } + pieces.iter().for_each(|p| p.push(&mut self.fill)); + self.points += pieces.len(); + if down { + if self.edge_at != Some(a) { + self.edge.move_to(a); + } + pieces.iter().for_each(|p| p.push(&mut self.edge)); + self.edge_at = Some(end); + } else { + self.edge_at = None; + } + self.last = end; + } + + /// Close the open subpolygon, adding a point at its start when it ends elsewhere; the edge to + /// that point is drawn when `down`. A subpolygon of fewer than three points (that one + /// included) is neither filled nor edged. → The point added. + fn close(&mut self, down: bool) -> Option { + if !self.open { + return None; + } + let closure = self.last != self.start; + if self.points + usize::from(closure) < 3 { + self.fill.truncate(self.marks.0); + self.edge.truncate(self.marks.1); + } else { + if closure && down { + if self.edge_at != Some(self.last) { + self.edge.move_to(self.last); + } + self.edge.line_to(self.start); + } + self.fill.close_path(); + } + (self.open, self.edge_at) = (false, None); + closure.then_some(self.start) + } + + /// A closed outline of its own (a circle): the open subpolygon is closed with the pen up + /// first, and the next move starts a subpolygon. + fn closed(&mut self, path: &BezPath) { + self.close(false); + self.fill.extend(path.iter()); + self.edge.extend(path.iter()); + self.fresh = true; + } +} + +/// The line drawn so far with the pen down, not yet a shape. +struct Run { + path: BezPath, + stroke: Stroke, + start: Point, + end: Point, +} + +pub(super) struct Plot { + pub shapes: Vec, + pub warnings: Vec, + /// A budget ran out: nothing more is drawn. + pub full: bool, + elements: usize, + // The coordinate system. + p1: Point, + p2: Point, + scaling: Option, + /// User units to plotter units (identity when scaling is off). + user: Affine, + /// The RO rotation (rotated plotter units to where the art lies) and its angle. + rot: Affine, + ro: u16, + // The pen. + relative: bool, + down: bool, + /// The pen's position, in plotter units before rotation. + pos: Point, + /// The pen SP selected (`None`: none yet, which draws with pen 1). + pen: Option, + pens: i64, + colors: HashMap, + ranges: [(f64, f64); 3], + width: f64, + widths: HashMap, + relative_widths: bool, + // Line and fill attributes. + line_type: Option, + saved_line_type: Option, + pattern: f64, + pattern_mm: bool, + user_types: [Option>; 8], + cap: LineCap, + join: LineJoin, + miter: f64, + fill: FillKind, + // Polygons. + poly: Option, + buffer: Option, + run: Option, + terminator: u8, + /// Instructions of kinds the reader doesn't know. + pub unknown: usize, + /// How many shapes there were at the first page advance. + page_end: Option, +} + +impl Plot { + pub fn new() -> Self { + let mut p = Self { + shapes: vec![], + warnings: vec![], + full: false, + elements: 0, + p1: Point::ZERO, + p2: HARD_CLIP, + scaling: None, + user: Affine::IDENTITY, + rot: Affine::IDENTITY, + ro: 0, + relative: false, + down: false, + pos: Point::ZERO, + pen: None, + pens: 8, + colors: HashMap::new(), + ranges: [(0.0, 255.0); 3], + width: DEFAULT_WIDTH_MM * PLU_PER_MM, + widths: HashMap::new(), + relative_widths: false, + line_type: None, + saved_line_type: None, + pattern: DEFAULT_PATTERN, + pattern_mm: false, + user_types: Default::default(), + cap: LineCap::Butt, + join: LineJoin::Miter, + miter: 5.0, + fill: FillKind::Solid, + poly: None, + buffer: None, + run: None, + terminator: ETX, + unknown: 0, + page_end: None, + }; + p.init(); + p + } + + pub fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + // ---------- defaults ---------- + + /// DF: the line and fill attributes, scaling, plotting mode and polygon mode as they start. + fn defaults(&mut self) { + self.flush(); + self.relative = false; + (self.line_type, self.saved_line_type, self.pattern, self.pattern_mm) = (None, None, DEFAULT_PATTERN, false); + self.user_types = Default::default(); + (self.cap, self.join, self.miter) = (LineCap::Butt, LineJoin::Miter, 5.0); + self.fill = FillKind::Solid; + (self.poly, self.buffer) = (None, None); + self.scaling = None; + self.ranges = [(0.0, 255.0); 3]; + self.terminator = ETX; + self.update_user(); + } + + /// IN: DF, and the pen up at the origin, default widths, palette and scaling points, no + /// rotation. The selected pen stays. + fn init(&mut self) { + self.defaults(); + (self.pos, self.down) = (Point::ZERO, false); + (self.width, self.relative_widths) = (DEFAULT_WIDTH_MM * PLU_PER_MM, false); + self.widths.clear(); + (self.rot, self.ro) = (Affine::IDENTITY, 0); + (self.p1, self.p2) = (Point::ZERO, HARD_CLIP); + self.pens = 8; + self.colors.clear(); + self.update_user(); + } + + // ---------- coordinates ---------- + + /// User units to plotter units for the scaling in force; scaling that maps everything onto one + /// point is ignored. + fn update_user(&mut self) { + let (p1, p2) = (self.p1, self.p2); + let user = match self.scaling { + None => Affine::IDENTITY, + Some(Scaling::Factor { x0, fx, y0, fy }) => { + Affine::translate(p1.to_vec2()) * Affine::scale_non_uniform(fx, fy) * Affine::translate((-x0, -y0)) + } + Some(Scaling::Fit { x0, x1, y0, y1, iso }) => { + let (w, h, ux, uy) = (p2.x - p1.x, p2.y - p1.y, x1 - x0, y1 - y0); + let (mut sx, mut sy, mut off) = (w / ux, h / uy, Vec2::ZERO); + if let Some((left, bottom)) = iso { + let s = sx.abs().min(sy.abs()); + let (extra_x, extra_y) = (w.abs() - ux.abs() * s, h.abs() - uy.abs() * s); + off = Vec2::new(extra_x * left / 100.0 * w.signum(), extra_y * bottom / 100.0 * h.signum()); + (sx, sy) = (s * sx.signum(), s * sy.signum()); + } + Affine::translate(p1.to_vec2() + off) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-x0, -y0)) + } + }; + let det = user.determinant(); + self.user = if det.is_finite() && det != 0.0 && user.as_coeffs().iter().all(|c| c.is_finite()) { user } else { Affine::IDENTITY }; + } + + /// A point in current units, in plotter units. + fn to_plu(&self, x: f64, y: f64) -> Point { + self.user * Point::new(x, y) + } + + /// An increment in current units, in plotter units. + fn delta(&self, x: f64, y: f64) -> Vec2 { + self.to_plu(x, y) - self.to_plu(0.0, 0.0) + } + + /// The pen's position in current units. + fn pos_user(&self) -> Point { + self.user.inverse() * self.pos + } + + /// Plotter units (before rotation) to where the art lies. + fn dev(&self, p: Point) -> Point { + self.rot * p + } + + /// User units to where the art lies. + fn user_dev(&self) -> Affine { + self.rot * self.user + } + + /// The far corner of the hard-clip limits in the current orientation (their sides swap at 90 + /// and 270 degrees). + fn hard_clip(&self) -> Point { + if self.ro % 180 == 90 { Point::new(HARD_CLIP.y, HARD_CLIP.x) } else { HARD_CLIP } + } + + /// RO: plotter units rotated `angle` degrees (0, 90, 180 or 270) to where the art lies, shifted + /// so the hard-clip limits stay where they were. + fn rotation(angle: u16) -> Affine { + let (w, h) = (HARD_CLIP.x, HARD_CLIP.y); + match angle { + 90 => Affine::new([0.0, 1.0, -1.0, 0.0, w, 0.0]), + 180 => Affine::new([-1.0, 0.0, 0.0, -1.0, w, h]), + 270 => Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, h]), + _ => Affine::IDENTITY, + } + } + + fn diagonal(&self) -> f64 { + (self.p2 - self.p1).hypot().max(1.0) + } + + // ---------- pens and attributes ---------- + + /// The palette entry the selected pen draws with (`None`: pen 0, no pen). + fn pen_index(&self) -> Option { + let n = self.pen.unwrap_or(1); + if n <= 0 { + return None; + } + Some((n - 1) % (self.pens - 1).max(1) + 1) + } + + fn color(&self, i: i64) -> [u8; 3] { + let default = usize::try_from(i).ok().and_then(|i| PALETTE.get(i)).copied().unwrap_or([0; 3]); + self.colors.get(&i).copied().unwrap_or(default) + } + + /// The stroke the selected pen draws (`None` for no pen). + fn stroke(&self) -> Option { + let i = self.pen_index()?; + let width = self.widths.get(&i).copied().unwrap_or(self.width).clamp(0.0, MAX_WIDTH); + let dash = self.line_type.filter(|k| *k != 0).map(|k| { + let index = k.unsigned_abs().clamp(1, 8) as usize - 1; + let length = if self.pattern_mm { self.pattern * PLU_PER_MM } else { self.pattern / 100.0 * self.diagonal() }; + match &self.user_types[index] { + Some(pct) => LinePattern::new(pct, length, k < 0), + None => LinePattern::new(LINE_TYPES[index], length, k < 0), + } + }); + Some(Stroke { color: self.color(i), width, cap: self.cap, join: self.join, miter: self.miter, dash }) + } + + /// The color the selected pen fills with (`None` for no pen). + fn fill_color(&mut self) -> Option<[u8; 3]> { + let c = self.color(self.pen_index()?); + match self.fill { + FillKind::Solid => Some(c), + FillKind::Pattern => { + self.warn(HATCHES); + Some(c) + } + FillKind::Shade(level) => { + let t = (level / 100.0).clamp(0.0, 1.0); + Some(c.map(|v| (255.0 - (255.0 - f64::from(v)) * t).round() as u8)) + } + } + } + + // ---------- output ---------- + + /// Count `n` path elements against the budget → whether they fit. + fn spend(&mut self, n: usize) -> bool { + self.elements += n; + if self.elements > MAX_ELEMENTS { + self.warn(TOO_MANY_POINTS); + self.full = true; + } + !self.full + } + + fn push(&mut self, shape: Shape) { + if shape.path.elements().len() < 2 { + return; + } + if self.shapes.len() >= MAX_SHAPES { + self.warn(TOO_MANY); + self.full = true; + return; + } + let b = shape.path.bounding_box(); + if ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT) { + return self.warn(FAR_AWAY); + } + self.shapes.push(shape); + } + + /// End the line being drawn. + fn flush(&mut self) { + let Some(run) = self.run.take() else { return }; + let mut els = run.path.into_elements(); + // Vectors of no length alone draw a dot: a vector one plotter unit long. + if els.len() == 1 { + els.push(PathEl::LineTo(run.start + Vec2::new(1.0, 0.0))); + } + // A line that ends where it started is closed, so its ends join. + if els.len() > 3 && run.end == run.start { + if matches!(els.last(), Some(PathEl::LineTo(p)) if *p == run.start) { + els.pop(); + } + els.push(PathEl::ClosePath); + } + self.push(Shape { path: BezPath::from_vec(els), fill: None, stroke: Some(run.stroke) }); + } + + /// A dot (a vector one plotter unit long) at `at`, drawn with the selected pen. + fn dot(&mut self, at: Point) { + if let Some(stroke) = self.stroke() { + let mut path = BezPath::new(); + path.move_to(at); + path.line_to(at + Vec2::new(1.0, 0.0)); + self.push(Shape { path, fill: None, stroke: Some(stroke) }); + } + } + + /// The pen moves from `a` along `pieces` (where the art lies), drawing when `down`; in polygon + /// mode the move goes into the polygon buffer. + fn trace(&mut self, a: Point, pieces: &[Piece], down: bool) { + // Only what goes into a path counts against the budget: outside polygon mode, moves with the + // pen up or with no pen (SP0) make nothing. + let draws = down && self.pen_index().is_some(); + if pieces.is_empty() || self.full || (!draws && self.poly.is_none()) || !self.spend(pieces.len()) { + return; + } + if let Some(poly) = &mut self.poly { + return poly.add(a, pieces, down); + } + let Some(stroke) = self.stroke() else { return }; + if self.line_type == Some(0) { + // Line type 0 draws a dot at each point given (an arc's or a curve's end). + self.flush(); + if let Some(p) = pieces.last() { + self.dot(p.end()); + } + return; + } + if self.run.as_ref().is_some_and(|r| r.stroke != stroke || r.end != a) { + self.flush(); + } + let run = self.run.get_or_insert_with(|| { + let mut path = BezPath::new(); + path.move_to(a); + Run { path, stroke, start: a, end: a } + }); + for p in pieces { + // A vector of no length adds nothing to a line (a line of nothing else is a dot). + if matches!(p, Piece::Line(b) if *b == run.end) { + continue; + } + p.push(&mut run.path); + run.end = p.end(); + } + } + + /// Move the pen to `target` (plotter units), drawing when it is down. + fn line_to(&mut self, target: Point) { + if !(target.x.is_finite() && target.y.is_finite()) { + return; + } + let (a, b) = (self.dev(self.pos), self.dev(target)); + let down = self.down; + self.trace(a, &[Piece::Line(b)], down); + self.pos = target; + } + + /// The curves of an arc around `center` (user units) from `start` through `sweep` degrees, + /// where the art lies, and its end (user units). `None` when it has no radius or sweep. + fn arc(&self, center: Point, start: Point, sweep: f64) -> Option<(Vec, Point)> { + let r = (start - center).hypot(); + let sweep = sweep.clamp(-32768.0, 32767.0).to_radians(); + if !(r > 0.0 && r.is_finite() && sweep != 0.0 && sweep.is_finite()) { + return None; + } + let a0 = (start - center).atan2(); + let arc = kurbo::Arc { center, radii: Vec2::new(r, r), start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; + let m = self.user_dev(); + let pieces = arc + .append_iter(r * 1e-6) + .filter_map(|el| match el { + PathEl::CurveTo(a, b, c) => Some(Piece::Curve(m * a, m * b, m * c)), + PathEl::LineTo(p) => Some(Piece::Line(m * p)), + _ => None, + }) + .collect(); + Some((pieces, center + Vec2::from_angle(a0 + sweep) * r)) + } + + /// An arc from the pen around `center` (user units), drawn with the pen as it is. + fn arc_from_pen(&mut self, center: Point, sweep: f64) { + let start = self.pos_user(); + match self.arc(center, start, sweep) { + Some((pieces, end)) => { + let (a, down) = (self.dev(self.pos), self.down); + self.trace(a, &pieces, down); + self.pos = self.user * end; + } + None => { + let at = self.dev(self.pos); + let down = self.down; + self.trace(at, &[Piece::Line(at)], down); + } + } + } + + /// A closed outline through `pieces` from `a` (where the art lies). + fn outline(a: Point, pieces: &[Piece]) -> BezPath { + let mut path = BezPath::new(); + path.move_to(a); + pieces.iter().for_each(|p| p.push(&mut path)); + path.close_path(); + path + } + + /// A circle of `radius` (current units) around the pen, starting at 0 degrees (180 for a + /// negative radius), where the art lies. + fn circle(&self, radius: f64) -> Option { + let c = self.pos_user(); + let start = c + Vec2::new(radius, 0.0); + let (pieces, _) = self.arc(c, start, 360.0)?; + Some(Self::outline(self.user_dev() * start, &pieces)) + } + + /// A wedge of `radius` (current units) around the pen, from `start` through `sweep` degrees. + fn wedge(&self, radius: f64, start: f64, sweep: f64) -> Option { + let c = self.pos_user(); + let reference = if radius < 0.0 { 180.0 } else { 0.0 }; + let sweep = sweep.clamp(-360.0, 360.0); + let first = c + Vec2::from_angle((reference + start.clamp(-32768.0, 32767.0) % 360.0).to_radians()) * radius.abs(); + let m = self.user_dev(); + if sweep.abs() >= 360.0 { + let (pieces, _) = self.arc(c, first, sweep)?; + return Some(Self::outline(m * first, &pieces)); + } + let mut pieces = vec![Piece::Line(m * first)]; + if let Some((arc, _)) = self.arc(c, first, sweep) { + pieces.extend(arc); + } + (radius != 0.0).then(|| Self::outline(m * c, &pieces)) + } + + /// The rectangle from the pen to `corner` (plotter units), where the art lies. + fn rect(&self, corner: Point) -> BezPath { + let (a, b) = (self.pos_user(), self.user.inverse() * corner); + let m = self.user_dev(); + let pieces = [Point::new(b.x, a.y), b, Point::new(a.x, b.y)].map(|p| Piece::Line(m * p)); + Self::outline(m * a, &pieces) + } + + /// `path` as the polygon buffer, filled (`fill`) or edged. + fn buffer_and_draw(&mut self, path: Option, fill: bool) { + self.flush(); + if self.poly.is_some() { + return; + } + let Some(path) = path else { + return self.dot(self.dev(self.pos)); + }; + if !self.spend(path.elements().len()) { + return; + } + let mut poly = Poly::default(); + poly.closed(&path); + self.buffer = Some(poly); + if fill { self.fill_polygon(FillRule::EvenOdd) } else { self.edge_polygon() } + } + + /// FP: the polygon buffer filled (each fill is a copy of the buffer, counted against the + /// budget). + fn fill_polygon(&mut self, rule: FillRule) { + self.flush(); + let n = self.buffer.as_ref().map_or(0, |b| b.fill.elements().len()); + if n == 0 || !self.spend(n) { + return; + } + let Some(c) = self.fill_color() else { return }; + let Some(path) = self.buffer.as_ref().map(|b| b.fill.clone()) else { return }; + self.push(Shape { path, fill: Some((c, rule)), stroke: None }); + } + + /// EP: the pen-down edges of the polygon buffer stroked (counted as FP's are). + fn edge_polygon(&mut self) { + self.flush(); + let n = self.buffer.as_ref().map_or(0, |b| b.edge.elements().len()); + if n == 0 || !self.spend(n) { + return; + } + let Some(stroke) = self.stroke() else { return }; + let Some(path) = self.buffer.as_ref().map(|b| b.edge.clone()) else { return }; + self.push(Shape { path, fill: None, stroke: Some(stroke) }); + } + + // ---------- instructions ---------- + + /// Read and play the instruction `op`. + pub fn op(&mut self, op: [u8; 2], lex: &mut Lexer) { + if self.poly.is_some() && !POLYGON_MODE.contains(&op) { + return self.skip_op(op, lex); + } + match &op { + b"IN" | b"BP" | b"DF" | b"PU" | b"PD" | b"PA" | b"PR" | b"SP" => self.setup_op(op, lex), + b"PW" | b"WU" | b"NP" | b"PC" | b"CR" => self.pen_op(op, lex), + b"LT" | b"UL" => self.line_type_op(op, lex), + b"LA" | b"FT" | b"SC" => self.attribute_op(op, lex), + b"IP" | b"IR" | b"RO" | b"CI" => self.frame_op(op, lex), + b"AA" | b"AR" | b"AT" | b"RT" | b"BZ" | b"BR" => self.curve_op(op, lex), + b"EA" | b"ER" | b"RA" | b"RR" | b"EW" | b"WG" | b"PM" | b"FP" | b"EP" | b"PE" => self.area_op(op, lex), + _ => self.other_op(op, lex), + } + } + + /// An instruction polygon mode ignores: its parameters (or text) are read. + fn skip_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + match &op { + b"LB" | b"BL" | b"WD" => lex.label(self.terminator), + b"DT" => { + lex.char(); + lex.params(); + } + b"SM" => { + lex.char(); + } + _ => lex.params(), + } + } + + /// Initialization, pen moves and pen selection. + fn setup_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"IN" | b"BP" => { + lex.params(); + self.init(); + } + b"DF" => { + lex.params(); + self.defaults(); + } + b"PU" | b"PD" => { + self.down = op[1] == b'D'; + self.points(lex); + } + b"PA" | b"PR" => { + self.relative = op[1] == b'R'; + self.points(lex); + } + b"SP" => { + let n = lex.numbers(&mut v); + self.flush(); + self.pen = Some(if n == 0 { 0 } else { v[0].round().clamp(-1.0, 1e9) as i64 }); + } + _ => {} + } + } + + /// Pen widths, the palette and its colors. + fn pen_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"PW" => { + let n = lex.numbers(&mut v); + self.flush(); + let width = |s: &Self, w: f64| if s.relative_widths { w / 100.0 * s.diagonal() } else { w * PLU_PER_MM }; + let default = if self.relative_widths { 0.1 } else { DEFAULT_WIDTH_MM }; + let w = width(self, if n == 0 { default } else { v[0].clamp(0.0, 32767.0) }); + if n >= 2 { + let pen = v[1].round().clamp(0.0, 1e9) as i64; + if pen > 0 && pen < self.pens.max(8) { + self.widths.insert(pen, w); + } + } else { + self.width = w; + self.widths.clear(); + } + } + b"WU" => { + let n = lex.numbers(&mut v); + self.flush(); + self.relative_widths = n > 0 && v[0].round() == 1.0; + self.width = if self.relative_widths { 0.1 / 100.0 * self.diagonal() } else { DEFAULT_WIDTH_MM * PLU_PER_MM }; + self.widths.clear(); + } + b"NP" => { + let n = lex.numbers(&mut v); + self.flush(); + if n == 0 { + self.pens = 8; + } else if v[0] >= 2.0 { + self.pens = i64::from((v[0].min(MAX_PENS as f64).ceil() as u32).next_power_of_two()).min(MAX_PENS); + } + } + b"PC" => { + let n = lex.numbers(&mut v); + self.flush(); + let pen = v[0].round().clamp(0.0, 1e9) as i64; + match n { + 0 => self.colors.clear(), + 1 => { + self.colors.remove(&pen); + } + // Two or three parameters: the instruction is ignored. + 2 | 3 => {} + _ if pen < MAX_PENS => { + let channel = |i: usize| { + let (b, w) = self.ranges[i]; + let t = if w == b { 0.0 } else { ((v[i + 1] - b) / (w - b)).clamp(0.0, 1.0) }; + (t * 255.0).round() as u8 + }; + let c = [channel(0), channel(1), channel(2)]; + self.colors.insert(pen, c); + } + _ => {} + } + } + b"CR" => { + let n = lex.numbers(&mut v); + if n == 0 { + self.ranges = [(0.0, 255.0); 3]; + } else if n >= 6 { + self.ranges = [(v[0], v[1]), (v[2], v[3]), (v[4], v[5])]; + } + } + _ => {} + } + } + + /// Line types and their patterns. + fn line_type_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"LT" => { + let n = lex.numbers(&mut v); + self.flush(); + if n == 0 { + if self.line_type.is_some() { + self.saved_line_type = self.line_type; + } + self.line_type = None; + return; + } + let k = v[0].round().clamp(-100.0, 100.0) as i32; + if k == 99 { + if self.line_type.is_none() { + self.line_type = self.saved_line_type; + } + return; + } + if !(-8..=8).contains(&k) { + return; + } + // A pattern length of 0 or less, or a mode other than 0 and 1, makes the instruction ignored. + if (n >= 2 && !(v[1] > 0.0 && v[1] <= 32767.0)) || (n >= 3 && !matches!(v[2].round() as i32, 0 | 1)) { + return; + } + self.line_type = Some(k); + if n >= 2 { + self.pattern = v[1]; + } + if n >= 3 { + self.pattern_mm = v[2].round() == 1.0; + } + } + b"UL" => { + let mut gaps = [0.0f64; 21]; + let n = lex.numbers(&mut gaps); + self.flush(); + let index = gaps[0].round().abs(); + if n == 0 { + self.user_types = Default::default(); + } else if (1.0..=8.0).contains(&index) { + let slot = index as usize - 1; + let values = &gaps[1..n]; + let sum: f64 = values.iter().sum(); + self.user_types[slot] = if n == 1 { + None + } else if values.iter().all(|g| *g >= 0.0) && sum > 0.0 { + Some(values.iter().map(|g| g / sum * 100.0).collect()) + } else { + return; + }; + } + } + _ => {} + } + } + + /// Line ends and joins, the fill type and scaling. + fn attribute_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"LA" => { + let n = lex.numbers(&mut v[..6]); + self.flush(); + if n == 0 { + (self.cap, self.join, self.miter) = (LineCap::Butt, LineJoin::Miter, 5.0); + } + for pair in v[..n - n % 2].chunks(2) { + let value = pair[1].round() as i32; + match (pair[0].round() as i32, value) { + (1, 1) => self.cap = LineCap::Butt, + (1, 2) => self.cap = LineCap::Square, + (1, 3 | 4) => self.cap = LineCap::Round, + (2, 1 | 2) => self.join = LineJoin::Miter, + (2, 4) => self.join = LineJoin::Round, + (2, 3 | 5 | 6) => self.join = LineJoin::Bevel, + (3, _) => self.miter = pair[1].clamp(1.0, 32767.0), + _ => {} + } + } + } + b"FT" => { + let n = lex.numbers(&mut v[..3]); + let kind = if n == 0 { 1 } else { v[0].round() as i32 }; + self.fill = match kind { + 1 | 2 => FillKind::Solid, + 10 => FillKind::Shade(if n >= 2 { v[1] } else { 100.0 }), + 3 | 4 | 11 | 21 | 22 => FillKind::Pattern, + _ => self.fill, + }; + } + b"SC" => { + let n = lex.numbers(&mut v[..7]); + self.flush(); + let kind = if n >= 5 { v[4].round() as i32 } else { 0 }; + self.scaling = match (n, kind) { + (0, _) => None, + (5, 2) if v[1] != 0.0 && v[3] != 0.0 => Some(Scaling::Factor { x0: v[0], fx: v[1], y0: v[2], fy: v[3] }), + (4..=7, 0 | 1) if v[0] != v[1] && v[2] != v[3] => { + let iso = (kind == 1).then(|| if n >= 7 { (v[5].clamp(0.0, 100.0), v[6].clamp(0.0, 100.0)) } else { (50.0, 50.0) }); + Some(Scaling::Fit { x0: v[0], x1: v[1], y0: v[2], y1: v[3], iso }) + } + _ => return, + }; + self.update_user(); + } + _ => {} + } + } + + /// The scaling points, the rotation and circles. + fn frame_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"IP" | b"IR" => { + let n = lex.numbers(&mut v[..4]); + self.flush(); + // IR's percentages and the defaults are of the hard-clip limits in the current + // orientation. Scaling points past the art's range are held at its edge, so lengths + // taken from them stay finite. + let clip = self.hard_clip(); + let at = |x: f64, y: f64| { + let p = if op[1] == b'R' { Point::new(x / 100.0 * clip.x, y / 100.0 * clip.y) } else { Point::new(x, y) }; + Point::new(p.x.clamp(-LIMIT, LIMIT), p.y.clamp(-LIMIT, LIMIT)) + }; + match n { + 0 => (self.p1, self.p2) = (Point::ZERO, clip), + 2 | 3 => { + let p1 = at(v[0], v[1]); + (self.p1, self.p2) = (p1, p1 + (self.p2 - self.p1)); + } + 4 => { + let (p1, mut p2) = (at(v[0], v[1]), at(v[2], v[3])); + // A coordinate of P2 equal to P1's is one plotter unit more. + if p2.x == p1.x { + p2.x += 1.0; + } + if p2.y == p1.y { + p2.y += 1.0; + } + (self.p1, self.p2) = (p1, p2); + } + _ => {} + } + self.update_user(); + } + b"RO" => { + let n = lex.numbers(&mut v[..1]); + self.flush(); + let angle = if n == 0 { 0.0 } else { v[0].round().rem_euclid(360.0) }; + if [0.0, 90.0, 180.0, 270.0].contains(&angle) { + let ro = angle as u16; + let rot = Self::rotation(ro); + // The pen keeps its place on the page, its coordinates changing with the axes; + // P1 and P2 keep their coordinates, and the polygon buffer turns with the axes. + let turn = rot * self.rot.inverse(); + self.pos = rot.inverse() * (self.rot * self.pos); + if let Some(b) = &mut self.buffer { + b.fill.apply_affine(turn); + b.edge.apply_affine(turn); + } + (self.rot, self.ro) = (rot, ro); + } + } + b"CI" => { + let n = lex.numbers(&mut v[..2]); + if n == 0 { + return; + } + let path = self.circle(v[0]); + // In polygon mode the circle is a subpolygon of its own; the pen stays at its + // center. + if self.poly.is_some() { + if let Some(path) = path + && self.spend(path.elements().len()) + && let Some(poly) = &mut self.poly + { + poly.closed(&path); + } + return; + } + self.flush(); + // Line type 0 draws a dot at the center. + if self.line_type == Some(0) { + return self.dot(self.dev(self.pos)); + } + let Some(path) = path else { return self.dot(self.dev(self.pos)) }; + if self.spend(path.elements().len()) + && let Some(stroke) = self.stroke() + { + self.push(Shape { path, fill: None, stroke: Some(stroke) }); + } + } + _ => {} + } + } + + /// Arcs and Bézier curves from the pen. + fn curve_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"AA" | b"AR" => { + if lex.numbers(&mut v[..4]) < 3 { + return; + } + let center = if op[1] == b'R' { self.pos_user() + Vec2::new(v[0], v[1]) } else { Point::new(v[0], v[1]) }; + self.arc_from_pen(center, v[2]); + } + b"AT" | b"RT" => { + if lex.numbers(&mut v[..5]) < 4 { + return; + } + let a = self.pos_user(); + let off = if op[0] == b'R' { a.to_vec2() } else { Vec2::ZERO }; + let (b, c) = (Point::new(v[0], v[1]) + off, Point::new(v[2], v[3]) + off); + self.three_point_arc(a, b, c); + } + b"BZ" | b"BR" => { + while let Some(x) = lex.number() { + let mut p = [x, 0.0, 0.0, 0.0, 0.0, 0.0]; + for slot in &mut p[1..] { + let Some(n) = lex.number() else { return }; + *slot = n; + } + let a = self.pos_user(); + let off = if op[1] == b'R' { a.to_vec2() } else { Vec2::ZERO }; + let [c1, c2, end] = [0, 2, 4].map(|i| Point::new(p[i], p[i + 1]) + off); + let m = self.user_dev(); + let (from, down) = (self.dev(self.pos), self.down); + self.trace(from, &[Piece::Curve(m * c1, m * c2, m * end)], down); + self.pos = self.user * end; + } + } + _ => {} + } + } + + /// Rectangles, wedges, polygon mode and encoded polylines. + fn area_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 8]; + match &op { + b"EA" | b"ER" | b"RA" | b"RR" => { + if lex.numbers(&mut v[..2]) < 2 { + return; + } + let corner = if op[1] == b'R' { self.pos + self.delta(v[0], v[1]) } else { self.to_plu(v[0], v[1]) }; + let path = self.rect(corner); + self.buffer_and_draw(Some(path), op[0] == b'R'); + } + b"EW" | b"WG" => { + if lex.numbers(&mut v[..4]) < 3 { + return; + } + let path = self.wedge(v[0], v[1], v[2]); + self.buffer_and_draw(path, op[0] == b'W'); + } + b"PM" => { + let n = lex.numbers(&mut v[..1]); + self.flush(); + // The point that closes a subpolygon moves the pen there: PM1 closes it with the + // pen up, PM2 with the pen as it is. + let mut closure = None; + match if n == 0 { 0 } else { v[0].round() as i32 } { + 0 if self.poly.is_none() => { + let at = self.dev(self.pos); + self.poly = Some(Poly { start: at, last: at, ..Poly::default() }); + self.buffer = None; + } + 1 => { + if let Some(p) = &mut self.poly { + closure = p.close(false); + p.fresh = true; + } + } + 2 => { + if let Some(mut p) = self.poly.take() { + closure = p.close(self.down); + self.buffer = Some(p); + } + } + _ => {} + } + if let Some(at) = closure { + self.pos = self.rot.inverse() * at; + } + } + b"FP" => { + let n = lex.numbers(&mut v[..1]); + self.fill_polygon(if n > 0 && v[0].round() == 1.0 { FillRule::NonZero } else { FillRule::EvenOdd }); + } + b"EP" => { + lex.params(); + self.edge_polygon(); + } + b"PE" => self.polyline_encoded(lex), + _ => {} + } + } + + /// Labels, comments, pages, the input window, and instructions that draw nothing. + fn other_op(&mut self, op: [u8; 2], lex: &mut Lexer) { + let mut v = [0.0f64; 4]; + match &op { + b"LB" | b"BL" | b"WD" => { + lex.label(self.terminator); + self.warn(LABELS); + } + b"DT" => { + self.terminator = lex.char().unwrap_or(ETX); + lex.params(); + } + b"SM" => { + // The symbol character is read so it isn't taken for an instruction; symbols + // aren't drawn. + if lex.char().is_some() { + self.warn(SYMBOLS); + } + } + b"CO" => { + lex.quoted(); + } + b"PG" | b"FR" => { + lex.params(); + self.flush(); + self.page_end.get_or_insert(self.shapes.len()); + // The next page starts with the pen up at the origin (FR also empties the + // polygon buffer). + (self.pos, self.down) = (Point::ZERO, false); + if op[0] == b'F' { + self.buffer = None; + } + } + b"IW" => { + if lex.numbers(&mut v) == 4 { + self.warn(WINDOW); + } + } + _ if super::IGNORED.contains(&op) => lex.params(), + _ => { + lex.params(); + self.unknown += 1; + } + } + } + + /// The coordinate pairs of PU, PD, PA and PR, plotted in the current mode. + fn points(&mut self, lex: &mut Lexer) { + while let Some(x) = lex.number() { + let Some(y) = lex.number() else { return }; + let target = if self.relative { self.pos + self.delta(x, y) } else { self.to_plu(x, y) }; + self.line_to(target); + if self.full { + return; + } + } + } + + /// AT and RT: the arc from `a` through `b` to `c` (user units). + fn three_point_arc(&mut self, a: Point, b: Point, c: Point) { + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let center = if a == c { + // Back to the start: the circle whose diameter ends at the start and the middle point. + Some(a.midpoint(b)) + } else if d.abs() > 1e-12 * (b - a).hypot2().max((c - a).hypot2()).max(1.0) { + let (a2, b2, c2) = (a.to_vec2().hypot2(), b.to_vec2().hypot2(), c.to_vec2().hypot2()); + Some(Point::new( + (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, + (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d, + )) + } else { + None + }; + let Some(center) = center.filter(|p| p.x.is_finite() && p.y.is_finite()) else { + // Points in a line: a line to the end. + return self.line_to(self.user * c); + }; + let tau = std::f64::consts::TAU; + let angle = |p: Point| (p - center).atan2(); + let sweep = if a == c { + tau + } else { + let (s, t) = ((angle(c) - angle(a)).rem_euclid(tau), (angle(b) - angle(a)).rem_euclid(tau)); + if t < s { s } else { s - tau } + }; + self.arc_from_pen(center, sweep.to_degrees()); + if a != c { + self.pos = self.user * c; + } + } + + /// PE: encoded pen moves, pen selections and rectangles. + fn polyline_encoded(&mut self, lex: &mut Lexer) { + let mut st = Pe::default(); + let (mut rect, mut corner) = (false, false); + while let Some(item) = lex.pe(&mut st) { + if self.full { + continue; + } + match item { + PeItem::Pen(n) => { + if self.poly.is_none() { + self.flush(); + self.pen = Some(n.clamp(-1, 1_000_000_000)); + } + } + PeItem::Rect => (rect, corner) = (true, false), + PeItem::Point { x, y, up, absolute } => { + if up { + rect = false; + } + let target = if absolute { self.to_plu(x, y) } else { self.pos + self.delta(x, y) }; + if rect && corner { + // The second pair of a rectangle: its opposite corner, relative. It is filled + // as RR fills one, so polygon mode, which doesn't allow RR, ignores it. + let path = self.rect(self.pos + self.delta(x, y)); + self.buffer_and_draw(Some(path), true); + corner = false; + } else if rect { + self.down = false; + self.line_to(target); + corner = true; + } else { + self.down = !up; + self.line_to(target); + } + } + } + } + if rect { + self.down = false; + } + } + + /// The plot's end: the last line drawn, and notes on what wasn't read. + pub fn finish(mut self, raster: bool) -> Self { + self.flush(); + if let Some(n) = self.page_end + && self.shapes.len() > n + { + self.warn(PAGES); + } + if raster { + self.warn(RASTER); + } + if self.unknown > 0 { + let n = self.unknown; + self.warnings.push(format!( + "{n} instruction{} of kinds VectorCraft doesn't read {} skipped", + if n == 1 { "" } else { "s" }, + if n == 1 { "was" } else { "were" } + )); + } + self + } +} diff --git a/crates/cad/src/hpgl/tests.rs b/crates/cad/src/hpgl/tests.rs new file mode 100644 index 0000000000..9a350707a6 --- /dev/null +++ b/crates/cad/src/hpgl/tests.rs @@ -0,0 +1,630 @@ +//! HP-GL import: units and the y axis, pens, runs, curves, filled and edged areas, polygon mode, +//! line types, scaling, rotation, encoded polylines, escapes around the instructions, what is +//! skipped with a warning, which files are taken to be HP-GL, and hostile files. + +use kurbo::{BezPath, PathEl, Point, Shape as _}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, LineCap, LineJoin, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::FillRule; + +use super::plot::{FAR_AWAY, HATCHES, LABELS, PAGES, RASTER, SYMBOLS, TOO_MANY_POINTS, WINDOW}; +use super::*; + +/// Points per millimeter. +const MM: f64 = 72.0 / 25.4; + +fn plot(s: &str) -> Imported { + plot_bytes(s.as_bytes()) +} + +fn plot_bytes(b: &[u8]) -> Imported { + match import(b) { + Ok(i) => i, + Err(e) => panic!("{e}: {:?}", String::from_utf8_lossy(b)), + } +} + +/// Every object, in paint order. +fn leaves(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| { + if n.children().is_none() { + out.push(n.clone()); + } + }); + out +} + +fn bez(n: &Node) -> BezPath { + match &n.kind { + NodeKind::Path { path, .. } => path.to_bezpath(), + k => panic!("a path, got {k:?}"), + } +} + +fn stroke(n: &Node) -> StrokeLayer { + n.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.clone()) } else { None }).expect("a stroke") +} + +fn fill(n: &Node) -> Option { + n.appearance.items.iter().find_map(|i| if let AppearanceItem::Fill(f) = i { Some(f.paint.clone()) } else { None }) +} + +fn rule(n: &Node) -> FillRule { + match &n.kind { + NodeKind::Path { rule, .. } => *rule, + k => panic!("a path, got {k:?}"), + } +} + +fn rgb(r: u8, g: u8, b: u8) -> Paint { + Paint::solid(Color::rgb8(r, g, b)) +} + +/// The end points of `bp`'s elements. +fn ends(bp: &BezPath) -> Vec { + bp.elements().iter().filter_map(|e| e.end_point()).collect() +} + +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-6 +} + +fn assert_points(got: &[Point], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!(near(*g, Point::new(w.0, w.1)), "{got:?} != {want:?}"); + } +} + +/// A PE number as the reference guide's encoding writes it (base 64, or base 32 for 7-bit data). +fn pe_number(v: i64, seven_bit: bool) -> Vec { + let mut n = if v >= 0 { 2 * v as u64 } else { 2 * v.unsigned_abs() + 1 }; + let (base, high) = if seven_bit { (32, 95) } else { (64, 191) }; + let mut out = vec![]; + while n >= base { + out.push(63 + (n % base) as u8); + n /= base; + } + out.push(high + n as u8); + out +} + +#[test] +fn plotter_units_become_points_with_y_down() { + // An inch right and an inch up, with the thinnest pen (0.25 pt): the artboard reaches 0.125 pt + // past the line at the corner's miter, and stops at the line's butt ends. + let i = plot("IN;SP1;PW0;PU0,0;PD1016,0,1016,1016;PU;"); + let doc = &i.document; + let r = doc.artboards[0].rect; + assert!((r.width() - 72.125).abs() < 1e-9 && (r.height() - 72.125).abs() < 1e-9, "{r:?}"); + let shapes = leaves(doc); + assert_eq!(shapes.len(), 1); + assert_points(&ends(&bez(&shapes[0])), &[(0.0, 72.0), (72.0, 72.0), (72.0, 0.0)]); + let s = stroke(&shapes[0]); + assert_eq!((s.width, s.paint.clone(), s.cap, s.join, s.miter_limit), (0.25, rgb(0, 0, 0), LineCap::Butt, LineJoin::Miter, 5.0)); + assert!(fill(&shapes[0]).is_none() && i.warnings.is_empty(), "{:?}", i.warnings); + + // The artboard holds what the strokes paint, the tip of a sharp miter join included. + let i = plot("IN;SP1;PW2;PD2032,0,0,1000;"); + let r = i.document.artboards[0].rect; + let painted = leaves(&i.document)[0].visual_bounds().unwrap(); + let path = bez(&leaves(&i.document)[0]).bounding_box(); + assert!(painted.x1 - path.x1 > 2.0 * MM, "the miter reaches past half the width: {painted:?} {path:?}"); + let inside = r.x0 <= painted.x0 + 1e-9 && r.y0 <= painted.y0 + 1e-9 && r.x1 >= painted.x1 - 1e-9 && r.y1 >= painted.y1 - 1e-9; + assert!(inside, "{r:?} {painted:?}"); +} + +#[test] +fn pens_pick_colors_and_widths() { + // Before any SP the pen is pen 1; SP0 draws nothing; pens past the palette wrap round it. + let i = plot("IN;PD0,0,100,0;PU;SP2;PD0,100,100,100;PU;SP0;PD0,200,100,200;PU;SP9;PD0,300,100,300;PU;SP3;PD0,400,100,400;PU;"); + let colors: Vec = leaves(&i.document).iter().map(|n| stroke(n).paint).collect(); + assert_eq!(colors, [rgb(0, 0, 0), rgb(255, 0, 0), rgb(255, 0, 0), rgb(0, 255, 0)]); + + // PC gives a pen a color in the color range; PC with the pen alone gives back its default. + let i = plot("IN;CR0,1,0,1,0,1;PC3,0,0,1;SP3;PD0,0,10,0;PU;PC3;PD0,10,10,10;PU;"); + let colors: Vec = leaves(&i.document).iter().map(|n| stroke(n).paint).collect(); + assert_eq!(colors, [rgb(0, 0, 255), rgb(0, 255, 0)]); + + // PW in millimeters for every pen, or for one; IN gives back 0.35 mm. + let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;"); + let widths: Vec = leaves(&i.document).iter().map(|n| stroke(n).width).collect(); + let want = [MM, 2.0 * MM, MM, 0.35 * MM]; + assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); +} + +#[test] +fn each_run_with_the_pen_down_is_one_path() { + // Relative moves; a run that comes back to its start is closed; a pen-up move elsewhere starts + // another path, and one back to where the line ended continues it. + let i = plot("IN;SP1;PW0;PA0,0;PR;PD1016,0,0,1016,-1016,0,0,-1016;PU2032,0;PD0,1016;PU0,1016;PU0,-1016;PD508,0;PU0,500;PD0,500;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 3, "{shapes:#?}"); + let NodeKind::Path { path: square, .. } = &shapes[0].kind else { panic!("a path") }; + assert_eq!((square.subpaths.len(), square.subpaths[0].anchors.len(), square.subpaths[0].closed), (1, 4, true)); + assert_eq!(ends(&bez(&shapes[1])).len(), 3, "the run went on from where it ended"); + assert_eq!(ends(&bez(&shapes[2])).len(), 2); + + // A pen-down move of no length draws a dot. + let i = plot("IN;SP1;PA500,500;PD;PA500,500;PU;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 1); + let b = bez(&shapes[0]).bounding_box(); + assert!((b.width() - 72.0 / 1016.0).abs() < 1e-9, "{b:?}"); +} + +#[test] +fn circles_arcs_and_curves_are_drawn_as_curves() { + // A circle of an inch round the pen, which stays at its center (the next line starts there). + let i = plot("IN;SP1;PW0;PA2032,2032;CI1016;PD3048,2032;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 2); + let c = bez(&shapes[0]); + assert!(c.elements().iter().any(|e| matches!(e, PathEl::CurveTo(..))) && matches!(c.elements().last(), Some(PathEl::ClosePath))); + // The curves stay within a thousandth of a point of the circle. + let b = c.bounding_box(); + assert!((b.width() - 144.0).abs() < 1e-3 && (b.height() - 144.0).abs() < 1e-3, "{b:?}"); + let line = ends(&bez(&shapes[1])); + assert!((line[0] - b.center()).hypot() < 1e-3, "{line:?} {b:?}"); + + // AA: a quarter turn counterclockwise round (0, 0) from (1016, 0) ends at (0, 1016), and the + // pen goes on from there. AR takes its center relative to the pen. + for s in ["IN;SP1;PW0;PA1016,0;PD;AA0,0,90;PA0,2032;", "IN;SP1;PW0;PA1016,0;PD;AR-1016,0,90;PA0,2032;"] { + let shapes = leaves(&plot(s).document); + assert_eq!(shapes.len(), 1, "{s}"); + let p = bez(&shapes[0]); + let pts = ends(&p); + // y down: (1016, 0) is at the bottom right, the arc's end on the left a quarter turn up. + let (start, end) = (pts[0], pts[pts.len() - 2]); + assert!(near(start, Point::new(72.125, 144.0)) && near(end, Point::new(0.125, 72.0)), "{s}: {pts:?}"); + assert!(near(*pts.last().unwrap(), Point::new(0.125, 0.0)), "{s}: {pts:?}"); + } + + // AT: the arc from the pen through a point to an end; points in a line give a line. + let shapes = leaves(&plot("IN;SP1;PW0;PA1016,0;PD;AT0,1016,-1016,0;").document); + let pts = ends(&bez(&shapes[0])); + let b = bez(&shapes[0]).bounding_box(); + assert!((b.width() - 144.0).abs() < 1e-6 && (b.height() - 72.0).abs() < 1e-6, "a half circle: {b:?}"); + assert!(near(pts[0], Point::new(144.125, 72.125)) && near(*pts.last().unwrap(), Point::new(0.125, 72.125)), "{pts:?}"); + let shapes = leaves(&plot("IN;SP1;PW0;PA0,0;PD;AT508,0,1016,0;").document); + assert_eq!(ends(&bez(&shapes[0])).len(), 2); + + // BZ and BR: cubic Béziers, BR's points relative to each curve's start. + for s in [ + "IN;SP1;PW0;PA0,0;PD;BZ0,1016,1016,1016,1016,0,1016,-1016,2032,-1016,2032,0;", + "IN;SP1;PW0;PA0,0;PD;BR0,1016,1016,1016,1016,0,0,-1016,1016,-1016,1016,0;", + ] { + let shapes = leaves(&plot(s).document); + let els = bez(&shapes[0]).elements().to_vec(); + assert_eq!(els.iter().filter(|e| matches!(e, PathEl::CurveTo(..))).count(), 2, "{s}"); + // The curves reach 762 plotter units (three quarters of their control points) up and down. + assert!(near(els.last().and_then(PathEl::end_point).unwrap(), Point::new(144.125, 54.125)), "{s}: {els:?}"); + } +} + +#[test] +fn rectangles_wedges_and_polygons_fill_and_edge() { + // RA fills, EA edges; neither moves the pen. + let i = plot("IN;SP2;PW0;PA0,0;RA1016,1016;EA1016,1016;PD508,0;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 3); + assert_eq!((fill(&shapes[0]), shapes[0].appearance.items.len()), (Some(rgb(255, 0, 0)), 1)); + assert!(fill(&shapes[1]).is_none() && stroke(&shapes[1]).paint == rgb(255, 0, 0)); + assert!(near(ends(&bez(&shapes[2]))[0], Point::new(0.125, 72.125)), "the line starts where the pen was"); + + // WG fills a wedge, EW edges one; a whole turn is a circle. + let i = plot("IN;SP1;PA0,0;WG1016,0,90;EW1016,0,360;"); + let shapes = leaves(&i.document); + let wedge = bez(&shapes[0]); + assert!(fill(&shapes[0]).is_some() && ends(&wedge).len() >= 3); + let ring = bez(&shapes[1]).bounding_box(); + assert!((ring.width() - 144.0).abs() < 1e-6); + + // Polygon mode: two squares, one inside the other; FP fills even-odd by default, FP1 + // non-zero; EP edges only what was drawn with the pen down. + let poly = "IN;SP1;PW0;PA0,0;PM0;PD3048,0,3048,3048,0,3048,0,0;PM1;PU1016,1016;PD2032,1016;PU2032,2032;PD1016,2032,1016,1016;PM2;"; + let i = plot(&format!("{poly}FP;FP1;EP;")); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 3); + assert_eq!((rule(&shapes[0]), rule(&shapes[1])), (FillRule::EvenOdd, FillRule::NonZero)); + let filled = bez(&shapes[0]); + assert_eq!(filled.elements().iter().filter(|e| matches!(e, PathEl::ClosePath)).count(), 2); + let edged = bez(&shapes[2]); + assert_eq!(edged.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(..))).count(), 3, "the pen-up side isn't edged: {edged:?}"); + // Nothing is drawn in polygon mode itself. + assert!(leaves(&plot(poly).document).is_empty()); + + // A circle in polygon mode is a subpolygon of its own; CI and RA after PM2 work as before. + let i = plot("IN;SP1;PA2032,2032;PM0;CI1016;PM2;FP;"); + assert_eq!(leaves(&i.document).len(), 1); + + // Fill types: shading mixes the pen with white; hatching fills solid with a warning. + let i = plot("IN;SP5;PA0,0;FT10,50;RA100,100;FT3,10,45;RA200,200;"); + let shapes = leaves(&i.document); + assert_eq!((fill(&shapes[0]), fill(&shapes[1])), (Some(rgb(128, 128, 255)), Some(rgb(0, 0, 255)))); + assert_eq!(i.warnings, [HATCHES]); +} + +#[test] +fn line_types_become_dash_patterns() { + // A 10 mm pattern of line type 2 is 5 mm on, 5 mm off. + let i = plot("IN;SP1;LT2,10,1;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + assert!(d.pattern.iter().all(|v| (v - 5.0 * MM).abs() < 1e-9) && d.pattern.len() == 2 && !d.align_corners, "{d:?}"); + // The default length is 4% of the P1-P2 diagonal; IP sets P1 and P2. + let i = plot("IN;IP0,0,3000,4000;SP1;LT3;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + let total = 200.0 * 72.0 / 1016.0; + assert!((d.pattern[0] - 0.7 * total).abs() < 1e-9 && (d.pattern[1] - 0.3 * total).abs() < 1e-9, "{d:?}"); + // Adaptive types stretch to each line; a zero length is a dot one plotter unit long. + let i = plot("IN;SP1;LT-4,10,1;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + assert!(d.align_corners && (d.pattern[2] - 72.0 / 1016.0).abs() < 1e-12, "{d:?}"); + // UL redefines a type; LT; draws solid and LT99 gives the type back. + let i = plot("IN;SP1;UL2,1,3;LT2,10,1;PD0,0,4000,0;PU;LT;PD0,100,4000,100;PU;LT99;PD0,200,4000,200;"); + let shapes = leaves(&i.document); + let d = stroke(&shapes[0]).dash.expect("dashed"); + assert!((d.pattern[0] - 2.5 * MM).abs() < 1e-9 && (d.pattern[1] - 7.5 * MM).abs() < 1e-9, "{d:?}"); + assert!(stroke(&shapes[1]).dash.is_none() && stroke(&shapes[2]).dash.is_some()); + // Line type 0 draws a dot at each point. + let i = plot("IN;SP1;LT0;PD0,0,1000,0,2000,0;"); + assert_eq!(leaves(&i.document).len(), 3); + // LA sets the caps, joins and miter limit. + let s = stroke(&leaves(&plot("IN;SP1;LA1,4,2,4,3,9;PD0,0,100,0;").document)[0]); + assert_eq!((s.cap, s.join, s.miter_limit), (LineCap::Round, LineJoin::Round, 9.0)); +} + +#[test] +fn scaling_maps_user_units_onto_p1_and_p2() { + // Anisotropic: 100 user units across an inch. + let size = |s: &str| { + let shapes = leaves(&plot(s).document); + bez(&shapes[0]).bounding_box().size() + }; + let s = size("IN;IP0,0,1016,2032;SC0,100,0,100;SP1;PD0,0,100,100;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 144.0).abs() < 1e-9, "{s:?}"); + // Isotropic: the smaller of the two scales on both axes. + let s = size("IN;IP0,0,1016,2032;SC0,100,0,100,1;SP1;PU0,0;PD100,100;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 72.0).abs() < 1e-9, "{s:?}"); + // Point factor: 10 plotter units per user unit. + let s = size("IN;SC0,10,0,10,2;SP1;PD0,0,101.6,50.8;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 36.0).abs() < 1e-9, "{s:?}"); + // Without IP, P2 lies 11 × 8.5 in from the origin. + let s = size("IN;SC0,11,0,8.5;SP1;PD0,0,1,1;"); + assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 72.0).abs() < 1e-9, "{s:?}"); + // SC; goes back to plotter units; scaling that makes no area is ignored. + let s = size("IN;SC0,1,0,1;SC;SC0,0,0,1;SP1;PD0,0,1016,1016;"); + assert!((s.width - 72.0).abs() < 1e-9, "{s:?}"); + // RO turns the coordinate system: x runs up. + let shapes = leaves(&plot("IN;RO90;SP1;PW0;PA0,0;PD1016,0;").document); + let b = bez(&shapes[0]).bounding_box(); + assert!(b.width() < 1e-9 && (b.height() - 72.0).abs() < 1e-9, "{b:?}"); +} + +#[test] +fn polyline_encoded_data_is_read() { + let mut f = b"IN;SP1;PW0;PE".to_vec(); + // Pen 2, a pen-up move to the absolute (1016, 0), then a relative line an inch up. + f.push(b':'); + f.extend(pe_number(2, false)); + f.extend(b"<="); + f.extend(pe_number(1016, false)); + f.extend(pe_number(0, false)); + f.extend(pe_number(0, false)); + f.extend(pe_number(1016, false)); + f.push(b';'); + let i = plot_bytes(&f); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 1); + assert_eq!(stroke(&shapes[0]).paint, rgb(255, 0, 0)); + assert_points(&ends(&bez(&shapes[0])), &[(0.125, 72.0), (0.125, 0.0)]); + + // 7-bit data with two fractional bits: 4064 / 4 = 1016. + let mut f = b"IN;SP1;PW0;PE7>".to_vec(); + f.extend(pe_number(2, true)); + f.extend(pe_number(-4064, true)); + f.extend(pe_number(0, true)); + f.push(b';'); + let b = bez(&leaves(&plot_bytes(&f).document)[0]).bounding_box(); + assert!((b.width() - 72.0).abs() < 1e-9, "{b:?}"); + + // Data that can't be decoded ends the instruction at its semicolon: none of it is read as + // instructions. + let shapes = leaves(&plot("IN;SP1;PE#PD5000,5000;PD1016,0;").document); + assert_eq!(shapes.len(), 1); + assert!((bez(&shapes[0]).bounding_box().width() - 72.0).abs() < 1e-9); + + // Rectangle mode: a pen-up move, then a filled rectangle relative to it. + let mut f = b"IN;SP3;PE9".to_vec(); + for v in [100, 100, 1016, 508] { + f.extend(pe_number(v, false)); + } + f.push(b';'); + let shapes = leaves(&plot_bytes(&f).document); + assert_eq!(fill(&shapes[0]), Some(rgb(0, 255, 0))); + let b = bez(&shapes[0]).bounding_box(); + assert!((b.width() - 72.0).abs() < 1e-9 && (b.height() - 36.0).abs() < 1e-9, "{b:?}"); +} + +#[test] +fn printer_escapes_and_job_lines_are_skipped() { + let mut f = b"\x1b%-12345X@PJL JOB\r\n@PJL ENTER LANGUAGE=PCL\r\n\x1bE\x1b%0BIN;SP1;PW0;PD0,0,1016,0;PU;\x1b%0A".to_vec(); + // An HP RTL raster image whose data spells out instructions. + f.extend(b"\x1b*r1A\x1b*b11WPD9999,9999\x1b*rC"); + f.extend(b"\x1b%1BPD1016,1016;\x1b%-12345X@PJL EOJ\r\n"); + assert!(is_hpgl(&f)); + let i = plot_bytes(&f); + let shapes = leaves(&i.document); + // The pen went up and came down where the line ended, so the line goes on. + assert_eq!(shapes.len(), 1, "{shapes:#?}"); + assert_eq!(ends(&bez(&shapes[0])).len(), 3); + assert_eq!(i.warnings, [RASTER], "{:?}", i.warnings); + let r = i.document.artboards[0].rect; + assert!((r.width() - 72.125).abs() < 1e-9 && (r.height() - 72.125).abs() < 1e-9, "{r:?}"); + + // The device-control escapes of older plotters. + let f = b"\x1b.(\x1b.I81;;17:\x1b.N;19:IN;SP1;PD0,0,1016,0;\x1b.)"; + assert!(is_hpgl(f)); + assert_eq!(leaves(&plot_bytes(f).document).len(), 1); +} + +#[test] +fn labels_comments_and_unknown_instructions_are_skipped() { + // A label's text, up to its terminator (ETX, or the one DT sets), isn't read as instructions. + let i = plot("IN;SP1;LBPD9999,9999\x03DT*,1;LBPU0,0;PD5000,5000*CO\"PD8000,8000\";PD1016,0;PU;ZZ1,2;QQ;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 1); + assert_eq!(i.warnings, [LABELS.to_string(), "2 instructions of kinds VectorCraft doesn't read were skipped".to_string()]); + // Symbol mode's symbols aren't drawn, with a warning; its lines are. + let i = plot("IN;SP1;SM*;PD100,0;SM;"); + assert_eq!((i.warnings.clone(), leaves(&i.document).len()), (vec![SYMBOLS.to_string()], 1)); + // Later pages and the input window are warned about. + let i = plot("IN;IW0,0,10,10;SP1;PD100,0;PU;PG;PD0,100;PG;"); + assert_eq!(i.warnings, [WINDOW, PAGES]); + // A page advance raises the pen at the origin: nothing joins the pages. + let i = plot("IN;SP1;PD100,0;PG;PA200,0;PD300,0;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 2); + assert_eq!(ends(&bez(&shapes[1])).len(), 2, "the second page's line starts at (200, 0)"); + // A page advance at the end changes nothing. + assert!(plot("IN;SP1;PD100,0;PG;").warnings.is_empty()); + // A file that draws nothing opens as a letter-size page. + let i = plot("IN;SP1;PU100,100;"); + assert!(leaves(&i.document).is_empty() && i.document.artboards[0].rect.size() == kurbo::Size::new(612.0, 792.0)); +} + +#[test] +fn only_plot_files_are_taken_for_hpgl() { + for f in [ + &b"IN;SP1;PU0,0;PD100,100;"[..], + b"in;sp1;pu0,0;pd100,100;", + b";IN;\r\nSP1;\r\nPA100,100;", + b"\x03IN;", + b"SP1PD0,0,10,10PU", + b"IN", + b"CO\"made by hand\";IN;", + b"IN;SP1;DT*;LBhello world*PA0,0;SMx;PA1,1;SM;", + b"IN;SP1;PE<=\xbf\xbf;PU;", + b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;SP1;", + ] { + assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + } + for f in [ + &b""[..], + b"IN THE BEGINNING", + b"set terminal png\nplot sin(x)\n", + b"Paris, 10 to 12", + b"SPDX-License-Identifier: MIT", + b"CONTENTS", + b"CO \"a comment\";hello world", + b"DT*;LBtext*nope", + b"\x89PNG\r\n\x1a\n", + b"IN;SP1;PD0,0;hello world", + b"\x1b%-12345X@PJL ENTER LANGUAGE=PCL\n\x1bE\x1b*r1A", + ] { + assert!(!is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f)); + } + // A comment needs no string; instructions of an older or a device's own set count when a + // semicolon ends them. + for f in [&b"CO;IN;SP1;PD0,0,10,10;"[..], b"IN;CO;SP1;PD0,0,10,10;", b"IN;SP1;VA;VS10;PU0,0;PD1016,0;", b"IN;GC5;SP1;PD0,0,10,0;"] { + assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + } + assert!(!is_hpgl(b"IN;GC5") && !is_hpgl(b"IN;Hello, world;")); + // A printer prolog of any length comes before the first instruction. + let long = [&b"\x1b%-12345X"[..], &b"@PJL COMMENT a job line of some length\r\n".repeat(400), b"\x1bE\x1b%0BIN;SP1;PD100,0;"].concat(); + assert!(long.len() > 16_000 && is_hpgl(&long)); + assert_eq!(leaves(&plot_bytes(&long).document).len(), 1); + // Instructions of any kind may follow the first eight, garbage included. + assert!(is_hpgl(b"IN;SP1;PU;PD;PU;PD;PU;PD;hello world")); +} + +/// A file read as HP-GL (picked by its extension) may start with any instruction the reader knows, +/// or one of another set that a semicolon ends; its content alone doesn't make it HP-GL. +#[test] +fn a_plot_file_may_start_with_any_instruction() { + for f in [&b"SI0.2,0.3;SP1;PA0,0;PD1016,0;"[..], b"DI1,0;SP1;PA0,0;PD1016,0;", b"GC5;SP1;PA0,0;PD1016,0;"] { + assert!(!is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + assert_eq!(leaves(&plot_bytes(f).document).len(), 1, "{:?}", String::from_utf8_lossy(f)); + } + for f in [&b"GC5"[..], b"SIhello world", b"set terminal png\n"] { + assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f)); + } + // Instructions of another set alone, however many or long, are not taken for HP-GL. + let long = [&b"GC"[..], "1".repeat(5000).as_bytes(), b";ZZ1;"].concat(); + for f in [&b"GC5;"[..], b"GC5;ZZ1;", b"GC5;ZZ1;YY2;XX3;WW4;VV5;UU6;TT7;", &long] { + assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f)); + } +} + +#[test] +fn escapes_that_carry_values_or_data_are_skipped_whole() { + // A reset leaves HP-GL until a language switch; symbol-set escapes carry a value and a letter. + for f in [ + &b"\x1bE\x1b(8U\x1b%1BIN;SP1;PD0,0,1016,0;"[..], + b"\x1bE\x1b(10U\x1b)0N\x1b%1BIN;SP1;PD0,0,1016,0;", + b"\x1bEHello\x1b%1BIN;SP1;PD0,0,1016,0;", + ] { + assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f)); + assert_eq!(leaves(&plot_bytes(f).document).len(), 1, "{:?}", String::from_utf8_lossy(f)); + } + // A letter left over from an escape doesn't join the next mnemonic. + let i = plot_bytes(b"IN;SP1;\x1b(8UPD0,0,1016,0;"); + assert!(i.warnings.is_empty() && leaves(&i.document).len() == 1, "{:?}", i.warnings); + // Raster data by plane and transparent print data are skipped by their byte counts, however + // they read. + let line = |data_escape: &[u8]| { + let data = b"\x1b%1BPD0,5000;"; + let mut f = b"IN;SP1;PW0;PD0,0,0,1016;\x1b%0A".to_vec(); + f.extend(data_escape); + f.extend(data.len().to_string().as_bytes()); + f.extend(if data_escape.ends_with(b"b") { &b"V"[..] } else { b"X" }); + f.extend(data); + f.extend(b"\x1b*rC\x1b%1BPD0,0;"); + bez(&leaves(&plot_bytes(&f).document)[0]).bounding_box() + }; + for escape in [&b"\x1b*r1A\x1b*b"[..], b"\x1b&p"] { + let b = line(escape); + assert!((b.height() - 72.0).abs() < 1e-9, "{:?}: {b:?}", String::from_utf8_lossy(escape)); + } +} + +#[test] +fn polygon_mode_follows_its_own_rules() { + // The point after a circle starts a new subpolygon: the triangle after it doesn't reach back + // to the circle's center, filled or edged. + let i = plot("IN;SP1;PW0;PA1000,1000;PM0;CI200;PD2000,1000,2000,2000,1000,2000;PM2;FP;EP;"); + let shapes = leaves(&i.document); + assert_eq!(shapes.len(), 2); + for s in &shapes { + let p = bez(s); + let first = p.elements().iter().position(|e| matches!(e, PathEl::ClosePath)).unwrap_or(p.elements().len()); + let circle = BezPath::from_vec(p.elements()[..first].to_vec()).bounding_box(); + let center = circle.center(); + assert!(ends(&p).iter().all(|e| !near(*e, center)), "{p:?}"); + } + // PM1 closes with the pen up: EP draws two sides of the triangle, not the third; PM2 closes + // with the pen as it is. + let sides = |s: &str| { + let p = bez(&leaves(&plot(s).document)[0]); + p.elements().iter().filter(|e| matches!(e, PathEl::LineTo(..))).count() + }; + assert_eq!(sides("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM1;PM2;EP;"), 2); + assert_eq!(sides("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM2;EP;"), 3); + // The closing point moves the pen: a relative move after PM1 starts from the start. + let i = plot("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM1;PU;PR0,2000;PD1000,0,0,1000;PM2;FP;"); + let b = bez(&leaves(&i.document)[0]).bounding_box(); + assert!((b.height() - 3000.0 * PT_PER_PLU).abs() < 1e-9, "{b:?}"); + // A subpolygon of fewer than three points (the closing point counted) is neither filled nor + // edged. + assert!(leaves(&plot("IN;SP1;PA0,0;PM0;PD0,0;PM2;FP;EP;").document).is_empty()); + let i = plot("IN;SP1;PA0,0;PM0;PR0,0;PM1;PA;PD1000,0,0,1000,0,0;PM2;FP;"); + let filled = bez(&leaves(&i.document)[0]); + assert_eq!(filled.elements().iter().filter(|e| matches!(e, PathEl::ClosePath)).count(), 1, "{filled:?}"); + // Polygon mode ignores the instructions it doesn't allow: pens, scaling and labels. + let i = plot("IN;SP1;PA0,0;PM0;SP2;SC0,1,0,1;LBPD9999,9999\x03PD1016,0,1016,1016;PM2;FP;"); + let shapes = leaves(&i.document); + assert_eq!((shapes.len(), fill(&shapes[0])), (1, Some(rgb(0, 0, 0)))); + assert!((bez(&shapes[0]).bounding_box().width() - 72.0).abs() < 1e-9 && i.warnings.is_empty(), "{:?}", i.warnings); +} + +#[test] +fn rotation_keeps_the_pen_and_turns_the_defaults() { + // After RO90, IP's default P2 is the rotated hard-clip corner: the user square spans 8.5 in + // across its rotated x axis and 11 in up it, which lie up and across the page. + let i = plot("IN;RO90;IP;SC0,100,0,100;SP1;PW0;PA0,0;PD100,0,100,100,0,100,0,0;"); + let b = bez(&leaves(&i.document)[0]).bounding_box(); + assert!((b.width() - 792.0).abs() < 1e-9 && (b.height() - 612.0).abs() < 1e-9, "{b:?}"); + // IR's percentages are of the rotated limits too. + let i = plot("IN;RO90;IR0,0,100,100;SC0,1,0,1;SP1;PW0;PA0,0;PD1,1;"); + let b = bez(&leaves(&i.document)[0]).bounding_box(); + assert!((b.width() - 792.0).abs() < 1e-9 && (b.height() - 612.0).abs() < 1e-9, "{b:?}"); + // The pen stays where it was on the page: a line after RO starts where the one before ended. + let i = plot("IN;SP1;PW0;PD0,0,1016,0;PU;RO90;PD;PR1016,0;"); + let all = leaves(&i.document).iter().map(|n| bez(n).bounding_box()).reduce(|a, b| a.union(b)).unwrap(); + assert!((all.width() - 72.0).abs() < 1e-9 && (all.height() - 72.0).abs() < 1e-9, "{all:?}"); +} + +#[test] +fn line_type_zero_and_odd_patterns_follow_the_reference() { + // Line type 0: one dot for an arc (at its end) and one for a circle (at its center). + for s in ["IN;SP1;LT0;PA0,0;PD;AA1016,0,180;", "IN;SP1;LT0;PA0,0;CI500;"] { + let shapes = leaves(&plot(s).document); + assert_eq!(shapes.len(), 1, "{s}"); + assert!(bez(&shapes[0]).bounding_box().width() < 0.1, "{s}"); + } + // An odd number of gaps repeats with the last pen-down stretch running into the first. + let i = plot("IN;SP1;UL3,50,25,25;LT3,10,1;PD0,0,4000,0;"); + let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed"); + assert!((d.pattern[0] - 7.5 * MM).abs() < 1e-9 && (d.pattern[1] - 2.5 * MM).abs() < 1e-9 && d.pattern.len() == 2, "{d:?}"); + assert!((d.offset - 2.5 * MM).abs() < 1e-9, "{d:?}"); + // One pen-down stretch is a solid line; a dot keeps the pattern's length. + let d = stroke(&leaves(&plot("IN;SP1;UL3,100;LT3,10,1;PD0,0,4000,0;").document)[0]).dash.expect("dashed"); + assert_eq!(d.pattern[1], 0.0); + let d = stroke(&leaves(&plot("IN;SP1;LT4,10,1;PD0,0,4000,0;").document)[0]).dash.expect("dashed"); + assert!((d.pattern.iter().sum::() - 10.0 * MM).abs() < 1e-9, "{d:?}"); +} + +#[test] +fn pen_colors_ignore_two_or_three_parameters() { + let i = plot("IN;PC3,0,0,255;PC3,255;PC3,255,0;SP3;PD0,0,10,0;"); + assert_eq!(stroke(&leaves(&i.document)[0]).paint, rgb(0, 0, 255)); +} + +#[test] +fn hostile_files_import_without_panics() { + let mut cases: Vec> = vec![ + // Coordinates past any plotter's range, and numbers with too many digits. + b"IN;SP1;PD99999999999999999999999999999,0;PU0,0;PD1016,1016;".to_vec(), + b"IN;SP1;PD0.000000000000000000000000001,1e999,--,++,..;".to_vec(), + // Unterminated labels, comments and encoded polylines. + b"IN;SP1;LBno end".to_vec(), + b"IN;CO\"no end".to_vec(), + b"IN;SP1;PE<=\xff\xff\xff\xfe\xfe".to_vec(), + b"IN;SP1;PE>\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\xfe\x40\xc0;".to_vec(), + // Arcs and wedges of every degenerate kind, with huge sweeps. + b"IN;SP1;PD;AA0,0,32767;AR0,0,90;AT0,0,0,0;RT1,1,2,2;CI0;CI-5;WG0,0,0;EW5,99999,-99999;WG-5,0,360;CI99999999999999;".to_vec(), + // Scaling onto one point, rotations the format doesn't define, huge palettes and pens. + b"IN;IP5,5,5,5;SC0,1,0,1,1;SP1;PD1,1;SC0,0,0,0,2;RO45;NP99999999;SP99999999999;PC99999999,1,2,3;PW99999,99999;PD2,2;".to_vec(), + // Polygon mode left open, PM1 and PM2 without PM0, FP and EP with nothing buffered. + b"IN;SP1;FP;EP;PM1;PM2;PM0;PD10,10;PM1;PM1;PM1;CI5;PE<\xc0\xc0;".to_vec(), + // Escapes cut short, and data lengths past the end. + b"\x1b%-12345X@PJL".to_vec(), + b"IN;SP1;PD0,0;\x1b*b99999999999W".to_vec(), + b"IN;\x1b".to_vec(), + b"IN;\x1b.".to_vec(), + ]; + // A job line with no end. + cases.push([&b"\x1b%-12345X@PJL "[..], &b"x".repeat(1 << 20)].concat()); + // Bytes of every value after a valid start. + cases.push([&b"IN;SP1;PD"[..], &(0..=255u8).collect::>()].concat()); + for f in &cases { + let r = std::panic::catch_unwind(|| import(f)); + assert!(r.is_ok(), "{:?}", String::from_utf8_lossy(f)); + } + let far = import(&cases[0]).unwrap(); + assert!(far.warnings.iter().any(|w| w == FAR_AWAY), "{:?}", far.warnings); + assert_eq!(leaves(&far.document).len(), 1, "the line in range is kept"); + + // Past the budget for path points, the rest is left out with a warning; pen-up moves, which + // make no path, don't count. + let many = format!("IN;SP1;PR;PD{}", "1,0,".repeat(300_000)); + let i = plot(&many); + assert!(i.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", i.warnings); + // Scaling points past any range give relative pen widths no wider than the widest pen. + let i = plot("IN;IP-99999999999999999999,0,99999999999999999999,0;WU1;PW32767;SP1;PD100,0;"); + let r = i.document.artboards[0].rect; + assert!(r.width().is_finite() && r.height() <= 16384.0 * 72.0 / 1016.0 + 1e-6, "{r:?}"); + assert!((stroke(&leaves(&i.document)[0]).width - 16384.0 * 72.0 / 1016.0).abs() < 1e-9); + + // Each fill of the polygon buffer is a copy of it, and counts. + let big = format!("IN;SP1;PM0;PR;PD{}PM2;{}", "1,1,".repeat(1000), "FP;EP;".repeat(1000)); + let i = plot(&big); + assert!(i.warnings.iter().any(|w| w == TOO_MANY_POINTS) && leaves(&i.document).len() < 400, "{:?}", i.warnings); + for pen in ["SP1;PU", "SP0;PD"] { + let moves = format!("IN;{pen}{};SP1;PU0,0;PD1016,0;", "1,0,".repeat(300_000)); + let i = plot(&moves); + assert!(i.warnings.is_empty() && leaves(&i.document).len() == 1, "{pen}: {:?}", i.warnings); + } +} diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs new file mode 100644 index 0000000000..3e20c69a98 --- /dev/null +++ b/crates/cad/src/hpgl/write.rs @@ -0,0 +1,1134 @@ +//! HP-GL export: the visible art over a region as pen moves, for pen plotters and cutters. +//! +//! Every visible path is drawn once along its own line: its fills and strokes are not painted, so +//! a filled shape is its closed outline (what a cutter cuts) and a stroke is its center line. Each +//! color is a pen: by default pen 1 is the first color the plot draws in, pen 2 the next new one, +//! and so on; with a pen table each path takes the pen whose color is nearest its own. The plots +//! of one export ([`export_regions`]) share the numbering. A path's color is its topmost visible +//! stroke's, else its topmost visible fill's (one at 0% opacity does not count); a gradient is the +//! average of its stops and a pattern its first visible solid fill (gray without one). Curves are +//! flattened to straight moves within a tolerance. Type is drawn as its glyph outlines, a gradient +//! mesh as its outline in the average of its shown points' colors, clipping masks cut what they clip, +//! and the art is cut at the region's edges. Hidden and non-printing layers, hidden objects, +//! objects at 0% opacity, template layers, guides and placed images are left out. +//! +//! Coordinates are plotter units (1016 to the inch, y up) from the region's bottom-left corner or +//! its center, rounded to whole units. Art past ±8,388,607 units (2²³ − 1, the smallest range +//! the HP-GL/2 reference asks a device to take for encoded polylines) from the origin is cut off. +//! An HP-GL plot with a coordinate outside −32,768 to 32,767 (16-bit numbers, the range older +//! devices read) gets a warning; HP-GL/2's encoded polylines take the wider range. +//! The pens are drawn in turn (pen 1's paths, then pen 2's), each in paint order or, with +//! `sort`, each next path the one that starts nearest where the pen stopped. With `inside_first`, +//! a pen draws a path only after every path of its own that lies inside it (a letter's counter +//! before the letter, a hole before the part). +//! +//! HP-GL writes `IN;`, then for each pen `PU;SP;` and per path `PUx,y;PDx,y,…;`, then `PU;SP0;`. +//! HP-GL/2 also writes the palette (`NP` and a `PC` color for each pen) and draws each pen's paths +//! as one encoded polyline (`PE`, base 64). + +mod clip; +mod nest; + +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashSet}; +use std::sync::Arc; + +use kurbo::PathEl; +use vectorcraft_color::Paint; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, StrokeLayer, SymbolBoxes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect}; + +use crate::MAX_NEST; +use clip::Region; + +/// Plotter units per point. +const PLU_PER_PT: f64 = 1016.0 / 72.0; +/// The largest coordinate written, plotter units. +pub const MAX_COORD: i64 = (1 << 23) - 1; +/// The coordinates an HP-GL plot keeps to without a warning: 16-bit numbers, plotter units. +const CLASSIC_RANGE: std::ops::RangeInclusive = -32_768..=32_767; +/// The curve tolerance a path is flattened to by default, points. +pub const DEFAULT_TOLERANCE: f64 = 0.1; +/// The smallest and largest curve tolerance, points. +pub const TOLERANCE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; +/// The most pens: a pen table's length, and the colors that get a pen of their own. +pub const MAX_PENS: usize = 255; +/// The most points the plots of one export hold. +const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 10_000_000 }; +/// The most work sorting paths and finding which lie inside others may take, over the whole plot: +/// one for each point or box compared. +const MAX_SORT_WORK: u64 = if cfg!(test) { 100_000 } else { 500_000_000 }; +/// The most edge tests clipping masks may take, over the whole plot. +const MAX_CLIP_TESTS: u64 = if cfg!(test) { 1_000_000 } else { 200_000_000 }; +/// The most points the clipping masks around an object may hold, together. +const MAX_MASK_POINTS: usize = if cfg!(test) { 10_000 } else { 10_000_000 }; +/// The most objects live art (blends, envelopes, repeats) may make for a plot, together, as one +/// evaluation of live art may make ([`vectorcraft_doc::live::MAX_GENERATED`]). +const MAX_GENERATED: u64 = if cfg!(test) { 1_000 } else { vectorcraft_doc::live::MAX_GENERATED as u64 }; + +const TEXT_OUTLINES: &str = "type is plotted as its glyph outlines"; +const INLINE_GRAPHICS: &str = "inline graphics in type are left out"; +const IMAGES: &str = "placed images are left out: a pen draws only lines"; +const MASKS: &str = "opacity masks are left out"; +const RASTER_FX: &str = "raster effects (shadows, glows, blurs, feathering) are left out"; +const STROKE_LOOK: &str = "stroke widths, dashes, brushes and arrowheads are left out: each path is drawn once along its own line"; +const TOO_MANY_POINTS: &str = "the export is too large: the art past its first 10 million points was left out"; +const CLIP_WORK: &str = "clipping masks are too complex to apply in full: the art past that point is drawn whole"; +const MASK_POINTS: &str = "clipping masks past 10 million points together are left out: the art they clip is drawn unclipped by them"; +const OUT_OF_RANGE: &str = "art past 8,388,607 plotter units (about 210 m) from the origin is cut off"; +const PAST_CLASSIC_RANGE: &str = "the plot has coordinates past 32,767 plotter units (about 82 cm) from the origin, which older HP-GL devices may not read: HP-GL/2 takes a wider range"; +const MANY_COLORS: &str = "the art has more than 255 colors: the colors past those draw with the pen of the nearest color"; +const UNSORTED: &str = "the plot has too many paths to sort in full: the rest are drawn in paint order"; +const UNSORTED_INSIDE: &str = "the plot has too many paths to sort in full: the rest are drawn in paint order, each after the paths inside it"; +const UNNESTED: &str = "the plot has too many paths to find in full which lie inside others: from the pen where that stopped, a path may be drawn before the paths inside it"; +const TOO_DEEP: &str = "symbols, blends, envelopes and repeats nested more than 8 deep were left out"; +const LIVE_LEFT_OUT: &str = "blends, envelopes and repeats make too many objects: the art past 4 million objects was left out"; +const SYMBOLS_LEFT_OUT: &str = "symbols placed inside symbols hold too many objects: the instances past that were left out"; + +/// The language written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Version { + /// `IN`, `SP`, `PU` and `PD` only. + #[default] + Hpgl, + /// HP-GL/2: pen colors (`NP`, `PC`) and encoded polylines (`PE`). + Hpgl2, +} + +impl Version { + pub const ALL: [Self; 2] = [Self::Hpgl, Self::Hpgl2]; + + /// The `hpglVersion` param value. + pub fn id(self) -> &'static str { + match self { + Self::Hpgl => "hpgl", + Self::Hpgl2 => "hpgl2", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::Hpgl => "HP-GL", + Self::Hpgl2 => "HP-GL/2", + } + } + + /// A version by id (`hpgl`, `hpgl2`; `hp-gl` and `hp-gl/2` also read), any case. + pub fn from_id(s: &str) -> Option { + let s = s.trim(); + Self::ALL.into_iter().find(|v| s.eq_ignore_ascii_case(v.id()) || s.eq_ignore_ascii_case(v.label())) + } +} + +/// Where the plot's origin (0, 0) lies on the region. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Origin { + #[default] + BottomLeft, + Center, +} + +impl Origin { + pub const ALL: [Self; 2] = [Self::BottomLeft, Self::Center]; + + /// The `origin` param value. + pub fn id(self) -> &'static str { + match self { + Self::BottomLeft => "bottomLeft", + Self::Center => "center", + } + } + + /// An origin by id, any case. + pub fn from_id(s: &str) -> Option { + Self::ALL.into_iter().find(|o| s.trim().eq_ignore_ascii_case(o.id())) + } +} + +/// The HP-GL export settings. +#[derive(Clone, Debug)] +pub struct HpglOptions { + pub version: Version, + /// How far a flattened curve may lie from the curve, points ([`TOLERANCE_RANGE`]; a value + /// outside it is an error). + pub tolerance: f64, + /// The pen table: pen 1's color first, up to [`MAX_PENS`] (more is an error). Empty: a pen for + /// each color the art draws in. + pub pens: Vec<[u8; 3]>, + pub origin: Origin, + /// Draw each pen's paths nearest first, instead of in paint order. + pub sort: bool, + /// Draw a path only after the pen's paths that lie inside it. + pub inside_first: bool, + /// The area plotted (document space): its bottom-left corner or center is the origin, and the + /// art is cut at its edges. + pub region: Rect, +} + +impl Default for HpglOptions { + fn default() -> Self { + Self { + version: Version::default(), + tolerance: DEFAULT_TOLERANCE, + pens: vec![], + origin: Origin::default(), + sort: false, + inside_first: false, + region: Rect::ZERO, + } + } +} + +/// A written plot. +#[derive(Clone, Debug, Default)] +pub struct HpglOutput { + pub bytes: Vec, + /// The pens' colors, pen 1's first. + pub pens: Vec<[u8; 3]>, + /// What was approximated or left out. + pub warnings: Vec, +} + +/// Write the visible art of `doc` over `opts.region` as an HP-GL plot. Live geometry effects are +/// applied first. +pub fn export(doc: &Document, opts: &HpglOptions) -> Result { + Ok(export_regions(doc, opts, &[opts.region])?.pop().unwrap_or_default()) +} + +/// Write the visible art of `doc` over each of `regions` as an HP-GL plot, one per region, as +/// [`export`] does with `opts.region`. The plots share one pen numbering, so a color is the same +/// pen in each, and one point budget. +pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> Result, String> { + let regions: Vec = regions.iter().map(|r| r.abs()).collect(); + if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { + return Err("the export region is empty".into()); + } + if !TOLERANCE_RANGE.contains(&opts.tolerance) { + return Err("the curve tolerance must be from 0.01 to 10 points".into()); + } + if opts.pens.len() > MAX_PENS { + return Err("the pen table holds more than 255 pens".into()); + } + let tolerance = opts.tolerance; + // Layers the plot leaves out go first: baking can wrap one in art that would be drawn (its + // crop marks). + let shown = plotted(&doc.layers, false).map(|layers| { + let mut d = doc.clone(); + d.layers = layers; + d + }); + let doc = shown.as_ref().unwrap_or(doc); + let baked = vectorcraft_effects::bake_document(doc); + let doc = baked.as_ref().unwrap_or(doc); + // Each plot's lines in plotter units, with the points a move doesn't change dropped, and its + // warnings. + let mut plots: Vec<(Lines, Vec)> = Vec::with_capacity(regions.len()); + let mut points = 0; + for r in regions { + // Document space to plotter units, y up. + let o = match opts.origin { + Origin::BottomLeft => Point::new(r.x0, r.y1), + Origin::Center => r.center(), + }; + let span = MAX_COORD as f64 / PLU_PER_PT; + let range = Rect::new(o.x - span, o.y - span, o.x + span, o.y + span); + let mut walk = Walk::new(doc, r.intersect(range), tolerance); + walk.points = points; + // Only a region past the range can have art the range cuts off. + if r.intersect(range) != r { + walk.range = Some((range, r)); + walk.asked = Region::new(vec![corners(r)], FillRule::NonZero); + } + for l in &doc.layers { + walk.node(l, false); + } + points = walk.points; + let Walk { runs, warnings, .. } = walk; + let to_plu = |p: Point| { + let x = ((p.x - o.x) * PLU_PER_PT).round().clamp(-(MAX_COORD as f64), MAX_COORD as f64) as i64; + let y = ((o.y - p.y) * PLU_PER_PT).round().clamp(-(MAX_COORD as f64), MAX_COORD as f64) as i64; + (x, y) + }; + let lines = runs + .into_iter() + .filter_map(|run| { + let mut pts: Vec<(i64, i64)> = Vec::with_capacity(run.points.len()); + for p in run.points { + let q = to_plu(p); + if pts.last() != Some(&q) { + pts.push(q); + } + } + // A line shorter than a plotter unit draws nothing and takes no pen. + (pts.len() >= 2).then_some((run.rgb, pts)) + }) + .collect(); + plots.push((lines, warnings)); + } + let mut pen_warnings = vec![]; + let colors: Vec<[u8; 3]> = plots.iter().flat_map(|(lines, _)| lines.iter().map(|(c, _)| *c)).collect(); + let (pens, of_line) = assign_pens(&colors, &opts.pens, &mut pen_warnings); + let mut of_line = of_line.into_iter(); + let mut out = Vec::with_capacity(plots.len()); + for (lines, mut warnings) in plots { + let mut by_pen: Vec>> = vec![vec![]; pens.len()]; + for ((_, pts), pen) in lines.into_iter().zip(of_line.by_ref()) { + if let Some(paths) = by_pen.get_mut(pen) { + paths.push(pts); + } + } + if !by_pen.iter().all(Vec::is_empty) { + pen_warnings.iter().for_each(|w| warn(&mut warnings, w)); + } + if opts.sort || opts.inside_first { + let (mut at, mut work) = ((0, 0), MAX_SORT_WORK); + for paths in &mut by_pen { + at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut warnings); + } + } + if opts.version == Version::Hpgl && by_pen.iter().flatten().flatten().any(|(x, y)| !CLASSIC_RANGE.contains(x) || !CLASSIC_RANGE.contains(y)) { + warn(&mut warnings, PAST_CLASSIC_RANGE); + } + let bytes = match opts.version { + Version::Hpgl => plain(&by_pen), + Version::Hpgl2 => encoded(&by_pen, &pens), + }; + out.push(HpglOutput { bytes, pens: pens.clone(), warnings }); + } + Ok(out) +} + +/// A plot's lines in plotter units, each with its color. +type Lines = Vec<([u8; 3], Vec<(i64, i64)>)>; + +fn warn(warnings: &mut Vec, w: &str) { + if !warnings.iter().any(|x| x == w) { + warnings.push(w.to_string()); + } +} + +/// The corners of `r`, as a clipping ring. +fn corners(r: Rect) -> Vec { + vec![Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} + +/// Does `r` hold `p`, its edges included? +fn holds(r: Rect, p: Point) -> bool { + p.x >= r.x0 && p.x <= r.x1 && p.y >= r.y0 && p.y <= r.y1 +} + +/// The pens and each line's pen (0-based), from the lines' `colors`: with a table, the table and +/// the nearest of its colors; else each new color a pen of its own, up to [`MAX_PENS`], and the +/// nearest after that. +fn assign_pens(colors: &[[u8; 3]], table: &[[u8; 3]], warnings: &mut Vec) -> (Vec<[u8; 3]>, Vec) { + let mut pens: Vec<[u8; 3]> = table.iter().take(MAX_PENS).copied().collect(); + let fixed = !pens.is_empty(); + let mut of_line = Vec::with_capacity(colors.len()); + for &rgb in colors { + let pen = match pens.iter().position(|c| *c == rgb) { + Some(i) => i, + None if !fixed && pens.len() < MAX_PENS => { + pens.push(rgb); + pens.len() - 1 + } + None => { + if !fixed { + warn(warnings, MANY_COLORS); + } + nearest(&pens, rgb) + } + }; + of_line.push(pen); + } + (pens, of_line) +} + +/// The index of the color in `pens` nearest `c` (the first of equally near ones). +fn nearest(pens: &[[u8; 3]], c: [u8; 3]) -> usize { + let d = |p: &[u8; 3]| (0..3).map(|i| (i32::from(p[i]) - i32::from(c[i])).pow(2)).sum::(); + pens.iter().enumerate().min_by_key(|(_, p)| d(p)).map_or(0, |(i, _)| i) +} + +fn dist2(a: (i64, i64), b: (i64, i64)) -> i128 { + let (dx, dy) = (i128::from(a.0) - i128::from(b.0), i128::from(a.1) - i128::from(b.1)); + dx * dx + dy * dy +} + +/// The squared distance from `p` to box `b` (`[x0, y0, x1, y1]`), 0 inside it. +fn box_dist2(p: (i64, i64), b: [i64; 4]) -> i128 { + let d = |v: i64, lo: i64, hi: i64| i128::from(lo.saturating_sub(v).max(v.saturating_sub(hi)).max(0)); + let (dx, dy) = (d(p.0, b[0], b[2]), d(p.1, b[1], b[3])); + dx * dx + dy * dy +} + +/// `paths` (one pen's) reordered from `at`. With `nearest`, each next path is the one nearest +/// where the pen stopped, by its start or, for an open path (then drawn backwards), its end, or +/// for a closed path any of its points (where it then starts); without, the first in paint order. +/// With `inside_first`, a path is drawn only once every path lying inside it ([`nest::outer`]) is. +/// Once `work` is spent, the paths left keep paint order, each after the paths inside it with +/// `inside_first`, with a warning. Returns where the pen stops. +fn reorder( + paths: &mut Vec>, + mut at: (i64, i64), + work: &mut u64, + nearest: bool, + inside_first: bool, + warnings: &mut Vec, +) -> (i64, i64) { + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| nest::bounds(p)).collect(); + // The paths each path lies inside, and how many paths inside each are still to draw. + let outer = inside_first.then(|| nest::outer(paths, &boxes, work)).flatten(); + if inside_first && outer.is_none() { + warn(warnings, UNNESTED); + } + let mut waiting = vec![0usize; paths.len()]; + for o in outer.iter().flatten().flatten() { + if let Some(w) = waiting.get_mut(*o) { + *w += 1; + } + } + if !nearest { + if let Some(outer) = &outer { + let all = std::mem::take(paths).into_iter().enumerate().collect(); + inner_first(all, outer, &mut waiting, paths); + } + return at; + } + // Each path with its index and box. + let mut left: Vec<_> = std::mem::take(paths).into_iter().zip(boxes).enumerate().map(|(i, (p, b))| (i, p, b)).collect(); + while !left.is_empty() { + // (index, reversed, the closed path's point to start at, distance) + let mut best: (usize, bool, Option, i128) = (usize::MAX, false, None, i128::MAX); + for (i, (j, p, b)) in left.iter().enumerate() { + let (Some(&s), Some(&e)) = (p.first(), p.last()) else { continue }; + *work = work.saturating_sub(1); + if waiting.get(*j).is_some_and(|w| *w > 0) { + continue; + } + if s == e && p.len() > 2 { + if box_dist2(at, *b) >= best.3 { + continue; + } + *work = work.saturating_sub(p.len() as u64); + if let Some((k, d)) = p.iter().enumerate().map(|(k, q)| (k, dist2(at, *q))).min_by_key(|(_, d)| *d) + && d < best.3 + { + best = (i, false, Some(k), d); + } + continue; + } + let (ds, de) = (dist2(at, s), dist2(at, e)); + if ds < best.3 { + best = (i, false, None, ds); + } + if de < best.3 { + best = (i, true, None, de); + } + } + // Spent, or no path free to draw (which only a fault could cause): the rest in paint + // order, each after the paths inside it. + if *work == 0 || best.0 >= left.len() { + match &outer { + Some(outer) => { + warn(warnings, UNSORTED_INSIDE); + inner_first(left.into_iter().map(|(j, p, _)| (j, p)).collect(), outer, &mut waiting, paths); + } + None => { + warn(warnings, UNSORTED); + paths.extend(left.into_iter().map(|(_, p, _)| p)); + } + } + return at; + } + let (j, mut p, _) = left.remove(best.0); + for o in outer.as_ref().and_then(|outer| outer.get(j)).into_iter().flatten() { + if let Some(w) = waiting.get_mut(*o) { + *w = w.saturating_sub(1); + } + } + if best.1 { + p.reverse(); + } else if let Some(k) = best.2 { + // A closed path starts at its point nearest the pen. + p.pop(); + let k = k.min(p.len().saturating_sub(1)); + p.rotate_left(k); + if let Some(&s) = p.first() { + p.push(s); + } + } + if let Some(&e) = p.last() { + at = e; + } + paths.push(p); + } + at +} + +/// Appends `left` (each path with its index among the pen's paths) to `paths` in paint order, +/// each after the paths lying inside it: `outer` lists the paths each lies inside, and `waiting` +/// counts, for each, the paths inside it still to draw. [`nest::outer`] puts a path only inside +/// larger ones, so every path comes free; a path left waiting by a fault is drawn last. +fn inner_first(left: Vec<(usize, Vec<(i64, i64)>)>, outer: &[Vec], waiting: &mut [usize], paths: &mut Vec>) { + let mut held: Vec>> = (0..outer.len()).map(|_| None).collect(); + let mut free = BinaryHeap::new(); + for (j, p) in left { + if let Some(h) = held.get_mut(j) { + if waiting.get(j).is_none_or(|w| *w == 0) { + free.push(Reverse(j)); + } + *h = Some(p); + } else { + paths.push(p); + } + } + while let Some(Reverse(j)) = free.pop() { + let Some(p) = held.get_mut(j).and_then(Option::take) else { continue }; + paths.push(p); + for &o in outer.get(j).into_iter().flatten() { + if let Some(w) = waiting.get_mut(o) { + *w = w.saturating_sub(1); + if *w == 0 { + free.push(Reverse(o)); + } + } + } + } + paths.extend(held.into_iter().flatten()); +} + +/// HP-GL: `IN;`, each pen's paths as `PU` and `PD`, `PU;SP0;`. +fn plain(by_pen: &[Vec>]) -> Vec { + let mut s = String::from("IN;"); + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + s.push_str(&format!("PU;SP{};", i + 1)); + for path in paths { + let Some(((x, y), rest)) = path.split_first() else { continue }; + s.push_str(&format!("PU{x},{y};PD")); + for (k, (x, y)) in rest.iter().enumerate() { + if k > 0 { + s.push(','); + } + s.push_str(&format!("{x},{y}")); + } + s.push(';'); + } + } + s.push_str("PU;SP0;"); + s.into_bytes() +} + +/// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. +fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { + let mut out = b"IN;".to_vec(); + if !pens.is_empty() { + // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. + let np = (pens.len() + 1).next_power_of_two().max(2); + out.extend(format!("NP{np};").bytes()); + for (i, [r, g, b]) in pens.iter().enumerate() { + out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); + } + } + let mut at: Option<(i64, i64)> = None; + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + out.extend(format!("PU;SP{};PE", i + 1).bytes()); + for path in paths { + for (k, &p) in path.iter().enumerate() { + if k == 0 { + out.push(b'<'); + } + // The first move of the plot is absolute, and so is one longer than the range a + // device takes for each number; every other is relative. + match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { + None => { + out.push(b'='); + pe_number(&mut out, p.0); + pe_number(&mut out, p.1); + } + Some((dx, dy)) => { + pe_number(&mut out, dx); + pe_number(&mut out, dy); + } + } + at = Some(p); + } + } + out.push(b';'); + } + out.extend(b"PU;SP0;"); + out +} + +/// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last +/// digit from 191 up. +fn pe_number(out: &mut Vec, v: i64) { + let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); + while n >= 64 { + out.push(63 + (n % 64) as u8); + n /= 64; + } + out.push(191 + n as u8); +} + +/// One line the pen draws, in document space, and its color. +struct Run { + rgb: [u8; 3], + points: Vec, +} + +/// The document walk: each visible path becomes runs, clipped, in paint order. +struct Walk<'a> { + doc: &'a Document, + symbols: SymbolBoxes<'a>, + /// The region the art is cut at. + region: Rect, + edge: Option, + /// The plotter's range and the region asked for, when that reaches past the range. + range: Option<(Rect, Rect)>, + /// The region asked for, to cut a line at before testing it against the range. + asked: Option, + tolerance: f64, + /// The clipping masks around the current object, outermost first. + clips: Vec, + /// The points those masks hold ([`MAX_MASK_POINTS`]). + mask_points: usize, + runs: Vec, + points: usize, + clip_tests: u64, + warnings: Vec, + nest: u32, + /// Objects the symbol instances written held, together ([`vectorcraft_doc::MAX_SYMBOL_NODES`]). + symbol_nodes: u64, + /// Objects the live art written made, together ([`MAX_GENERATED`]). + generated: u64, + /// A copy of the document without its layers, to bake symbol art in ([`Walk::baked`]). + scratch: Option, + /// The symbols whose art holds geometry effects ([`Walk::baked`]), or instances of such + /// symbols. + effect_symbols: HashSet, +} + +impl<'a> Walk<'a> { + fn new(doc: &'a Document, region: Rect, tolerance: f64) -> Self { + Self { + doc, + symbols: doc.symbol_boxes().quick(), + region, + edge: Region::new(vec![corners(region)], FillRule::NonZero), + range: None, + asked: None, + tolerance, + clips: vec![], + mask_points: 0, + runs: vec![], + points: 0, + clip_tests: 0, + warnings: vec![], + nest: 0, + symbol_nodes: 0, + generated: 0, + scratch: None, + effect_symbols: effect_symbols(doc), + } + } + + fn warn(&mut self, w: &str) { + warn(&mut self.warnings, w); + } + + fn full(&self) -> bool { + self.points >= MAX_POINTS + } + + fn node(&mut self, n: &Node, force: bool) { + if n.is_ruler_guide() || n.is_template() { + return; + } + if self.full() { + self.warn(TOO_MANY_POINTS); + return; + } + if !force && !n.visible { + return; + } + // Art at no opacity shows nothing, and nor does anything inside it. + if n.opacity <= 0.0 { + return; + } + // Bounds don't measure the effects in symbol art, which apply only once an instance is + // placed: an instance of such art, and what holds one, is not skipped by its bounds. + let unmeasured = !self.effect_symbols.is_empty() && holds_instance_of(n, &self.effect_symbols); + // The box round all the object can paint, a blend's steps on its spine included. + if !n.is_layer() && !unmeasured { + match n.reach_bounds_with(&self.symbols) { + Some(b) if !overlaps(b, self.region) => { + // Art over the asked-for region but past the plotter's range is cut off. + if self.range.is_some_and(|(_, whole)| overlaps(b, whole)) { + self.warn(OUT_OF_RANGE); + } + return; + } + None if !n.is_container() => return, + _ => {} + } + } + if n.extras().mask.as_ref().is_some_and(|m| !m.disabled) { + self.warn(MASKS); + } + let raster = |fx: &[vectorcraft_doc::Effect]| fx.iter().any(|e| e.visible && vectorcraft_effects::is_raster(&e.id)); + if raster(&n.appearance.effects) || n.appearance.items.iter().any(|i| raster(i.effects())) { + self.warn(RASTER_FX); + } + match &n.kind { + // Non-printing layers aren't plotted. + NodeKind::Layer { children, printable, clip, .. } => { + if *printable { + self.children(children, *clip); + } + } + NodeKind::Group { children, clip } => self.children(children, *clip), + NodeKind::Path { path, guide, .. } => { + if !*guide { + self.shape(n, &path.to_bezpath()); + } + } + NodeKind::Compound { children, .. } => { + let mut bp = BezPath::new(); + for p in children.iter().filter_map(|c| c.path_data()) { + bp.extend(p.to_bezpath()); + } + self.shape(n, &bp); + } + NodeKind::Text(t) => { + if t.runs.iter().any(|r| r.inline.is_some()) { + self.warn(INLINE_GRAPHICS); + } + if let Some(o) = vectorcraft_effects::outline_text(n) { + self.warn(TEXT_OUTLINES); + self.node(&o, true); + } + } + NodeKind::Image(_) => self.warn(IMAGES), + NodeKind::SymbolInstance { symbol, xf } => self.symbol(n, symbol, *xf), + // A gradient mesh is its outline, in the average of its shown points' colors: its + // patches are shading, not lines. A mesh whose every point is at 0% opacity shows + // nothing. + NodeKind::Mesh(m) => { + let shown: Vec<[u8; 3]> = m.points.iter().filter(|p| p.opacity > 0.0).map(|p| rgb8(&p.color)).collect(); + if !shown.is_empty() { + self.draw(average(shown.into_iter()), &m.outline().to_bezpath(), true); + } + } + // Live blends, envelopes and repeats are drawn as their evaluated art, a level at a + // time, so a gradient mesh a blend makes is its outline too. + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { + if self.nest >= MAX_NEST { + self.warn(TOO_DEEP); + return; + } + // Once the budget is spent, nothing more is evaluated. + if self.generated >= MAX_GENERATED { + self.warn(LIVE_LEFT_OUT); + return; + } + let art = vectorcraft_effects::expand_live(Some(self.doc), n); + let count = art.iter().map(|c| c.count() as u64).sum::(); + if self.generated.saturating_add(count) > MAX_GENERATED { + self.generated = MAX_GENERATED; + self.warn(LIVE_LEFT_OUT); + return; + } + self.generated += count; + self.nest += 1; + art.iter().for_each(|c| self.node(c, false)); + self.nest -= 1; + } + NodeKind::RulerGuide { .. } => {} + } + } + + /// A symbol instance's art, placed (clip groups included), within the budget for the export. + fn symbol(&mut self, n: &Node, symbol: &str, xf: Affine) { + let doc = self.doc; + if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { + self.warn(SYMBOLS_LEFT_OUT); + return; + } + let Some(sym) = doc.symbols.iter().find(|s| s.name == symbol) else { return }; + if self.nest >= MAX_NEST { + self.warn(TOO_DEEP); + return; + } + // The instance's own changes and its stain, as the canvas draws it. + let art = vectorcraft_brush::instance_art(&sym.art, n); + let count = art.count_with_masks() as u64; + let most = doc.symbol_slice_map(symbol, xf).map_or(count, |m| m.most_placed(&art, doc)); + let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { + let placed = doc.place_symbol_art(symbol, &art, xf); + let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); + (placed, n) + }); + match placed { + Some(Some(art)) => { + let art = self.baked(art); + self.nest += 1; + self.node(&art, true); + self.nest -= 1; + } + Some(None) => {} + None => { + self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; + self.warn(SYMBOLS_LEFT_OUT); + } + } + } + + /// Placed symbol art with its geometry effects applied: the document's bake reaches the + /// layers, not the symbols' art. + fn baked(&mut self, art: Node) -> Node { + if !vectorcraft_effects::needs_bake(&art) { + return art; + } + // Guides and layers left out go first, as for the document's layers. + let art = Arc::new(art); + let art = match plotted(std::slice::from_ref(&art), false) { + Some(mut kept) => match kept.pop() { + Some(a) => a, + None => return Node::group(vectorcraft_doc::NodeId(0), vec![]), + }, + None => art, + }; + let art = Arc::unwrap_or_clone(art); + let doc = self.doc; + let scratch = self.scratch.get_or_insert_with(|| { + let mut d = doc.clone(); + d.layers.clear(); + d + }); + scratch.layers = vec![Arc::new(art)]; + let baked = vectorcraft_effects::bake_document(scratch).and_then(|b| b.layers.into_iter().next()); + let art = std::mem::take(&mut scratch.layers).into_iter().next(); + baked.or(art).map(Arc::unwrap_or_clone).unwrap_or_else(|| Node::group(vectorcraft_doc::NodeId(0), vec![])) + } + + /// A container's children. A clipping container's first child cuts the rest; it is drawn + /// itself, once and whole, when it paints: where its stroke paints (over the clipped art) when + /// it has one, else where its fill paints (below it). Nothing to clip by hides the clipped art, + /// as on the canvas. + fn children(&mut self, children: &[Arc], clip: bool) { + let Some((first, rest)) = children.split_first().filter(|_| clip) else { + children.iter().for_each(|c| self.node(c, false)); + return; + }; + let mut paint = first.clip_paint(); + // A stroke at 0% opacity isn't drawn, so the clipping path is drawn in its fill. + let type_stroke = |s: &Node| matches!(&s.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.has_stroke())); + paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s)); + if paint.stroke.is_none() + && let Some(fill) = &paint.fill + { + self.node(fill, false); + } + match vectorcraft_effects::clip_outline(first).map(|(bp, rule)| (self.rings(&bp), rule)) { + Some((Some(rings), rule)) => { + let held: usize = rings.iter().map(Vec::len).sum(); + if let Some(region) = Region::new(rings, rule) { + self.mask_points += held; + self.clips.push(region); + rest.iter().for_each(|c| self.node(c, false)); + self.clips.pop(); + self.mask_points -= held; + } + } + // A mask past the budget isn't built: the art it would clip is drawn unclipped by it. + Some((None, _)) => { + self.warn(MASK_POINTS); + rest.iter().for_each(|c| self.node(c, false)); + } + None => {} + } + // Drawn whole where its stroke paints: a fill closes its outline, and type's characters + // without a stroke are drawn too. + if paint.stroke.is_some() { + self.node(first, false); + } + } + + /// `bp` flattened into closed rings for a clipping mask; `None` when they would take the + /// masks around it past [`MAX_MASK_POINTS`]. + fn rings(&self, bp: &BezPath) -> Option>> { + let left = MAX_MASK_POINTS.saturating_sub(self.mask_points); + let (mut rings, whole) = self.flatten_within(bp, true, left); + if !whole || rings.iter().map(Vec::len).sum::() > left { + return None; + } + for r in &mut rings { + r.pop(); + } + Some(rings) + } + + /// A path drawn in its color: the topmost stroke's that paints, else the topmost fill's that + /// paints (visible, with a paint and some opacity). A filled path's every subpath is closed, + /// as its fill closes it, also when its stroke gives the color. + fn shape(&mut self, n: &Node, bp: &BezPath) { + if bp.elements().is_empty() { + return; + } + let fill = top_fill(n); + let paint = match (top_stroke(n), fill) { + (Some(s), _) => { + if s.dash.as_ref().is_some_and(|d| d.is_dashed()) + || s.brush.is_some() + || s.profile.is_some() + || s.start_arrow.is_some() + || s.end_arrow.is_some() + { + self.warn(STROKE_LOOK); + } + &s.paint + } + (None, Some(f)) => f, + (None, None) => return, + }; + let rgb = self.flat(paint); + self.draw(rgb, bp, fill.is_some()); + } + + /// `bp` drawn in `rgb`: flattened (with `close` every subpath closed), then cut and added. + fn draw(&mut self, rgb: [u8; 3], bp: &BezPath, close: bool) { + // Bounded by the plot's point budget; each curve by its own segment cap. + let budget = MAX_POINTS.saturating_sub(self.points).saturating_mul(4).max(4); + let (lines, whole) = self.flatten_within(bp, close, budget); + if !whole { + self.warn(TOO_MANY_POINTS); + } + for line in lines { + self.add(rgb, line); + } + } + + /// One color for a paint: a solid color, the average of a gradient's stops, or a pattern's + /// first solid fill (gray without one). + fn flat(&self, p: &Paint) -> [u8; 3] { + match p { + Paint::None => [0; 3], + Paint::Solid { color, .. } => rgb8(color), + Paint::Gradient(g) => average(g.gradient.stops.iter().map(|s| rgb8(&s.color))), + Paint::Pattern { pattern, .. } => { + self.doc.pattern(pattern).and_then(|def| def.art.iter().find_map(|a| first_solid(a))).map_or([128; 3], |c| rgb8(&c)) + } + } + } + + /// `bp` as polylines (each subpath one), within the tolerance, stopping once about `budget` + /// moves are made; with `close` every subpath ends at its start, else those that close. Also + /// whether every element of `bp` was flattened. + fn flatten_within(&self, bp: &BezPath, close: bool, budget: usize) -> (Vec>, bool) { + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + let end = |cur: &mut Vec, out: &mut Vec>, closing: bool| { + if (closing || close) + && let Some(&s) = cur.first() + && cur.last() != Some(&s) + { + cur.push(s); + } + out.push(std::mem::take(cur)); + }; + let (made, taken) = (std::cell::Cell::new(0usize), std::cell::Cell::new(0usize)); + let elements = bp.iter().take_while(|_| made.get() < budget).inspect(|_| taken.set(taken.get() + 1)); + vectorcraft_geom::flatten(elements, self.tolerance, |el| { + made.set(made.get() + 1); + match el { + PathEl::MoveTo(p) => { + end(&mut cur, &mut out, false); + cur.push(p); + } + PathEl::LineTo(p) => { + if cur.last() != Some(&p) { + cur.push(p); + } + } + PathEl::ClosePath => { + let s = cur.first().copied(); + end(&mut cur, &mut out, true); + // A subpath that goes on after its close starts where it closed. + if let Some(s) = s { + cur.push(s); + } + } + _ => {} + } + }); + let whole = taken.get() == bp.elements().len(); + // A subpath the budget cut short stays open: a move back to its start isn't on its outline. + if whole { + end(&mut cur, &mut out, false); + } else { + out.push(cur); + } + out.retain(|l| l.len() >= 2); + (out, whole) + } + + /// A polyline drawn in `rgb`, cut by the region and the clipping masks around it. + fn add(&mut self, rgb: [u8; 3], line: Vec) { + // Only the part over the region asked for counts: the rest is cut off anyway. + if let (Some((range, _)), Some(asked)) = (self.range, &self.asked) + && !self.warnings.iter().any(|w| w == OUT_OF_RANGE) + { + let mut unlimited = u64::MAX; + if asked.cut(&line, &mut unlimited).unwrap_or_default().iter().flatten().any(|p| !holds(range, *p)) { + self.warn(OUT_OF_RANGE); + } + } + // The region has four edges, so its cut costs a few tests a point and needs no limit. + let mut unlimited = u64::MAX; + let mut pieces = self.edge.as_ref().and_then(|edge| edge.cut(&line, &mut unlimited)).unwrap_or_default(); + for clip in &self.clips { + let mut left = MAX_CLIP_TESTS.saturating_sub(self.clip_tests); + let cut: Option>>> = pieces.iter().map(|p| clip.cut(p, &mut left)).collect(); + self.clip_tests = MAX_CLIP_TESTS.saturating_sub(left); + match cut { + Some(cut) => pieces = cut.into_iter().flatten().collect(), + None => { + // Spent: this art keeps the parts this mask and the ones inside it would cut, + // and later art that reaches a mask isn't clipped either. + self.clip_tests = MAX_CLIP_TESTS; + warn(&mut self.warnings, CLIP_WORK); + break; + } + } + } + for mut points in pieces { + let left = MAX_POINTS.saturating_sub(self.points); + if points.len() > left { + self.warn(TOO_MANY_POINTS); + points.truncate(left); + } + if points.len() < 2 { + return; + } + self.points += points.len(); + self.runs.push(Run { rgb, points }); + } + } +} + +fn overlaps(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// `nodes` (the children of a clipping container when `clipping`) without the layers and +/// sublayers a plot leaves out (hidden, non-printing, template or at 0% opacity) and without +/// guides, in layers and groups at any depth, so that baking can't wrap one in art that is drawn +/// (its Crop Marks); `None` when nothing changes. A guide that is a clipping path keeps its place +/// without its effects. +fn plotted(nodes: &[Arc], clipping: bool) -> Option>> { + let mut changed = false; + let mut out = Vec::with_capacity(nodes.len()); + for (i, n) in nodes.iter().enumerate() { + match &n.kind { + NodeKind::Layer { printable, template, .. } if !(n.visible && n.opacity > 0.0 && *printable && !*template) => { + changed = true; + continue; + } + NodeKind::Path { guide: true, .. } => { + changed = true; + if clipping && i == 0 { + let mut g = (**n).clone(); + g.appearance.effects.clear(); + out.push(Arc::new(g)); + } + continue; + } + _ => {} + } + let inner = match &n.kind { + NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip } => plotted(children, *clip), + _ => None, + }; + match inner { + Some(children) => { + changed = true; + let mut c = (**n).clone(); + if let Some(ch) = c.children_mut() { + *ch = children; + } + out.push(Arc::new(c)); + } + None => out.push(n.clone()), + } + } + changed.then_some(out) +} + +/// The symbols of `doc` whose art holds geometry effects, and those whose art holds instances of +/// them, as deep as symbols are drawn ([`MAX_NEST`]). +fn effect_symbols(doc: &Document) -> HashSet { + let mut set: HashSet = doc.symbols.iter().filter(|s| vectorcraft_effects::needs_bake(&s.art)).map(|s| s.name.clone()).collect(); + for _ in 0..MAX_NEST { + if set.is_empty() { + break; + } + let more: Vec = + doc.symbols.iter().filter(|s| !set.contains(&s.name) && holds_instance_of(&s.art, &set)).map(|s| s.name.clone()).collect(); + if more.is_empty() { + break; + } + set.extend(more); + } + set +} + +/// Is `n`, or anything in it, an instance of one of `symbols`? +fn holds_instance_of(n: &Node, symbols: &HashSet) -> bool { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol), + _ => n.children().into_iter().flatten().any(|c| holds_instance_of(c, symbols)), + } +} + +fn rgb8(c: &vectorcraft_color::Color) -> [u8; 3] { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] +} + +/// The average of `colors` (black without any). +fn average(colors: impl Iterator) -> [u8; 3] { + let (sum, n) = colors.fold(([0.0; 3], 0.0), |(a, n), c| ([0, 1, 2].map(|i| a[i] + f64::from(c[i])), n + 1.0)); + sum.map(|v| (v / f64::max(n, 1.0)).round().clamp(0.0, 255.0) as u8) +} + +/// The first visible solid fill color in `n` (a pattern tile's art), hidden objects and objects +/// or fills at 0% opacity left out. +fn first_solid(n: &Node) -> Option { + if !n.visible || n.opacity <= 0.0 { + return None; + } + let own = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 => f.paint.color(), + _ => None, + }); + own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) +} + +/// The topmost stroke of `n` that paints: visible, with a paint, a weight and some opacity. +fn top_stroke(n: &Node) -> Option<&StrokeLayer> { + n.appearance.items.iter().rev().find_map(|i| match i { + AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0 && s.opacity > 0.0 => Some(s), + _ => None, + }) +} + +/// The paint of the topmost fill of `n` that paints: visible, with a paint and some opacity. +fn top_fill(n: &Node) -> Option<&Paint> { + n.appearance.items.iter().rev().find_map(|i| match i { + AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() && f.opacity > 0.0 => Some(&f.paint), + _ => None, + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/cad/src/hpgl/write/clip.rs b/crates/cad/src/hpgl/write/clip.rs new file mode 100644 index 0000000000..235032ee2b --- /dev/null +++ b/crates/cad/src/hpgl/write/clip.rs @@ -0,0 +1,265 @@ +//! Polylines cut by a region: each segment is split where it crosses the region's edges, and the +//! pieces whose middle lies inside are kept, joined where they meet. + +use vectorcraft_geom::{FillRule, Point, Rect}; + +/// A clipping region: closed rings (each closes implicitly) and the rule that decides inside. +pub(super) struct Region { + rings: Vec>, + rule: FillRule, + bounds: Rect, +} + +impl Region { + /// The region of `rings` under `rule`; `None` when it has no ring of three points or more. + pub fn new(rings: Vec>, rule: FillRule) -> Option { + let rings: Vec> = rings.into_iter().filter(|r| r.len() >= 3).collect(); + let bounds = rings.iter().flatten().fold(None, |b: Option, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?; + Some(Self { rings, rule, bounds }) + } + + /// The edges this region has, which [`Region::cut`] tests each segment against. + fn edges(&self) -> u64 { + self.rings.iter().map(|r| r.len() as u64).sum() + } + + /// Does `p` lie on one of the region's edges (within a millionth of a point)? + fn on_edge(&self, p: Point) -> bool { + self.rings.iter().any(|ring| { + ring.iter().enumerate().any(|(i, &a)| { + let b = ring[(i + 1) % ring.len()]; + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (a + ab * t).distance(p) <= 1e-6 + }) + }) + } + + /// Is `p` inside (non-zero winding or an odd number of crossings), or on an edge? + fn contains(&self, p: Point) -> bool { + if self.on_edge(p) { + return true; + } + let mut winding = 0i64; + for ring in &self.rings { + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + if a.y <= p.y { + if b.y > p.y && cross(a, b, p) > 0.0 { + winding += 1; + } + } else if b.y <= p.y && cross(a, b, p) < 0.0 { + winding -= 1; + } + } + } + match self.rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + } + } + + /// Where segment `a`–`b` crosses this region's edges, as fractions of its length strictly + /// between 0 and 1, sorted. + fn crossings(&self, a: Point, b: Point) -> Vec { + let mut ts = vec![]; + for ring in &self.rings { + for (i, &c) in ring.iter().enumerate() { + let d = ring[(i + 1) % ring.len()]; + if let Some(t) = intersect(a, b, c, d) + && t > 1e-12 + && t < 1.0 - 1e-12 + { + ts.push(t); + } + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|x, y| (*x - *y).abs() <= 1e-12); + ts + } + + /// The parts of polyline `line` inside the region, each a polyline of two points or more. + /// Every test of a point or a segment against an edge takes one from `budget`; `None` when + /// the budget runs out first. + pub fn cut(&self, line: &[Point], budget: &mut u64) -> Option>> { + let edges = self.edges(); + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + for w in line.windows(2) { + let (a, b) = (w[0], w[1]); + // A segment wholly off the region's box lies outside it. + let near = overlaps(Rect::from_points(a, b), self.bounds); + let ts = if near { + spend(budget, edges)?; + self.crossings(a, b) + } else { + vec![] + }; + let mut from = 0.0; + for to in ts.into_iter().chain([1.0]) { + let (p, q) = (a.lerp(b, from), a.lerp(b, to)); + // Each piece between crossings is tested on its own: its edge and winding tests. + let inside = if near { + spend(budget, edges.saturating_mul(2))?; + self.contains(p.midpoint(q)) + } else { + false + }; + if inside { + if cur.last().is_none_or(|l| l.distance(p) > 1e-9) { + flush(&mut out, &mut cur); + cur.push(p); + } + cur.push(q); + } else { + flush(&mut out, &mut cur); + } + from = to; + } + } + flush(&mut out, &mut cur); + // A closed line that leaves the region and comes back: its last piece ends where its + // first starts, at the line's start, and the two are one piece. + if line.len() > 2 + && line.first() == line.last() + && out.len() >= 2 + && let (Some(end), Some(start)) = (out.last().and_then(|l| l.last()), out.first().and_then(|l| l.first())) + && end.distance(*start) <= 1e-9 + { + let first = out.remove(0); + if let Some(last) = out.last_mut() { + last.extend(first.into_iter().skip(1)); + } + } + Some(out) + } +} + +/// Take `n` from `budget`; `None` when it holds less. +fn spend(budget: &mut u64, n: u64) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +fn flush(out: &mut Vec>, cur: &mut Vec) { + let line = std::mem::take(cur); + if line.len() >= 2 { + out.push(line); + } +} + +fn overlaps(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Which side of line `a`–`b` point `p` lies on (positive: left). +fn cross(a: Point, b: Point, p: Point) -> f64 { + (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y) +} + +/// Where segment `a`–`b` crosses segment `c`–`d`, as a fraction of `a`–`b`; `None` when they +/// are parallel or don't meet. +fn intersect(a: Point, b: Point, c: Point, d: Point) -> Option { + let (r, s) = (b - a, d - c); + let den = r.x * s.y - r.y * s.x; + if den.abs() <= f64::EPSILON * (r.hypot() * s.hypot()).max(f64::MIN_POSITIVE) { + return None; + } + let ac = c - a; + let t = (ac.x * s.y - ac.y * s.x) / den; + let u = (ac.x * r.y - ac.y * r.x) / den; + ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then_some(t) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { + vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)] + } + + /// `line` cut by `r` with no limit on the work. + fn cut(r: &Region, line: &[Point]) -> Vec> { + let mut unlimited = u64::MAX; + r.cut(line, &mut unlimited).unwrap() + } + + #[test] + fn a_line_across_a_square_keeps_its_middle() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let pieces = cut(&r, &[Point::new(-5.0, 5.0), Point::new(15.0, 5.0)]); + assert_eq!(pieces, vec![vec![Point::new(0.0, 5.0), Point::new(10.0, 5.0)]]); + // Wholly outside, nothing; wholly inside, the line as it is. + assert!(cut(&r, &[Point::new(20.0, 0.0), Point::new(30.0, 0.0)]).is_empty()); + let inside = vec![Point::new(1.0, 1.0), Point::new(9.0, 1.0), Point::new(9.0, 9.0)]; + assert_eq!(cut(&r, &inside), vec![inside]); + } + + /// Each piece between crossings costs a pass over the edges: a line through the teeth of a + /// comb spends far more than its two points times the edges. + #[test] + fn every_piece_between_crossings_is_paid_for() { + let mut ring = vec![]; + for i in 0..100 { + let x = f64::from(i) * 4.0; + ring.extend([Point::new(x, 0.0), Point::new(x + 2.0, 0.0), Point::new(x + 2.0, 10.0), Point::new(x + 4.0, 10.0)]); + } + ring.extend([Point::new(400.0, 20.0), Point::new(0.0, 20.0)]); + let r = Region::new(vec![ring], FillRule::NonZero).unwrap(); + let line = [Point::new(-1.0, 5.0), Point::new(401.0, 5.0)]; + // 402 edges, 200 crossings, 201 pieces: 402 + 201 × 2 × 402 tests. + let need = 402 + 201 * 2 * 402; + let mut budget = need; + assert_eq!(r.cut(&line, &mut budget).map(|p| p.len()), Some(100)); + assert_eq!(budget, 0); + let mut short = need - 1; + assert!(r.cut(&line, &mut short).is_none()); + // A segment off the region's box costs nothing. + assert_eq!(r.cut(&[Point::new(0.0, 30.0), Point::new(9.0, 30.0)], &mut 0), Some(vec![])); + } + + /// A line along any of the region's edges is inside it. + #[test] + fn a_line_on_an_edge_is_kept() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + for line in [ + [Point::new(0.0, 0.0), Point::new(10.0, 0.0)], + [Point::new(10.0, 0.0), Point::new(10.0, 10.0)], + [Point::new(10.0, 10.0), Point::new(0.0, 10.0)], + [Point::new(0.0, 10.0), Point::new(0.0, 0.0)], + ] { + assert_eq!(cut(&r, &line), vec![line.to_vec()], "{line:?}"); + } + } + + #[test] + fn a_line_leaving_and_coming_back_is_two_pieces() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0)]; + assert_eq!(cut(&r, &line), vec![vec![Point::new(5.0, 5.0), Point::new(10.0, 5.0)], vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0)]]); + } + + /// A closed line that starts inside, leaves and comes back is one piece: the part after it + /// comes back runs on into the part before it left. + #[test] + fn a_closed_line_cut_once_stays_one_piece() { + let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap(); + let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0)]; + assert_eq!(cut(&r, &line), vec![vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0), Point::new(10.0, 5.0)]]); + } + + #[test] + fn the_fill_rule_decides_a_hole() { + let rings = vec![square(0.0, 0.0, 10.0, 10.0), square(3.0, 3.0, 7.0, 7.0)]; + let line = [Point::new(-1.0, 5.0), Point::new(11.0, 5.0)]; + // Both rings wind the same way: even-odd cuts a hole, non-zero doesn't. + let even_odd = cut(&Region::new(rings.clone(), FillRule::EvenOdd).unwrap(), &line); + assert_eq!(even_odd, vec![vec![Point::new(0.0, 5.0), Point::new(3.0, 5.0)], vec![Point::new(7.0, 5.0), Point::new(10.0, 5.0)]]); + let non_zero = cut(&Region::new(rings, FillRule::NonZero).unwrap(), &line); + assert_eq!(non_zero.len(), 1); + assert!(Region::new(vec![vec![Point::ZERO, Point::new(1.0, 1.0)]], FillRule::NonZero).is_none()); + } +} diff --git a/crates/cad/src/hpgl/write/nest.rs b/crates/cad/src/hpgl/write/nest.rs new file mode 100644 index 0000000000..eee4630ff3 --- /dev/null +++ b/crates/cad/src/hpgl/write/nest.rs @@ -0,0 +1,357 @@ +//! Which of a pen's paths lie inside which of its closed paths, in plotter units, for drawing the +//! inner paths first. + +/// The box of `p`: `[x0, y0, x1, y1]`. +pub(super) fn bounds(p: &[(i64, i64)]) -> [i64; 4] { + p.iter().fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |b, q| [b[0].min(q.0), b[1].min(q.1), b[2].max(q.0), b[3].max(q.1)]) +} + +/// For each of `paths` (`boxes` are their [`bounds`]), the closed paths it lies inside: none of +/// its segments crosses the closed path's line, each part of it between the points where it meets +/// that line lies inside the closed path (by the even-odd rule) or on the line, and at least one +/// part lies inside. A path touching the line of the one around it is inside it, a path crossing +/// it is not, and copies of one outline are not inside each other. A path is tested only against +/// closed paths larger than it (by the area of their box, then the area they enclose, then paint +/// order), so no two paths are each inside the other, and only against the closed paths in the +/// [`Grid`] cell of its box's first corner. `None` once `work` is spent: a grid cell filled and a +/// box compared cost one each, and each segment tested costs the closed path's points for its +/// crossings and again for each part of it. +pub(super) fn outer(paths: &[Vec<(i64, i64)>], boxes: &[[i64; 4]], work: &mut u64) -> Option>> { + let size: Vec<(i128, i128)> = paths + .iter() + .zip(boxes) + .map(|(p, b)| { + let box_area = (i128::from(b[2]) - i128::from(b[0])) * (i128::from(b[3]) - i128::from(b[1])); + (box_area, if closed(p) { twice_area(p) } else { 0 }) + }) + .collect(); + let rings: Vec = (0..paths.len()).filter(|&i| paths.get(i).is_some_and(|p| closed(p))).collect(); + let mut out = vec![vec![]; paths.len()]; + if rings.is_empty() { + return Some(out); + } + let grid = Grid::new(&rings, boxes, work)?; + for (a, (p, ab)) in paths.iter().zip(boxes).enumerate() { + for &r in grid.at(ab[0], ab[1]) { + spend(work, 1)?; + let (Some(rb), Some(ring)) = (boxes.get(r), paths.get(r)) else { continue }; + let smaller = (size.get(a), a) < (size.get(r), r); + if !smaller || rb[0] > ab[0] || rb[1] > ab[1] || rb[2] < ab[2] || rb[3] < ab[3] { + continue; + } + if inside(p, ring, work)? + && let Some(o) = out.get_mut(a) + { + o.push(r); + } + } + } + Some(out) +} + +/// The most cells along each side of a [`Grid`]. +const MAX_GRID_SIDE: usize = 512; +/// The most cells of a [`Grid`] a closed path is listed in; one whose box covers more is listed +/// once, among the wide ones. A closed path has 4 points or more, so the grid lists no more +/// entries than the pen has points. +const MAX_CELLS_PER_PATH: usize = 4; + +/// A grid over the boxes of a pen's closed paths, about one cell for each, up to +/// [`MAX_GRID_SIDE`] a side: each cell lists, in paint order, the closed paths whose box covers +/// it, and the closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells are listed +/// apart. A closed path whose box holds a point is among the wide ones or in that point's cell. +struct Grid { + /// The first corner of the closed paths' boxes together. + x0: i128, + y0: i128, + /// Their width and height, plus one. + w: i128, + h: i128, + /// Cells along each side. + side: usize, + /// The cells row by row. + cells: Vec>, + /// The closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells. + wide: Vec, +} + +impl Grid { + /// The grid of the closed paths `rings` (indices into `boxes`). `None` once `work` is spent. + fn new(rings: &[usize], boxes: &[[i64; 4]], work: &mut u64) -> Option { + let all = rings + .iter() + .filter_map(|&r| boxes.get(r)) + .fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |e, b| [e[0].min(b[0]), e[1].min(b[1]), e[2].max(b[2]), e[3].max(b[3])]); + let side = ((rings.len() as f64).sqrt().ceil() as usize).clamp(1, MAX_GRID_SIDE); + let (x0, y0) = (i128::from(all[0]), i128::from(all[1])); + let mut grid = Self { + x0, + y0, + w: (i128::from(all[2]) - x0 + 1).max(1), + h: (i128::from(all[3]) - y0 + 1).max(1), + side, + cells: vec![vec![]; side * side], + wide: vec![], + }; + for &r in rings { + let Some(b) = boxes.get(r) else { continue }; + let (Some((cx0, cy0)), Some((cx1, cy1))) = (grid.cell(b[0], b[1]), grid.cell(b[2], b[3])) else { continue }; + let covered = (cx1 - cx0 + 1) * (cy1 - cy0 + 1); + if covered > MAX_CELLS_PER_PATH { + spend(work, 1)?; + grid.wide.push(r); + continue; + } + spend(work, covered as u64)?; + for cy in cy0..=cy1 { + for cell in grid.cells.get_mut(cy * side + cx0..=cy * side + cx1).into_iter().flatten() { + cell.push(r); + } + } + } + Some(grid) + } + + /// The column and row of the cell holding `(x, y)`, `None` outside the grid. + fn cell(&self, x: i64, y: i64) -> Option<(usize, usize)> { + let (dx, dy) = (i128::from(x) - self.x0, i128::from(y) - self.y0); + if dx < 0 || dy < 0 || dx >= self.w || dy >= self.h { + return None; + } + let side = self.side as i128; + Some(((dx * side / self.w) as usize, (dy * side / self.h) as usize)) + } + + /// The wide closed paths, then those listed in the cell holding `(x, y)`. + fn at(&self, x: i64, y: i64) -> impl Iterator { + let cell = self.cell(x, y).and_then(|(cx, cy)| self.cells.get(cy * self.side + cx)).map_or(&[][..], Vec::as_slice); + self.wide.iter().chain(cell) + } +} + +/// Takes `n` from `work`; `None`, with `work` at 0, when it has less. +fn spend(work: &mut u64, n: u64) -> Option<()> { + let left = work.checked_sub(n); + *work = left.unwrap_or(0); + left.map(|_| ()) +} + +/// Does `p` start and end at one point, with three other points or more? +fn closed(p: &[(i64, i64)]) -> bool { + p.len() > 3 && p.first() == p.last() +} + +/// Twice the area the closed path `p` encloses. +fn twice_area(p: &[(i64, i64)]) -> i128 { + let sum: i128 = p + .windows(2) + .map(|w| match w { + [a, b] => i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1), + _ => 0, + }) + .sum(); + sum.abs() +} + +/// Does `p` lie inside the closed path `ring`, as [`outer`] decides? `None` once `work` is spent. +fn inside(p: &[(i64, i64)], ring: &[(i64, i64)], work: &mut u64) -> Option { + let mut any = false; + for w in p.windows(2) { + let [s, e] = w else { continue }; + spend(work, ring.len() as u64)?; + // Where the segment meets the line without crossing it: its ends and the ring's points on + // it. Between two of these the segment is all inside or all outside. + let mut stops = vec![*s, *e]; + for edge in ring.windows(2) { + let [a, b] = edge else { continue }; + if crosses((*s, *e), (*a, *b)) { + return Some(false); + } + if a != s && a != e && on((*s, *e), *a) { + stops.push(*a); + } + } + let along = |q: &(i64, i64)| { + (i128::from(q.0) - i128::from(s.0)) * (i128::from(e.0) - i128::from(s.0)) + + (i128::from(q.1) - i128::from(s.1)) * (i128::from(e.1) - i128::from(s.1)) + }; + stops.sort_by_key(along); + stops.dedup(); + for part in stops.windows(2) { + let [m, n] = part else { continue }; + spend(work, ring.len() as u64)?; + // The part's middle, doubled so it is whole. + match locate((i128::from(m.0) + i128::from(n.0), i128::from(m.1) + i128::from(n.1)), ring) { + Some(false) => return Some(false), + Some(true) => any = true, + None => {} + } + } + } + Some(any) +} + +/// Which side of the line through `a` and `b` `c` is on: 1 left, -1 right, 0 on it. +fn side(a: (i64, i64), b: (i64, i64), c: (i64, i64)) -> i128 { + let d = (i128::from(b.0) - i128::from(a.0)) * (i128::from(c.1) - i128::from(a.1)) + - (i128::from(b.1) - i128::from(a.1)) * (i128::from(c.0) - i128::from(a.0)); + d.signum() +} + +/// Do segments `u` and `v` cross at a point inside both, each passing from one side of the other +/// to the other side? +fn crosses(u: ((i64, i64), (i64, i64)), v: ((i64, i64), (i64, i64))) -> bool { + side(u.0, u.1, v.0) * side(u.0, u.1, v.1) < 0 && side(v.0, v.1, u.0) * side(v.0, v.1, u.1) < 0 +} + +/// Does `q` lie on segment `u`? +fn on(u: ((i64, i64), (i64, i64)), q: (i64, i64)) -> bool { + let ((x0, y0), (x1, y1)) = u; + side(u.0, u.1, q) == 0 && q.0 >= x0.min(x1) && q.0 <= x0.max(x1) && q.1 >= y0.min(y1) && q.1 <= y0.max(y1) +} + +/// Where the doubled point `q` lies against the closed path `ring`: `Some(true)` inside by the +/// even-odd rule, `Some(false)` outside, `None` on its line. +fn locate(q: (i128, i128), ring: &[(i64, i64)]) -> Option { + let mut inside = false; + for w in ring.windows(2) { + let [a, b] = w else { continue }; + let (a, b) = ((2 * i128::from(a.0), 2 * i128::from(a.1)), (2 * i128::from(b.0), 2 * i128::from(b.1))); + // Which side of the segment's line `q` is on, 0 on it. + let side = (b.0 - a.0) * (q.1 - a.1) - (b.1 - a.1) * (q.0 - a.0); + if side == 0 && q.0 >= a.0.min(b.0) && q.0 <= a.0.max(b.0) && q.1 >= a.1.min(b.1) && q.1 <= a.1.max(b.1) { + return None; + } + // A segment crossing the level of `q` to its right. + if (a.1 > q.1) != (b.1 > q.1) && (side > 0) == (b.1 > a.1) { + inside = !inside; + } + } + Some(inside) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: i64, y0: i64, x1: i64, y1: i64) -> Vec<(i64, i64)> { + vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] + } + + fn nest(paths: &[Vec<(i64, i64)>]) -> Option>> { + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = u64::MAX; + outer(paths, &boxes, &mut work) + } + + #[test] + fn points_inside_outside_and_on_the_line() { + let ring = square(0, 0, 10, 10); + assert_eq!(locate((10, 10), &ring), Some(true)); + assert_eq!(locate((30, 10), &ring), Some(false)); + assert_eq!(locate((10, -2), &ring), Some(false)); + assert_eq!(locate((20, 10), &ring), None); + assert_eq!(locate((0, 0), &ring), None); + } + + #[test] + fn a_path_inside_another_lies_inside_it_and_not_the_other_way() { + let paths = [square(0, 0, 100, 100), square(10, 10, 20, 20), vec![(30, 30), (40, 40)]]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0]])); + } + + #[test] + fn touching_counts_as_inside_and_crossing_does_not() { + // A square with a corner on the outline's left edge, a triangle whose corners lie on the + // outline's edges, and a square that crosses the outline. + let paths = [square(0, 0, 100, 100), square(0, 40, 20, 60), vec![(0, 50), (50, 0), (100, 50), (0, 50)], square(90, 90, 120, 95)]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0], vec![]])); + } + + /// Every point of a copy lies on the other's line, and none inside it. + #[test] + fn copies_of_one_outline_do_not_lie_inside_each_other() { + let paths = [square(0, 0, 10, 10), square(0, 0, 10, 10), vec![(10, 10), (10, 0), (0, 0), (0, 10), (10, 10)]]; + assert_eq!(nest(&paths), Some(vec![vec![], vec![], vec![]])); + } + + /// A line whose ends and middle lie inside an outline but which crosses a slot cut into it. + #[test] + fn a_line_across_a_slot_is_not_inside() { + let slotted = vec![(0, 0), (100, 0), (100, 100), (14, 100), (14, 40), (12, 40), (12, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[slotted, vec![(10, 50), (40, 50)]]), Some(vec![vec![], vec![]])); + } + + /// A line that leaves an outline and comes back through two of its corners, crossing none of + /// its sides, and one that runs along the bottom of a slot. + #[test] + fn a_line_through_corners_is_inside_only_where_it_stays_inside() { + let v_slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (15, 40), (10, 50), (10, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[v_slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![]])); + let slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (10, 50), (10, 100), (0, 100), (0, 0)]; + assert_eq!(nest(&[slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![0]])); + } + + /// An outline that crosses itself encloses no area by its signed sum, yet a line in one of its + /// lobes lies inside it. + #[test] + fn a_line_inside_a_lobe_of_a_crossed_outline_lies_inside_it() { + let bow = vec![(0, 0), (100, 100), (0, 100), (100, 0), (0, 0)]; + assert_eq!(twice_area(&bow), 0); + assert_eq!(nest(&[bow, vec![(40, 80), (60, 80)]]), Some(vec![vec![], vec![0]])); + } + + #[test] + fn a_ring_inside_a_ring_inside_a_ring_lies_inside_both() { + let paths = [square(20, 20, 80, 80), square(0, 0, 100, 100), square(40, 40, 60, 60)]; + assert_eq!(nest(&paths), Some(vec![vec![1], vec![], vec![0, 1]])); + } + + /// 10,000 parts in rows, each with a hole: each hole is tested against the few closed paths + /// near it, not against every part. + #[test] + fn parts_in_rows_are_tested_only_against_the_closed_paths_near_them() { + let mut paths = vec![]; + for row in 0..100 { + for col in 0..100 { + let (x, y) = (col * 30, row * 30); + paths.push(square(x, y, x + 20, y + 20)); + paths.push(square(x + 5, y + 5, x + 15, y + 15)); + } + } + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = 5_000_000; + let found = outer(&paths, &boxes, &mut work); + let want: Vec> = (0..paths.len()).map(|i| if i % 2 == 1 { vec![i - 1] } else { vec![] }).collect(); + assert_eq!(found, Some(want)); + } + + /// 400 closed paths that each cover most of the grid are listed once each, not in every cell + /// they cover. + #[test] + fn closed_paths_covering_many_cells_are_listed_once() { + let mut paths: Vec> = (0..400).map(|i| square(i, i, 1000 + i, 1000 + i)).collect(); + paths.extend((0..400).map(|i| { + let (x, y) = ((i % 20) * 50, (i / 20) * 50); + square(x, y, x + 10, y + 10) + })); + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let rings: Vec = (0..paths.len()).collect(); + let mut work = u64::MAX; + let Some(grid) = Grid::new(&rings, &boxes, &mut work) else { panic!("the budget ran out") }; + assert_eq!(grid.wide, (0..400).collect::>()); + assert!(grid.cells.iter().map(Vec::len).sum::() <= 400 * MAX_CELLS_PER_PATH); + } + + #[test] + fn finding_what_lies_inside_stops_at_its_budget() { + let paths: Vec> = (0..50).map(|i| square(-i, -i, 100 + i, 100 + i)).collect(); + let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect(); + let mut work = 1_000; + assert_eq!(outer(&paths, &boxes, &mut work), None); + assert_eq!(work, 0); + let mut work = u64::MAX; + let found = outer(&paths, &boxes, &mut work); + assert_eq!(found.map(|o| o.iter().map(Vec::len).sum::()), Some(50 * 49 / 2)); + } +} diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs new file mode 100644 index 0000000000..c29ef67532 --- /dev/null +++ b/crates/cad/src/hpgl/write/tests.rs @@ -0,0 +1,1109 @@ +//! HP-GL export: the instructions written, pens, origins, what is cut and left out, limits, and +//! plots read back by the HP-GL reader. + +use std::sync::Arc; + +use kurbo::{PathEl, Shape as _}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, LayerColor, Node, NodeKind, TextObject}; +use vectorcraft_geom::{PathData, Point, Rect, shapes}; + +use super::*; + +/// A 200 × 100 pt document whose first layer holds what `nodes` makes. +fn doc_with(nodes: impl FnOnce(&mut Document) -> Vec) -> Document { + let mut d = Document::new(200.0, 100.0); + let nodes = nodes(&mut d); + let layer = d.layers[0].id; + for n in nodes { + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + d +} + +fn stroked(d: &mut Document, p: PathData, c: Color) -> Node { + Node::path(d.alloc_id(), p, Appearance::basic(Paint::None, Paint::solid(c), 1.0)) +} + +fn filled(d: &mut Document, p: PathData, c: Color) -> Node { + Node::path(d.alloc_id(), p, Appearance::basic(Paint::solid(c), Paint::None, 1.0)) +} + +fn line(a: (f64, f64), b: (f64, f64)) -> PathData { + let mut bp = BezPath::new(); + bp.move_to(a); + bp.line_to(b); + PathData::from_bezpath(&bp) +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> PathData { + shapes::rectangle(Rect::new(x0, y0, x1, y1)) +} + +/// The options with the first artboard as the region. +fn opts(d: &Document) -> HpglOptions { + HpglOptions { region: d.artboards[0].rect, ..HpglOptions::default() } +} + +fn plot(d: &Document, o: &HpglOptions) -> HpglOutput { + match export(d, o) { + Ok(out) => out, + Err(e) => panic!("{e}"), + } +} + +fn text(out: &HpglOutput) -> String { + String::from_utf8(out.bytes.clone()).expect("ASCII") +} + +/// A black square outline, a red line and a blue ellipse filled without a stroke. +fn three() -> Document { + doc_with(|d| { + vec![ + stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK), + stroked(d, line((70.0, 20.0), (150.0, 80.0)), Color::rgb8(255, 0, 0)), + filled(d, shapes::ellipse(Rect::new(70.0, 30.0, 130.0, 70.0)), Color::rgb8(0, 0, 255)), + ] + }) +} + +/// Every instruction in the HP-GL reference guide's form: a two-letter mnemonic, integer +/// parameters separated by commas, and a semicolon (https://support.hp.com/sg-en/document/c01121263). +#[test] +fn a_plot_is_pen_moves_in_plotter_units_from_the_bottom_left() { + let d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)]); + let out = plot(&d, &opts(&d)); + // 1016 units to the inch, y up from the artboard's bottom edge; the square closes. + assert_eq!(text(&out), "IN;PU;SP1;PU141,1270;PD847,1270,847,847,141,847,141,1270;PU;SP0;"); + for i in text(&out).split_terminator(';') { + let (op, params) = i.split_at(2); + assert!(op.bytes().all(|c| c.is_ascii_uppercase()), "{i}"); + assert!(params.is_empty() || params.split(',').all(|v| v.parse::().is_ok()), "{i}"); + } + assert_eq!(out.pens, [[0, 0, 0]]); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); +} + +#[test] +fn the_origin_can_be_the_center() { + let d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)]); + let out = plot(&d, &HpglOptions { origin: Origin::Center, ..opts(&d) }); + // The artboard's center is (100, 50): x from -1270, y from 564 (40 pt up). + assert_eq!(text(&out), "IN;PU;SP1;PU-1270,564;PD-564,564,-564,141,-1270,141,-1270,564;PU;SP0;"); +} + +#[test] +fn each_new_color_is_the_next_pen_and_pens_draw_in_turn() { + let d = doc_with(|d| { + vec![ + stroked(d, line((10.0, 10.0), (20.0, 10.0)), Color::rgb8(255, 0, 0)), + stroked(d, line((10.0, 20.0), (20.0, 20.0)), Color::BLACK), + stroked(d, line((10.0, 30.0), (20.0, 30.0)), Color::rgb8(255, 0, 0)), + ] + }); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens, [[255, 0, 0], [0, 0, 0]]); + assert_eq!(text(&out), "IN;PU;SP1;PU141,1270;PD282,1270;PU141,988;PD282,988;PU;SP2;PU141,1129;PD282,1129;PU;SP0;"); + // A pen table: each color takes the nearest pen's (red is as near black as blue, and black + // comes first). + let table = plot(&d, &HpglOptions { pens: vec![[0, 0, 0], [0, 0, 255]], ..opts(&d) }); + assert_eq!(table.pens, [[0, 0, 0], [0, 0, 255]]); + assert!(text(&table).starts_with("IN;PU;SP1;PU141,1270;"), "{}", text(&table)); + assert!(!text(&table).contains("SP2"), "{}", text(&table)); +} + +#[test] +fn a_filled_path_is_its_closed_outline_and_a_stroke_its_line() { + let d = doc_with(|d| { + let mut open = BezPath::new(); + open.move_to((10.0, 10.0)); + open.line_to((20.0, 10.0)); + open.line_to((20.0, 20.0)); + let open = PathData::from_bezpath(&open); + let both = Node::path(d.alloc_id(), open.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::rgb8(255, 0, 0)), 1.0)); + vec![filled(d, open.clone(), Color::BLACK), stroked(d, open, Color::BLACK), both] + }); + let out = plot(&d, &opts(&d)); + let t = text(&out); + assert!(t.contains("PU141,1270;PD282,1270,282,1129,141,1270;"), "the fill closes: {t}"); + assert!(t.contains("PU141,1270;PD282,1270,282,1129;PU;"), "the stroke doesn't: {t}"); + // A path with a fill and a stroke is closed too, in its stroke's color. + assert_eq!(out.pens, [[0, 0, 0], [255, 0, 0]]); + assert!(t.ends_with("SP2;PU141,1270;PD282,1270,282,1129,141,1270;PU;SP0;"), "{t}"); +} + +/// A gradient mesh is its outline, once, in the average of its points' colors. +#[test] +fn a_gradient_mesh_is_its_outline() { + let d = doc_with(|d| { + let mesh = vectorcraft_doc::live::GradientMesh::from_surface(4, 4, &|u, v| Point::new(10.0 + u * 50.0, 10.0 + v * 50.0), &|u, _| { + if u < 0.5 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 0, 255) } + }); + vec![Node::new(d.alloc_id(), NodeKind::Mesh(mesh))] + }); + let out = plot(&d, &opts(&d)); + let t = text(&out); + assert_eq!(t.matches("PD").count(), 1, "{t}"); + assert!(t.starts_with("IN;PU;SP1;PU"), "{t}"); + // The square's four corners are on the line it draws. + for corner in ["141,1270", "847,1270", "847,564", "141,564"] { + assert!(t.contains(corner), "{corner} in {t}"); + } + let [r, g, b] = out.pens[0]; + assert!(r > 0 && b > 0 && g == 0, "{:?}", out.pens); +} + +/// A square gradient mesh, 30 pt a side, at `x`. +fn mesh_at(x: f64) -> vectorcraft_doc::live::GradientMesh { + vectorcraft_doc::live::GradientMesh::from_surface(4, 4, &|u, v| Point::new(x + u * 30.0, 10.0 + v * 30.0), &|_, _| Color::BLACK) +} + +fn blend_of(d: &mut Document, keys: Vec, steps: u32) -> Node { + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(Arc::new).collect(), spec: Box::new(spec) }) +} + +/// A mesh inside a blend is its outline too: a blend of two meshes with one step between them +/// draws three outlines. A mesh whose every point is at 0% opacity draws nothing. +#[test] +fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() { + let d = doc_with(|d| { + let keys = vec![Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(110.0)))]; + let mut clear = mesh_at(60.0); + clear.points.iter_mut().for_each(|p| p.opacity = 0.0); + vec![blend_of(d, keys, 1), Node::new(d.alloc_id(), NodeKind::Mesh(clear))] + }); + let t = text(&plot(&d, &opts(&d))); + assert_eq!(t.matches("PD").count(), 3, "{t}"); +} + +/// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a +/// warning. +#[test] +fn live_art_past_its_limit_is_left_out() { + let d = doc_with(|d| { + let keys = vec![stroked(d, line((10.0, 10.0), (10.0, 20.0)), Color::BLACK), stroked(d, line((190.0, 10.0), (190.0, 20.0)), Color::BLACK)]; + vec![blend_of(d, keys, 1_200)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == LIVE_LEFT_OUT), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP0;"); +} + +/// A line shorter than a plotter unit draws nothing and takes no pen. +#[test] +fn a_line_that_draws_nothing_takes_no_pen() { + let d = doc_with(|d| { + vec![stroked(d, line((10.0, 10.0), (10.01, 10.0)), Color::rgb8(255, 0, 0)), stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens, [[0, 0, 0]]); + assert!(text(&out).starts_with("IN;PU;SP1;PU141,1270;"), "{}", text(&out)); + let two = plot(&d, &HpglOptions { version: Version::Hpgl2, ..opts(&d) }); + assert!(two.bytes.starts_with(b"IN;NP2;PC1,0,0,0;PU;SP1;PE"), "{:?}", String::from_utf8_lossy(&two.bytes)); +} + +/// The plots of one export share the pens: a color is the same pen in each, numbered in the +/// order the plots first draw in it. +#[test] +fn the_plots_of_one_export_share_their_pens() { + let d = doc_with(|d| { + vec![ + stroked(d, line((10.0, 10.0), (20.0, 10.0)), Color::BLACK), + stroked(d, line((110.0, 10.0), (120.0, 10.0)), Color::rgb8(255, 0, 0)), + stroked(d, line((110.0, 20.0), (120.0, 20.0)), Color::BLACK), + ] + }); + let regions = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 200.0, 100.0)]; + let plots = export_regions(&d, &HpglOptions::default(), ®ions).unwrap(); + assert_eq!(plots.len(), 2); + for p in &plots { + assert_eq!(p.pens, [[0, 0, 0], [255, 0, 0]]); + } + assert_eq!(text(&plots[0]), "IN;PU;SP1;PU141,1270;PD282,1270;PU;SP0;"); + assert_eq!(text(&plots[1]), "IN;PU;SP1;PU141,1129;PD282,1129;PU;SP2;PU141,1270;PD282,1270;PU;SP0;"); +} + +#[test] +fn hidden_and_non_printing_art_is_left_out() { + let mut d = doc_with(|d| { + let mut hidden = stroked(d, rect(10.0, 10.0, 20.0, 20.0), Color::BLACK); + hidden.visible = false; + let none = Node::path(d.alloc_id(), rect(30.0, 10.0, 40.0, 20.0), Appearance::basic(Paint::None, Paint::None, 1.0)); + vec![hidden, none] + }); + let mut layer = Node::layer(d.alloc_id(), "Notes", LayerColor::Preset(1)); + if let NodeKind::Layer { printable, .. } = &mut layer.kind { + *printable = false; + } + let art = stroked(&mut d, rect(50.0, 10.0, 60.0, 20.0), Color::BLACK); + layer.children_mut().unwrap().push(Arc::new(art)); + d.layers.push(Arc::new(layer)); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); +} + +/// Hidden and template layers, guides of either kind and placed images draw nothing; an image +/// comes back as a warning. +#[test] +fn layers_guides_and_images_that_draw_nothing_are_left_out() { + let mut d = doc_with(|d| { + let mut guide = stroked(d, rect(10.0, 10.0, 20.0, 20.0), Color::BLACK); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let ruler = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 50.0, artboard: None }); + let image = vectorcraft_doc::ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![ruler, guide, Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)))] + }); + let hidden = d.add_layer(Some("Notes")); + let template = d.add_layer(Some("Tracing")); + for l in [hidden, template] { + let n = stroked(&mut d, rect(30.0, 10.0, 40.0, 20.0), Color::BLACK); + d.insert(Some(l), 0, n).unwrap(); + } + if let Some(n) = d.node_mut(hidden) { + n.visible = false; + } + if let Some(NodeKind::Layer { template, .. }) = d.node_mut(template).map(|n| &mut n.kind) { + *template = true; + } + let out = plot(&d, &opts(&d)); + assert_eq!(text(&out), "IN;PU;SP0;"); + assert_eq!(out.warnings, [IMAGES]); +} + +/// A non-printing layer's Crop Marks are left out with the layer, and so is a template layer's. +#[test] +fn the_crop_marks_of_a_layer_left_out_are_left_out() { + for template in [false, true] { + let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK)]); + let layer = d.layers[0].id; + if let Some(n) = d.node_mut(layer) { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true }); + if let NodeKind::Layer { printable, template: t, .. } = &mut n.kind { + (*printable, *t) = (template, template); + } + } + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;", "template: {template}"); + } +} + +/// A guide's Crop Marks are left out with the guide, in the layers and in a symbol's art. +#[test] +fn the_crop_marks_of_a_guide_are_left_out() { + let guide = |d: &mut Document| { + let mut g = stroked(d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true }); + if let NodeKind::Path { guide, .. } = &mut g.kind { + *guide = true; + } + g + }; + let d = doc_with(|d| { + let g = guide(d); + vec![Node::group(d.alloc_id(), vec![Arc::new(g)])] + }); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); + let mut d = Document::new(200.0, 100.0); + let g = guide(&mut d); + let art = Node::group(d.alloc_id(), vec![Arc::new(g)]); + let d = symbol_doc(art, |_| {}); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); +} + +/// Inline graphics in type are left out with a warning. +#[test] +fn inline_graphics_in_type_are_left_out_with_a_warning() { + let d = doc_with(|d| { + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let mut t = TextObject::point(Point::new(10.0, 60.0), "O", style.clone()); + t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("mark"), style)); + vec![Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)))] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == INLINE_GRAPHICS), "{:?}", out.warnings); +} + +/// A gradient's pen is the average of its stops' colors. +#[test] +fn a_gradient_takes_the_average_of_its_stops() { + let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + g.gradient.stops[0].color = Color::rgb8(255, 0, 0); + g.gradient.stops[1].color = Color::rgb8(0, 0, 255); + let d = + doc_with(|d| vec![Node::path(d.alloc_id(), rect(10.0, 10.0, 60.0, 40.0), Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 1.0))]); + assert_eq!(plot(&d, &opts(&d)).pens, [[128, 0, 128]]); +} + +/// An object or group at 0% opacity shows nothing, and a fill or stroke at 0% opacity gives a +/// path no color: here only the blue fill's outline is drawn. +#[test] +fn art_at_no_opacity_is_left_out() { + let (red, green, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 255, 0), Color::rgb8(0, 0, 255)); + let d = doc_with(|d| { + let mut faded = stroked(d, rect(10.0, 10.0, 20.0, 20.0), red); + faded.opacity = 0.0; + let inner = stroked(d, line((30.0, 10.0), (40.0, 10.0)), green); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(inner)]); + group.opacity = 0.0; + let mut clear_fill = filled(d, rect(10.0, 30.0, 20.0, 40.0), green); + let mut fill_and_clear_stroke = + Node::path(d.alloc_id(), rect(50.0, 10.0, 60.0, 20.0), Appearance::basic(Paint::solid(blue), Paint::solid(red), 1.0)); + for item in clear_fill.appearance.items.iter_mut().chain(fill_and_clear_stroke.appearance.items.iter_mut()) { + match item { + AppearanceItem::Fill(f) if f.paint == Paint::solid(green) => f.opacity = 0.0, + AppearanceItem::Stroke(s) => s.opacity = 0.0, + _ => {} + } + } + vec![faded, group, clear_fill, fill_and_clear_stroke] + }); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens, [[0, 0, 255]]); + assert_eq!(text(&out).matches("PD").count(), 1, "{}", text(&out)); +} + +/// A pattern's pen is the color of its first visible solid fill: a hidden tile object, one at 0% +/// opacity and a fill at 0% opacity are skipped. +#[test] +fn a_pattern_takes_the_color_of_its_first_visible_fill() { + let mut d = doc_with(|_| vec![]); + let mut hidden = filled(&mut d, rect(0.0, 0.0, 5.0, 5.0), Color::rgb8(255, 0, 0)); + hidden.visible = false; + let mut faded = filled(&mut d, rect(0.0, 5.0, 5.0, 10.0), Color::rgb8(0, 255, 0)); + faded.opacity = 0.0; + let mut clear_fill = filled(&mut d, rect(5.0, 5.0, 10.0, 10.0), Color::rgb8(255, 255, 0)); + for item in &mut clear_fill.appearance.items { + if let AppearanceItem::Fill(f) = item { + f.opacity = 0.0; + } + } + let shown = filled(&mut d, rect(5.0, 0.0, 10.0, 5.0), Color::rgb8(0, 0, 255)); + let art = [hidden, faded, clear_fill, shown].map(Arc::new).to_vec(); + d.patterns.push(vectorcraft_doc::PatternDef::new("tiles", art)); + let path = Node::path( + d.alloc_id(), + rect(10.0, 10.0, 50.0, 50.0), + Appearance::basic(Paint::Pattern { pattern: "tiles".into(), xf: Default::default() }, Paint::None, 1.0), + ); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, path).unwrap(); + assert_eq!(plot(&d, &opts(&d)).pens, [[0, 0, 255]]); +} + +#[test] +fn art_is_cut_at_the_artboard_and_by_clipping_masks() { + let d = doc_with(|d| { + let across = stroked(d, line((-50.0, 50.0), (250.0, 50.0)), Color::BLACK); + let clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::default()); + let clipped = stroked(d, line((0.0, 30.0), (200.0, 30.0)), Color::BLACK); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![across, group] + }); + let t = text(&plot(&d, &opts(&d))); + assert_eq!(t, "IN;PU;SP1;PU0,706;PD2822,706;PU282,988;PD564,988;PU;SP0;"); +} + +#[test] +fn type_is_drawn_as_its_outlines() { + let d = doc_with(|d| { + let style = CharStyle { size: 30.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + vec![Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "Ol", style))))] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TEXT_OUTLINES), "{:?}", out.warnings); + // A pen-up move to each contour (the O's two and the l's one), and the two around the pen. + let t = text(&out); + assert!(t.matches("PU").count() >= 5, "{t}"); +} + +#[test] +fn an_empty_or_zero_length_plot_has_no_moves() { + let empty = Document::new(200.0, 100.0); + assert_eq!(text(&plot(&empty, &opts(&empty))), "IN;PU;SP0;"); + let d = + doc_with(|d| vec![stroked(d, line((10.0, 10.0), (10.0, 10.0)), Color::BLACK), stroked(d, line((10.0, 10.0), (10.01, 10.0)), Color::BLACK)]); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;"); + let bad = HpglOptions { region: Rect::new(0.0, 0.0, 0.0, 10.0), ..HpglOptions::default() }; + assert_eq!(export(&d, &bad).err().as_deref(), Some("the export region is empty")); + let nan = HpglOptions { region: Rect::new(0.0, 0.0, f64::NAN, 10.0), ..HpglOptions::default() }; + assert!(export(&d, &nan).is_err()); +} + +/// A tolerance outside its range and a pen table of more than 255 pens are errors, not changed. +#[test] +fn bad_options_are_errors() { + let d = three(); + for tolerance in [0.0, 0.009, 10.01, f64::NAN, f64::INFINITY] { + let o = HpglOptions { tolerance, ..opts(&d) }; + assert_eq!(export(&d, &o).err().as_deref(), Some("the curve tolerance must be from 0.01 to 10 points"), "{tolerance}"); + } + for tolerance in [0.01, 10.0] { + assert!(export(&d, &HpglOptions { tolerance, ..opts(&d) }).is_ok(), "{tolerance}"); + } + let o = HpglOptions { pens: vec![[0, 0, 0]; MAX_PENS + 1], ..opts(&d) }; + assert_eq!(export(&d, &o).err().as_deref(), Some("the pen table holds more than 255 pens")); + assert!(export(&d, &HpglOptions { pens: vec![[0, 0, 0]; MAX_PENS], ..opts(&d) }).is_ok()); +} + +#[test] +fn art_past_the_plotter_range_is_cut_off() { + let d = doc_with(|d| vec![stroked(d, line((0.0, 50.0), (1e9, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region: Rect::new(0.0, 0.0, 1e9, 100.0), ..HpglOptions::default() }); + assert!(out.warnings.iter().any(|w| w == OUT_OF_RANGE), "{:?}", out.warnings); + assert_eq!(text(&out), format!("IN;PU;SP1;PU0,706;PD{MAX_COORD},706;PU;SP0;")); + // Art past the range but off the region asked for would be cut off anyway: no warning. + let d = doc_with(|d| vec![stroked(d, line((-1e9, 50.0), (10.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region: Rect::new(0.0, 0.0, 1e9, 100.0), ..HpglOptions::default() }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU0,706;PD141,706;PU;SP0;"); +} + +/// HP-GL past 16-bit coordinates is written as it is, with a warning; HP-GL/2 gets none. +#[test] +fn hpgl_past_16_bit_coordinates_warns() { + let region = Rect::new(-2400.0, 0.0, 2400.0, 100.0); + // Past 32,767 from the bottom-left corner, within the range from the center. + let d = doc_with(|d| vec![stroked(d, line((-2000.0, 50.0), (2000.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region, ..HpglOptions::default() }); + assert_eq!(out.warnings, [PAST_CLASSIC_RANGE]); + assert_eq!(text(&out), "IN;PU;SP1;PU5644,706;PD62089,706;PU;SP0;"); + let out = plot(&d, &HpglOptions { region, origin: Origin::Center, ..HpglOptions::default() }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU-28222,0;PD28222,0;PU;SP0;"); + // Past −32,768 and 32,767 from the center. + let d = doc_with(|d| vec![stroked(d, line((-2400.0, 50.0), (2400.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region, origin: Origin::Center, ..HpglOptions::default() }); + assert_eq!(out.warnings, [PAST_CLASSIC_RANGE]); + assert_eq!(text(&out), "IN;PU;SP1;PU-33867,0;PD33867,0;PU;SP0;"); + let out = plot(&d, &HpglOptions { region, origin: Origin::Center, version: Version::Hpgl2, ..HpglOptions::default() }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); +} + +#[test] +fn a_plot_stops_at_its_point_budget() { + let d = doc_with(|d| (0..MAX_POINTS / 4).map(|i| stroked(d, rect(1.0, 1.0, 2.0 + (i % 50) as f64, 3.0), Color::BLACK)).collect()); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); + assert!(text(&out).matches("PU").count() <= MAX_POINTS / 5 + 3); +} + +/// The points a plain plot moves through. +fn moves(t: &str) -> usize { + t.split_terminator(';') + .filter(|i| i.starts_with("PU") || i.starts_with("PD")) + .map(|i| i[2..].split(',').filter(|v| !v.is_empty()).count() / 2) + .sum() +} + +#[test] +fn one_path_longer_than_the_budget_is_cut_at_it() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((1.0, 1.0)); + for i in 0..MAX_POINTS + 10 { + bp.line_to((if i % 2 == 0 { 2.0 } else { 1.0 }, 1.0 + (i % 50) as f64)); + } + vec![stroked(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); + let n = moves(&text(&out)); + assert!(n > 2 && n <= MAX_POINTS, "{n}"); +} + +/// A path whose flattening stops at the budget while its moves so far lie off the artboard: the +/// rest, over the artboard, is left out with a warning. +#[test] +fn a_path_cut_short_by_the_budget_warns() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((-50.0, 10.0)); + for i in 0..MAX_POINTS * 4 + 10 { + bp.line_to((if i % 2 == 0 { -40.0 } else { -50.0 }, 10.0)); + } + bp.line_to((50.0, 50.0)); + bp.line_to((60.0, 50.0)); + vec![stroked(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); +} + +/// A filled path cut short by the budget is not closed: the move from where it stopped back to its +/// start is not on its outline. Only its first move, along y = 50 off the artboard's left edge, +/// is drawn. +#[test] +fn a_filled_path_cut_short_stays_open() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((10.0, 50.0)); + bp.line_to((-40.0, 50.0)); + for i in 0..MAX_POINTS * 4 + 10 { + bp.line_to((if i % 2 == 0 { -40.0 } else { -50.0 }, 10.0)); + } + vec![filled(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU141,706;PD0,706;PU;SP0;"); +} + +/// A blend's steps that its bent spine turns onto the region plotted are drawn, although its keys +/// and spine lie off it. +#[test] +fn blend_steps_a_spine_turns_onto_the_region_are_drawn() { + let d = doc_with(|d| { + let keys = + vec![stroked(d, line((-400.0, -200.0), (200.0, -200.0)), Color::BLACK), stroked(d, line((-560.0, -60.0), (40.0, -60.0)), Color::BLACK)]; + let mut spine = BezPath::new(); + spine.move_to((-100.0, -200.0)); + spine.quad_to((-100.0, -60.0), (-260.0, -60.0)); + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Steps(20), + spine: Some(PathData::from_bezpath(&spine)), + orientation: vectorcraft_doc::BlendOrientation::AlignToPath, + ..Default::default() + }; + vec![Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(Arc::new).collect(), spec: Box::new(spec) })] + }); + // The keys and spine lie above y = -55; the steps turned along the spine cross this area. + let region = Rect::new(-300.0, 0.0, -200.0, 50.0); + let t = text(&plot(&d, &HpglOptions { region, ..HpglOptions::default() })); + assert!(t.contains("PD"), "{t}"); +} + +/// A closed path that starts on the artboard, leaves it and comes back is one line, with no +/// pen lift where it started. +#[test] +fn a_closed_path_cut_at_the_artboard_is_one_line() { + let d = doc_with(|d| { + let mut bp = BezPath::new(); + bp.move_to((150.0, 10.0)); + bp.line_to((250.0, 10.0)); + bp.line_to((250.0, 50.0)); + bp.line_to((150.0, 50.0)); + bp.close_path(); + vec![stroked(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + let t = text(&plot(&d, &opts(&d))); + assert_eq!(t, "IN;PU;SP1;PU2822,706;PD2117,706,2117,1270,2822,1270;PU;SP0;"); +} + +/// A clipping path that paints is drawn once: where its fill paints (before the art it clips), +/// or where its stroke paints (after it). +#[test] +fn a_clipping_path_is_drawn_where_it_paints() { + let clip_doc = |fill: Paint, stroke: Paint| { + doc_with(|d| { + let clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::basic(fill, stroke, 1.0)); + let clipped = stroked(d, line((0.0, 30.0), (200.0, 30.0)), Color::BLACK); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }) + }; + let red = Paint::solid(Color::rgb8(255, 0, 0)); + let filled = clip_doc(red.clone(), Paint::None); + assert_eq!(plot(&filled, &opts(&filled)).pens, [[255, 0, 0], [0, 0, 0]]); + let stroked = clip_doc(Paint::None, red.clone()); + assert_eq!(plot(&stroked, &opts(&stroked)).pens, [[0, 0, 0], [255, 0, 0]]); + let both = clip_doc(Paint::solid(Color::rgb8(0, 0, 255)), red); + let out = plot(&both, &opts(&both)); + assert_eq!(out.pens, [[0, 0, 0], [255, 0, 0]], "drawn once, in its stroke's color"); + // Two pen changes, a move to each of the two paths, and the last pen up. + assert_eq!(text(&out).matches("PU").count(), 5, "{}", text(&out)); + // A stroke at 0% opacity isn't drawn: the clipping path is drawn in its fill, below. + let faded = doc_with(|d| { + let mut clip = Node::path( + d.alloc_id(), + rect(20.0, 20.0, 40.0, 40.0), + Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0), + ); + for item in &mut clip.appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.opacity = 0.0; + } + } + let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }); + assert_eq!(plot(&faded, &opts(&faded)).pens, [[0, 0, 255], [0, 0, 0]]); + // An open clipping path with a fill and a stroke is drawn closed, as other filled paths are. + let mut open = BezPath::new(); + open.move_to((20.0, 20.0)); + open.line_to((40.0, 20.0)); + open.line_to((40.0, 40.0)); + let open = PathData::from_bezpath(&open); + let open_doc = doc_with(|d| { + let clip = Node::path(d.alloc_id(), open, Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0)); + let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }); + let t = text(&plot(&open_doc, &opts(&open_doc))); + assert!(t.ends_with("SP2;PU282,1129;PD564,1129,564,847,282,1129;PU;SP0;"), "{t}"); +} + +/// A symbol `art` and an instance of it at its place. +fn symbol_doc(art: Node, instance: impl FnOnce(&mut Node)) -> Document { + let mut d = doc_with(|d| { + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + instance(&mut n); + vec![n] + }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "s".into(), art: Arc::new(art) }); + d +} + +/// Symbols nested more than 8 deep are left out with a warning. +#[test] +fn symbols_nested_too_deep_are_left_out_with_a_warning() { + let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s9".into(), xf: Affine::IDENTITY })]); + let art = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "s0".into(), art: Arc::new(art) }); + for i in 1..10 { + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("s{}", i - 1), xf: Affine::IDENTITY }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("s{i}"), art: Arc::new(inner) }); + } + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == TOO_DEEP), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP0;"); +} + +/// A symbol instance stained by its fill draws in the stained color. +#[test] +fn a_stained_symbol_instance_takes_its_stain() { + let mut d = Document::new(200.0, 100.0); + let art = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + let d = symbol_doc(art, |n| n.appearance = Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 1.0).into()); + assert_eq!(plot(&d, &opts(&d)).pens, [[255, 0, 0]]); +} + +/// The geometry effects in a symbol's art apply: a line moved 30 pt right by a Transform effect. +#[test] +fn a_symbol_draws_its_art_with_its_effects() { + let mut d = Document::new(200.0, 100.0); + let mut art = stroked(&mut d, line((10.0, 10.0), (20.0, 10.0)), Color::BLACK); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 30.0}), + visible: true, + }); + let d = symbol_doc(art, |_| {}); + assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP1;PU564,1270;PD706,1270;PU;SP0;"); +} + +/// Art an effect moves onto the artboard from off it is drawn, for an instance on its own and +/// one in a group: the bounds that skip art off the artboard don't measure symbol effects. +#[test] +fn symbol_art_an_effect_moves_onto_the_artboard_is_drawn() { + let mut d = Document::new(200.0, 100.0); + let mut art = stroked(&mut d, line((-30.0, 10.0), (-20.0, 10.0)), Color::BLACK); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"moveH": 40.0}), + visible: true, + }); + let alone = symbol_doc(art.clone(), |_| {}); + assert_eq!(text(&plot(&alone, &opts(&alone))), "IN;PU;SP1;PU141,1270;PD282,1270;PU;SP0;"); + let mut grouped = doc_with(|d| { + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + vec![Node::group(d.alloc_id(), vec![Arc::new(n)])] + }); + grouped.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "s".into(), art: Arc::new(art.clone()) }); + assert_eq!(text(&plot(&grouped, &opts(&grouped))), "IN;PU;SP1;PU141,1270;PD282,1270;PU;SP0;"); + // Other art off the artboard is still skipped: a blend there doesn't spend the live art's + // limit (1,000 objects in tests) before the blend on the artboard. + let mut d = doc_with(|d| { + let off = + vec![stroked(d, line((-500.0, 10.0), (-500.0, 20.0)), Color::BLACK), stroked(d, line((-400.0, 10.0), (-400.0, 20.0)), Color::BLACK)]; + let on = vec![stroked(d, line((10.0, 10.0), (10.0, 20.0)), Color::BLACK), stroked(d, line((30.0, 10.0), (30.0, 20.0)), Color::BLACK)]; + vec![blend_of(d, off, 1_200), blend_of(d, on, 1)] + }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "unused".into(), art: Arc::new(art) }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(text(&out).matches("PD").count(), 3, "{}", text(&out)); +} + +/// A rectangle with `per_side` straight moves along each side. +fn fine_rect(x0: f64, y0: f64, x1: f64, y1: f64, per_side: u32) -> PathData { + let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]; + let mut bp = BezPath::new(); + bp.move_to(corners[0]); + for (k, a) in corners.iter().enumerate() { + let b = corners[(k + 1) % 4]; + for i in 1..=per_side { + let t = f64::from(i) / f64::from(per_side); + bp.line_to((a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)); + } + } + bp.close_path(); + PathData::from_bezpath(&bp) +} + +/// Nested clipping masks of 6,000 points each pass the 10,000 points masks may hold together +/// in tests: the inner one is left out with a warning, and the line is cut by the outer one only. +#[test] +fn masks_past_their_point_budget_are_left_out() { + let d = doc_with(|d| { + let clip_group = |d: &mut Document, mask: PathData, art: Node| { + let mask = Node::path(d.alloc_id(), mask, Appearance::basic(Paint::None, Paint::None, 1.0)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + group + }; + let across = Node::path(d.alloc_id(), line((0.0, 50.0), (200.0, 50.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let inner = clip_group(d, fine_rect(50.0, 30.0, 150.0, 70.0, 1500), across); + vec![clip_group(d, fine_rect(10.0, 10.0, 190.0, 90.0, 1500), inner)] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == MASK_POINTS), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP1;PU141,706;PD2681,706;PU;SP0;"); +} + +/// A line through the 500 teeth of a comb-shaped mask crosses its edges about 1,000 times, and +/// each piece between crossings is tested against all 2,002 edges: that spends the clipping +/// budget, so the line is drawn whole with a warning. +#[test] +fn a_mask_crossed_many_times_spends_the_clipping_budget() { + let d = doc_with(|d| { + let mut pts = vec![]; + for i in 0..500 { + let x = f64::from(i) * 0.4; + pts.extend([(x, 20.0), (x + 0.2, 20.0), (x + 0.2, 50.0), (x + 0.4, 50.0)]); + } + pts.extend([(200.0, 80.0), (0.0, 80.0)]); + let mut bp = BezPath::new(); + bp.move_to(pts[0]); + pts[1..].iter().for_each(|&p| bp.line_to(p)); + bp.close_path(); + let comb = Node::path(d.alloc_id(), PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::None, 1.0)); + let clipped = stroked(d, line((0.5, 35.0), (199.5, 35.0)), Color::BLACK); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(comb), Arc::new(clipped)]); + if let NodeKind::Group { clip, .. } = &mut group.kind { + *clip = true; + } + vec![group] + }); + let out = plot(&d, &opts(&d)); + assert!(out.warnings.iter().any(|w| w == CLIP_WORK), "{:?}", out.warnings); + assert_eq!(text(&out).matches("PD").count(), 1, "{}", text(&out)); +} + +#[test] +fn more_colors_than_pens_share_the_nearest_pen() { + let d = doc_with(|d| (0..300).map(|i| stroked(d, rect(1.0, 1.0, 5.0, 5.0), Color::rgb8((i % 256) as u8, (i / 256) as u8, 7))).collect()); + let out = plot(&d, &opts(&d)); + assert_eq!(out.pens.len(), MAX_PENS); + assert!(out.warnings.iter().any(|w| w == MANY_COLORS), "{:?}", out.warnings); +} + +#[test] +fn sorting_draws_the_nearest_path_next() { + let d = doc_with(|d| { + vec![ + stroked(d, line((150.0, 90.0), (150.0, 80.0)), Color::BLACK), + stroked(d, line((10.0, 80.0), (10.0, 90.0)), Color::BLACK), + stroked(d, line((80.0, 90.0), (80.0, 80.0)), Color::BLACK), + ] + }); + let unsorted = text(&plot(&d, &opts(&d))); + assert_eq!(unsorted, "IN;PU;SP1;PU2117,141;PD2117,282;PU141,282;PD141,141;PU1129,141;PD1129,282;PU;SP0;"); + // From the origin: the left line drawn backwards from its lower end, then the middle and the + // right one from the end the pen is nearest. + let sorted = text(&plot(&d, &HpglOptions { sort: true, ..opts(&d) })); + assert_eq!(sorted, "IN;PU;SP1;PU141,141;PD141,282;PU1129,282;PD1129,141;PU2117,141;PD2117,282;PU;SP0;"); +} + +/// A closed path is as near as its nearest point, and starts there. +#[test] +fn sorting_measures_a_closed_path_by_its_nearest_point() { + let d = doc_with(|d| vec![stroked(d, rect(40.0, 60.0, 50.0, 70.0), Color::BLACK), stroked(d, rect(10.0, 10.0, 190.0, 90.0), Color::BLACK)]); + let t = text(&plot(&d, &HpglOptions { sort: true, ..opts(&d) })); + // The large square's bottom-left corner is nearer the origin than any point of the small one. + assert_eq!(t, "IN;PU;SP1;PU141,141;PD141,1270,2681,1270,2681,141,141,141;PU564,423;PD564,564,706,564,706,423,564,423;PU;SP0;"); +} + +#[test] +fn sorting_stops_at_its_budget_and_keeps_every_path() { + let d = doc_with(|d| (0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK)).collect()); + let out = plot(&d, &HpglOptions { sort: true, ..opts(&d) }); + assert!(out.warnings.iter().any(|w| w == UNSORTED), "{:?}", out.warnings); + assert_eq!(text(&out).matches("PD").count(), 600); +} + +/// `x` points in plotter units. +fn plu(x: f64) -> i64 { + (x * 1016.0 / 72.0).round() as i64 +} + +/// The left edge of each path a plain HP-GL plot draws, in drawing order (plotter units). +fn lefts(out: &HpglOutput) -> Vec { + let mut lefts: Vec = vec![]; + for i in text(out).split_terminator(';') { + let xs = i.get(2..).unwrap_or_default().split(',').step_by(2).filter_map(|x| x.parse::().ok()); + match i.get(..2) { + Some("PU") => lefts.extend(xs.min()), + Some("PD") => { + if let (Some(l), Some(x)) = (lefts.last_mut(), xs.min()) { + *l = (*l).min(x); + } + } + _ => {} + } + } + lefts +} + +/// A letter O made as one path: its outline, then its counter. +#[test] +fn inside_first_cuts_a_letters_counter_before_its_outline() { + let d = doc_with(|d| { + let mut bp = rect(10.0, 10.0, 60.0, 90.0).to_bezpath(); + bp.extend(shapes::ellipse(Rect::new(25.0, 30.0, 45.0, 70.0)).to_bezpath()); + vec![filled(d, PathData::from_bezpath(&bp), Color::BLACK)] + }); + assert_eq!(lefts(&plot(&d, &opts(&d))), [plu(10.0), plu(25.0)]); + assert_eq!(lefts(&plot(&d, &HpglOptions { inside_first: true, ..opts(&d) })), [plu(25.0), plu(10.0)]); +} + +/// A part drawn before its two holes: the holes are cut first, nearest first with `sort`. +#[test] +fn a_part_with_two_holes_is_cut_holes_first() { + let d = doc_with(|d| { + vec![ + stroked(d, rect(10.0, 10.0, 190.0, 90.0), Color::BLACK), + stroked(d, shapes::ellipse(Rect::new(160.0, 40.0, 180.0, 60.0)), Color::BLACK), + stroked(d, shapes::ellipse(Rect::new(20.0, 40.0, 40.0, 60.0)), Color::BLACK), + ] + }); + let (part, right, left) = (plu(10.0), plu(160.0), plu(20.0)); + assert_eq!(lefts(&plot(&d, &opts(&d))), [part, right, left]); + assert_eq!(lefts(&plot(&d, &HpglOptions { inside_first: true, ..opts(&d) })), [right, left, part]); + // Sorting alone starts at the part's corner, nearest the origin; inside first, the nearest + // hole comes first, then the other, then the part. + assert_eq!(lefts(&plot(&d, &HpglOptions { sort: true, ..opts(&d) })), [part, left, right]); + let both = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) }); + assert_eq!(lefts(&both), [left, right, part]); + assert!(both.warnings.is_empty(), "{:?}", both.warnings); +} + +/// Rings inside rings are cut innermost first, and a ring with nothing inside it keeps its place +/// in paint order. +#[test] +fn nested_rings_are_cut_innermost_first() { + let d = doc_with(|d| { + vec![ + stroked(d, rect(120.0, 10.0, 190.0, 90.0), Color::BLACK), + stroked(d, rect(10.0, 10.0, 100.0, 90.0), Color::BLACK), + stroked(d, rect(20.0, 20.0, 90.0, 80.0), Color::BLACK), + stroked(d, rect(30.0, 30.0, 80.0, 70.0), Color::BLACK), + ] + }); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert_eq!(lefts(&out), [plu(120.0), plu(30.0), plu(20.0), plu(10.0)]); +} + +/// Each pen's paths are ordered among themselves: a red square inside a black part is drawn with +/// the red pen, after the black part. +#[test] +fn inside_first_orders_each_pens_paths() { + let d = doc_with(|d| { + vec![ + stroked(d, rect(10.0, 10.0, 190.0, 90.0), Color::BLACK), + stroked(d, rect(20.0, 20.0, 40.0, 40.0), Color::rgb8(255, 0, 0)), + stroked(d, rect(50.0, 20.0, 70.0, 40.0), Color::BLACK), + ] + }); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert_eq!(lefts(&out), [plu(50.0), plu(10.0), plu(20.0)]); +} + +/// Finding which of 100 nested rings lie inside which is past the budget: they are drawn in +/// paint order, with a warning. +#[test] +fn inside_first_past_its_budget_draws_in_paint_order() { + let d = doc_with(|d| (0..100).map(|i| stroked(d, rect(1.0 + 0.4 * f64::from(i), 10.0, 199.0, 90.0), Color::BLACK)).collect()); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert_eq!(out.warnings, [UNNESTED]); + let l = lefts(&out); + assert_eq!(l.len(), 100); + assert!(l.windows(2).all(|w| w[0] <= w[1]), "{l:?}"); + // With `sort` too, the budget is spent before sorting starts: paint order, with both warnings. + let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) }); + assert_eq!(out.warnings, [UNNESTED, UNSORTED]); + assert_eq!(lefts(&out), l); +} + +/// Sorting 600 lines inside two rings runs out of work: every path is drawn, the inner ring and +/// then the outer one last. +#[test] +fn inside_first_past_its_sorting_budget_keeps_the_rings_last() { + let d = doc_with(|d| { + let mut v = vec![stroked(d, rect(0.5, 5.0, 150.0, 30.0), Color::BLACK), stroked(d, rect(0.7, 7.0, 140.0, 25.0), Color::BLACK)]; + v.extend((0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK))); + v + }); + let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) }); + assert_eq!(out.warnings, [UNSORTED_INSIDE]); + let l = lefts(&out); + assert_eq!(l.len(), 602); + assert_eq!(l.get(600..), Some(&[plu(0.7), plu(0.5)][..])); +} + +/// Without `sort`, 1,000 lines inside a ring are drawn in paint order and the ring after them, +/// within the budget. +#[test] +fn inside_first_alone_keeps_paint_order_for_many_paths() { + let d = doc_with(|d| { + let mut v = vec![stroked(d, rect(0.5, 5.0, 199.0, 30.0), Color::BLACK)]; + v.extend((0..1000).map(|i| stroked(d, line((1.0 + 0.19 * f64::from(i), 10.0), (1.0 + 0.19 * f64::from(i), 20.0)), Color::BLACK))); + v + }); + let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) }); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let l = lefts(&out); + assert_eq!(l.len(), 1001); + assert_eq!(l.last(), Some(&plu(0.5))); + assert!(l.get(..1000).is_some_and(|l| l.windows(2).all(|w| w[0] < w[1])), "{l:?}"); +} + +#[test] +fn art_wholly_past_the_plotter_range_is_cut_off_with_a_warning() { + let d = doc_with(|d| vec![stroked(d, line((7e8, 50.0), (7e8 + 10.0, 50.0)), Color::BLACK)]); + let out = plot(&d, &HpglOptions { region: Rect::new(0.0, 0.0, 1e9, 100.0), ..HpglOptions::default() }); + assert!(out.warnings.iter().any(|w| w == OUT_OF_RANGE), "{:?}", out.warnings); + assert_eq!(text(&out), "IN;PU;SP0;"); +} + +/// The reference guide's example of an encoded number: 10,525 is written as the bytes 121, 71 +/// and 196 (https://support.hp.com/sg-en/document/c01121263). +#[test] +fn encoded_numbers_follow_the_reference_guide() { + let mut out = vec![]; + pe_number(&mut out, 10_525); + assert_eq!(out, [121, 71, 196]); + out.clear(); + pe_number(&mut out, -1); + pe_number(&mut out, 0); + // The sign in the low bit: -1 is 3. + assert_eq!(out, [194, 191]); +} + +#[test] +fn hpgl2_writes_the_palette_and_encoded_polylines() { + let out = plot(&three(), &HpglOptions { version: Version::Hpgl2, ..opts(&three()) }); + let b = &out.bytes; + assert!(b.starts_with(b"IN;NP4;PC1,0,0,0;PC2,255,0,0;PC3,0,0,255;PU;SP1;PE<="), "{:?}", String::from_utf8_lossy(b)); + assert!(b.ends_with(b";PU;SP0;")); + assert_eq!(b.windows(4).filter(|w| w == b";PE<").count(), 3, "one encoded polyline per pen"); + // Encoded moves take fewer bytes than the same moves written as text. + let plain = plot(&three(), &opts(&three())); + assert!(b.len() < plain.bytes.len(), "{} against {}", b.len(), plain.bytes.len()); +} + +/// A move longer than 8,388,607 units is written absolute (`=`), so every number stays in the +/// range: here from about −5,000,000 to +5,000,000 units around a centered origin. +#[test] +fn hpgl2_writes_a_move_past_the_range_absolute() { + let d = doc_with(|d| { + vec![ + stroked(d, line((-354_000.0, 50.0), (-353_990.0, 50.0)), Color::BLACK), + stroked(d, line((353_990.0, 50.0), (354_000.0, 50.0)), Color::BLACK), + ] + }); + let o = HpglOptions { + version: Version::Hpgl2, + origin: Origin::Center, + region: Rect::new(-400_000.0, 0.0, 400_000.0, 100.0), + ..HpglOptions::default() + }; + let out = plot(&d, &o); + assert_eq!(out.bytes.iter().filter(|b| **b == b'=').count(), 2, "{:?}", String::from_utf8_lossy(&out.bytes)); + let back = super::super::import(&out.bytes).unwrap(); + let mut xs = vec![]; + back.document.walk(|n| { + if let Some(p) = n.path_data() { + xs.extend(p.to_bezpath().elements().iter().filter_map(|e| if let PathEl::MoveTo(p) = e { Some(p.x) } else { None })); + } + }); + assert_eq!(xs.len(), 2); + assert!((xs[1] - xs[0] - 707_990.0).abs() < 0.2, "{xs:?}"); +} + +/// The points of every path `doc` holds, in paint order. +fn polylines(doc: &Document) -> Vec<(Vec, Option)> { + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + let bp = path.to_bezpath(); + let pts = bp.elements().iter().filter_map(|e| match e { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }); + let stroke = n.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.paint.clone()) } else { None }); + out.push((pts.collect(), stroke)); + } + }); + out +} + +/// Each version's plot read back: the same lines, within the tolerance and half a plotter unit, +/// and with HP-GL/2 the same colors. +#[test] +fn plots_read_back_as_the_same_lines() { + let d = three(); + for version in Version::ALL { + let out = plot(&d, &HpglOptions { version, ..opts(&d) }); + let back = super::super::import(&out.bytes).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let lines = polylines(&back.document); + assert_eq!(lines.len(), 3, "{version:?}"); + // The reader's artboard is round what the art paints: line the two up by the square. + let shift = lines[0].0[0] - Point::new(10.0, 10.0); + // Two roundings to whole plotter units (1/1016 in) apart at most. + let near = |p: Point, q: Point| (p - shift).distance(q) <= 0.11; + let square = [(10.0, 10.0), (60.0, 10.0), (60.0, 40.0), (10.0, 40.0), (10.0, 10.0)].map(Point::from); + assert!(lines[0].0.iter().zip(square).all(|(p, q)| near(*p, q)) && lines[0].0.len() == 5, "{:?}", lines[0].0); + assert!(near(lines[1].0[0], Point::new(70.0, 20.0)) && near(lines[1].0[1], Point::new(150.0, 80.0)), "{:?}", lines[1].0); + // The ellipse's every point lies on it, within the tolerance and the rounding. + let ellipse = kurbo::Ellipse::new((100.0, 50.0), (30.0, 20.0), 0.0); + for p in &lines[2].0 { + let q = p.to_vec2() - shift - kurbo::Vec2::new(100.0, 50.0); + let r = (q.x / 30.0).hypot(q.y / 20.0); + assert!((r - 1.0).abs() * 20.0 <= DEFAULT_TOLERANCE + 0.1, "{p:?} off the ellipse"); + } + assert!(lines[2].0.len() > 16 && ellipse.area() > 0.0); + if version == Version::Hpgl2 { + let colors: Vec> = lines.iter().map(|l| l.1.clone()).collect(); + assert_eq!( + colors, + [Paint::solid(Color::rgb8(0, 0, 0)), Paint::solid(Color::rgb8(255, 0, 0)), Paint::solid(Color::rgb8(0, 0, 255))].map(Some) + ); + } + } +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 6035211600..0ef28a4aaa 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -1,4 +1,5 @@ -//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader. +//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an +//! HP-GL/2 plot file reader and writer. //! //! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF //! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths @@ -11,13 +12,16 @@ //! clipping) is approximated or left out, and each such loss comes back as a warning. //! //! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`]. +//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`]. //! //! - `aci`: the 256-colour index palette and the nearest index of a colour. //! - `writer`: group codes, handles and the file's sections, tables and objects. //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. +//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. mod aci; +pub mod hpgl; pub mod import; mod scene; mod writer; @@ -277,6 +281,10 @@ pub struct DxfOptions { pub scale_lineweights: bool, pub colors: ColorDepth, pub raster: RasterFormat, + /// Placed images are written as IMAGE entities with their files (else left out, undecoded). + pub include_images: bool, + /// Filled areas get a solid HATCH after their outlines (else the outlines alone). + pub include_hatches: bool, pub preserve: Preserve, /// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`] /// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have @@ -299,6 +307,8 @@ impl Default for DxfOptions { scale_lineweights: false, colors: ColorDepth::default(), raster: RasterFormat::default(), + include_images: true, + include_hatches: true, preserve: Preserve::default(), alter_paths: false, outline_text: false, @@ -318,7 +328,8 @@ pub enum DxfPreset { /// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight /// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize /// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths), - /// and placed images as PNG. + /// and placed images and fill hatches left out (fills are their outlines), with PNG as the + /// format images take when they are put back in. Cnc, } @@ -356,6 +367,8 @@ impl DxfPreset { scale_lineweights: false, colors: ColorDepth::Aci256, raster: RasterFormat::Png, + include_images: false, + include_hatches: false, preserve: Preserve::Editability, alter_paths: false, outline_text: true, @@ -373,6 +386,8 @@ impl DxfPreset { && o.scale_lineweights == c.scale_lineweights && o.colors == c.colors && o.raster == c.raster + && o.include_images == c.include_images + && o.include_hatches == c.include_hatches && o.preserve == c.preserve && o.alter_paths == c.alter_paths && o.outline_text == c.outline_text; diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 45ed992995..7c5d8b6755 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -1,5 +1,6 @@ //! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint -//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes +//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with +//! hatches left out), placed images are linked image files unless left out, strokes //! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or //! filled outlines where the look needs them. @@ -28,6 +29,8 @@ const NO_TRUE_COLOR: &str = "true colour needs DXF 2004 or later: colours are wr const NO_TRANSPARENCY: &str = "transparency needs DXF 2004 or later: transparent objects are written opaque"; const NO_FILLS: &str = "DXF R12 has no fills: filled areas are written as their outlines"; const NO_IMAGES: &str = "DXF R12 has no images: placed images are left out"; +const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)"; +const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)"; const WIDE_LINES: &str = "lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width"; const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)"; @@ -339,6 +342,32 @@ fn subpaths(bp: &BezPath) -> Vec { out } +/// `bp` with each open subpath that can enclose an area closed, as a fill closes it: two or more +/// segments, or one curve. A single straight segment stays open. +fn closed_fill(bp: &BezPath) -> BezPath { + let mut out = BezPath::new(); + let (mut segs, mut curved) = (0usize, false); + let close = |out: &mut BezPath, segs: usize, curved: bool| { + if segs >= 2 || (segs == 1 && curved) { + out.close_path(); + } + }; + for el in bp.elements() { + match *el { + PathEl::MoveTo(_) => { + close(&mut out, segs, curved); + (segs, curved) = (0, false); + } + PathEl::ClosePath => (segs, curved) = (0, false), + PathEl::LineTo(_) => segs += 1, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => (segs, curved) = (segs + 1, true), + } + out.push(*el); + } + close(&mut out, segs, curved); + out +} + /// The most pixels of an image written (it is held decoded, as RGBA and encoded at once). const MAX_IMAGE_PIXELS: u64 = 64 << 20; @@ -583,7 +612,8 @@ impl<'a> Scene<'a> { } fn node(&mut self, n: &Node, force: bool) { - if let NodeKind::Layer { template: true, .. } = n.kind { + // Ruler guides draw on screen only: no entity and no loss warning. + if n.is_ruler_guide() || n.is_template() { return; } // Symbols that hold symbols are written in full for each instance: depth alone doesn't @@ -676,6 +706,8 @@ impl<'a> Scene<'a> { self.node(c, false); } } + // Ruler guides draw on screen only. + NodeKind::RulerGuide { .. } => {} } self.opacity = opacity; } @@ -875,13 +907,13 @@ impl<'a> Scene<'a> { Some(vectorcraft_brush::stroke_pieces(doc, b, bp, st)) } - /// A filled area as its outlines followed by a solid hatch (R12: the outlines alone). Laser - /// and cutter software reads the outlines and skips hatches. `clean`: the path has no + /// A filled area as its outlines followed by a solid hatch (R12, or with hatches left out: the + /// outlines alone). Laser and cutter software reads the outlines and skips hatches. `clean`: the path has no /// overlaps, so the hatch's even-odd rule reads it as it is. fn area(&mut self, bp: &BezPath, rule: FillRule, style: &EntityStyle, clean: bool) { if !self.o.version.handles() { self.warn(NO_FILLS); - self.lines(bp, style, 0.0); + self.lines(&closed_fill(bp), style, 0.0); return; } let several = bp.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count() > 1; @@ -890,11 +922,17 @@ impl<'a> Scene<'a> { .flatten() .map(|p| p.to_bezpath()); let outline = normalized.as_ref().unwrap_or(bp); + // A fill with no loop of three points or more encloses no area: no outline and no hatch. let loops: Vec> = polygons(outline).into_iter().filter(|p| p.len() >= 3).collect(); if loops.is_empty() { return; } - self.lines(outline, style, 0.0); + // The outlines close as the fill does, so an open path's fill keeps its closing edge. + self.lines(&closed_fill(outline), style, 0.0); + if !self.o.include_hatches { + self.warn(HATCHES_OFF); + return; + } let h = self.handle(); let layer = self.layer.clone(); self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch"); @@ -1282,6 +1320,10 @@ impl<'a> Scene<'a> { self.warn(NO_IMAGES); return; } + if !self.o.include_images { + self.warn(IMAGES_OFF); + return; + } let Some(i) = self.image_def(im) else { return }; let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return }; let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 90e4cbc2c6..9d2a519e1d 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -843,10 +843,151 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro assert!(out.images.is_empty()); assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc); assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom); + assert_eq!(DxfPreset::of(&DxfOptions { include_images: true, ..o.clone() }), DxfPreset::Custom); + assert_eq!(DxfPreset::of(&DxfOptions { include_hatches: true, ..o.clone() }), DxfPreset::Custom); assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom); assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc)); } +/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order +/// `fill`'s rectangle. +fn image_and_fill_doc(fill: Paint) -> Document { + let mut png = vec![]; + image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut d = doc_with(|d| { + let im = ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![ + path(d, shapes::rectangle(Rect::new(50.0, 10.0, 150.0, 60.0)), fill, Paint::None, 0.0), + Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))), + ] + }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)"; +const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)"; + +#[test] +fn fills_without_hatches_keep_their_outlines() { + let d = shapes_doc(); + let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle"); + assert_eq!(out.warnings, [HATCHES_OFF]); + let e = entities(&out); + assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight"); + // Hatches stay by default, with no note. + let on = export(&d, &opts(&d)).unwrap(); + assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF)); + // The outlines are the ones written beside hatches, also for overlapping subpaths, which are + // merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way. + let compound = doc_with(|d| { + let mut bp = shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 60.0)).to_bezpath(); + bp.extend(shapes::rectangle(Rect::new(40.0, 40.0, 90.0, 90.0)).to_bezpath().elements().iter().copied()); + let p = PathData::from_bezpath(&bp); + vec![ + path(d, p, Paint::solid(Color::BLACK), Paint::None, 0.0), + path(d, shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 70.0)), Paint::solid(Color::BLACK), Paint::None, 0.0), + path(d, shapes::line(Point::new(100.0, 10.0), Point::new(150.0, 60.0)), Paint::solid(Color::BLACK), Paint::None, 0.0), + ] + }); + let without_hatches = |o: &DxfOutput| { + let mut e = entities(o); + e.retain(|x| kind(x) != "HATCH"); + e.into_iter().map(|x| x.into_iter().filter(|p| p.0 != 5).collect::()).collect::>() + }; + let (c_on, c_off) = + (export(&compound, &opts(&compound)).unwrap(), export(&compound, &DxfOptions { include_hatches: false, ..opts(&compound) }).unwrap()); + assert_eq!(kinds(&c_on), ["LWPOLYLINE", "HATCH"], "one merged outline"); + assert_eq!(without_hatches(&c_off), without_hatches(&c_on)); + assert_eq!(without_hatches(&out), without_hatches(&on)); + // Strokes outlined for their look are areas too: their outlines stay. + let altered = + export(&d, &DxfOptions { include_hatches: false, alter_paths: true, preserve: Preserve::Editability, version: DxfVersion::R14, ..opts(&d) }) + .unwrap(); + assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered)); + // Nothing filled: no note. + let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty()); + // R12 has no hatches anyway: the same outlines, and its own note alone. + let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap(); + let (off, on) = (r12(false), r12(true)); + assert_eq!(off.bytes, on.bytes); + assert_eq!(off.warnings, on.warnings); + assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF)); +} + +#[test] +fn an_open_path_s_fill_outline_keeps_its_closing_edge() { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((10.0, 10.0)); + bp.line_to((90.0, 10.0)); + bp.line_to((50.0, 80.0)); + let open = PathData::from_bezpath(&bp); + let d = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)]); + let closed = |e: &Pairs| get(e, 70).and_then(|v| v.trim().parse::().ok()).is_some_and(|v| v & 1 == 1); + for include_hatches in [false, true] { + let out = export(&d, &DxfOptions { include_hatches, ..opts(&d) }).unwrap(); + let e: Vec = entities(&out).into_iter().filter(|x| kind(x) == "LWPOLYLINE").collect(); + assert_eq!(e.len(), 2, "the fill's outline and the stroke: {:?}", kinds(&out)); + assert!(closed(&e[0]), "the fill's outline closes as the fill does (hatches {include_hatches})"); + assert!(!closed(&e[1]), "the stroke stays open (hatches {include_hatches})"); + } + // R12 writes the outline alone, closed too. + let fill_only = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::None, 0.0)]); + let r12 = export(&fill_only, &DxfOptions { version: DxfVersion::R12, ..opts(&fill_only) }).unwrap(); + let e = entities(&r12); + assert_eq!(kind(&e[0]), "POLYLINE", "{:?}", kinds(&r12)); + assert!(closed(&e[0]), "R12's outline closes as the fill does"); +} + +#[test] +fn images_can_be_left_out_with_their_files() { + let d = image_and_fill_doc(Paint::None); + let out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap(); + assert!(entities(&out).is_empty() && out.images.is_empty(), "{:?}", kinds(&out)); + let p = pairs(&out.bytes); + assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES"))); + assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE"))); + assert_eq!(out.warnings, [IMAGES_OFF]); + // An image that can't be decoded is not read when images are left out. + let mut broken = d.clone(); + broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None }); + assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]); + assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded"))); + // R12 has no images anyway: its own note alone. + let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap(); + assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF)); +} + +#[test] +fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() { + let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + let run = |o: DxfOptions| export(&d, &DxfOptions { region: d.artboards[0].rect, ..o }).unwrap(); + let both = run(DxfOptions::default()); + assert_eq!(kinds(&both), ["LWPOLYLINE", "HATCH", "IMAGE"]); + assert_eq!(both.images.len(), 1); + let no_images = run(DxfOptions { include_images: false, ..DxfOptions::default() }); + assert_eq!((kinds(&no_images), no_images.images.len()), (vec!["LWPOLYLINE".to_string(), "HATCH".into()], 0)); + let no_hatches = run(DxfOptions { include_hatches: false, ..DxfOptions::default() }); + assert_eq!((kinds(&no_hatches), no_hatches.images.len()), (vec!["LWPOLYLINE".to_string(), "IMAGE".into()], 1)); + // CNC / CAM: the cutting path alone, with no image file and both notes. + let cnc = run(DxfPreset::Cnc.options()); + assert_eq!(kinds(&cnc), ["LWPOLYLINE"]); + assert!(cnc.images.is_empty()); + assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings); + let custom = DxfPreset::Custom.options(); + assert!(custom.include_images && custom.include_hatches, "Custom keeps both"); +} + #[test] fn layers_become_dxf_layers() { let mut d = shapes_doc(); diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 03d0f5670c..c5803e3224 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -15,20 +15,42 @@ pub enum GradientKind { Radial, /// Freeform gradients: colour points and lines (see [`crate::freeform`]). Freeform, + /// Conic (angle) gradients: the stops sweep once around the center (`start`), clockwise on + /// the page from the vector, with a seam where the last stop meets the first. A negative + /// `aspect` mirrors the sweep (see [`GradientGeom::transform`]). + Conic, + /// Diamond gradients: the stops run from the center (`start`) out to a square whose + /// half-diagonal is the vector (a diamond when the vector is level), stretched across the + /// vector by `aspect` (see [`GradientGeom::diamond_frame`]). + Diamond, } impl GradientKind { - /// Parse a kind name (`linear`, `radial`, `freeform`; any case). + /// Every kind, in the order the Gradient panel lists them. + pub const ALL: [GradientKind; 5] = + [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond, GradientKind::Freeform]; + /// Parse a kind name (`linear`, `radial`, `conic`, `diamond`, `freeform`; any case). `angle` + /// and `conical` also mean conic. pub fn parse(s: &str) -> Option { - [GradientKind::Linear, GradientKind::Radial, GradientKind::Freeform].into_iter().find(|k| k.label().eq_ignore_ascii_case(s)) + if s.eq_ignore_ascii_case("angle") || s.eq_ignore_ascii_case("conical") { + return Some(GradientKind::Conic); + } + Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s)) } pub fn label(self) -> &'static str { match self { GradientKind::Linear => "Linear", GradientKind::Radial => "Radial", GradientKind::Freeform => "Freeform", + GradientKind::Conic => "Conic", + GradientKind::Diamond => "Diamond", } } + /// Is it placed by a center (`start`) and an extent around it (radial, conic and diamond), + /// rather than by a line? + pub fn is_centered(self) -> bool { + matches!(self, GradientKind::Radial | GradientKind::Conic | GradientKind::Diamond) + } } /// How a gradient mixes the colours between its stops (the Gradient panel's Method). @@ -642,19 +664,32 @@ pub struct GradientGeom { /// How far out a focal point may sit, as a fraction of the extent ellipse. const FOCAL_MAX: f64 = 0.99; +/// Most wedges [`GradientGeom::conic_wedges`] draws a conic gradient as. +pub const MAX_CONIC_WEDGES: usize = 4096; + fn one64() -> f64 { 1.0 } impl GradientGeom { /// Default placement for a bounding box: linear spans the box through the centre at `angle_deg`, - /// radial is centred with radius = half the larger dimension and its vector at `angle_deg`. + /// radial and conic are centered with radius = half the larger dimension and their vector at + /// `angle_deg`, and diamond is centered with its vector at `angle_deg`, its square's edge + /// running through the box's farthest corner (at 0 or 90 degrees, through all four). pub fn fit(kind: GradientKind, b: Rect, angle_deg: f64) -> Self { let c = b.center(); let a = angle_deg.to_radians(); let d = Vec2::new(a.cos(), -a.sin()); match kind { - GradientKind::Radial => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None }, + GradientKind::Radial | GradientKind::Conic => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None }, + GradientKind::Diamond => { + // The square through the box's farthest corner: the largest reach along the vector + // plus across it, at one corner. + let (w, h) = (b.width() / 2.0, b.height() / 2.0); + let level = |x: f64, y: f64| (x * d.x + y * d.y).abs() + (y * d.x - x * d.y).abs(); + let half = level(w, h).max(level(w, -h)); + Self { start: c, end: c + d * half, aspect: 1.0, focal: None } + } _ => { // Project the box corners onto the direction to cover the whole box. let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0; @@ -668,7 +703,16 @@ impl GradientGeom { /// Linear (and freeform) gradients keep their isolines: the new vector is the normal to the /// mapped isolines, reaching the line the old end maps onto. Radial gradients map their ellipse /// (the radius along the vector, `aspect` × the radius across it); its principal axes give the - /// new end (on the axis nearest the mapped vector) and aspect. + /// new end (on the axis nearest the mapped vector) and aspect. Conic gradients keep their + /// vector exactly (where the sweep starts, so the seam stays in place) and take the mapped + /// extent across it as their aspect, its sign flipping under a mirror so the sweep turns the + /// other way: exact for moves, rotations, uniform scales and mirrors, and the nearest frame + /// that keeps the seam under a shear or a non-uniform scale. A conic whose vector has no + /// length, or whose aspect is 0, still has the sign of its aspect flipped by a mirror. + /// Diamond gradients keep their vector (a corner of the square) the same way, with the size + /// of the mapped extent across it as their aspect: exact for moves, rotations, scales along or + /// across the vector and mirrors, and the nearest square stretched across its vector under a + /// shear or another scale. pub fn transform(&mut self, a: Affine, kind: GradientKind) { // The focal point is a point like any other. self.focal = self.focal.map(|f| a * f); @@ -677,9 +721,34 @@ impl GradientGeom { let perp = |v: Vec2| Vec2::new(-v.y, v.x); let start = a * self.start; let u = self.end - self.start; + let mirror = m0 * m3 - m1 * m2 < 0.0; if u.hypot2() < 1e-18 { self.start = start; self.end = start; + if kind == GradientKind::Conic && mirror { + self.aspect = -self.aspect; + } + return; + } + if kind == GradientKind::Conic { + let (lu, lw) = (lin(u), lin(perp(u) * self.aspect)); + self.start = start; + self.end = start + lu; + let aspect = lw.dot(perp(lu)) / lu.hypot2(); + self.aspect = match (lu.hypot2() > 1e-18 && aspect.is_finite(), aspect == 0.0) { + (false, _) => 1.0, + // A flat extent keeps its sign, so a mirror still turns the sweep the other way. + (true, true) => 0.0f64.copysign(if self.aspect.is_sign_negative() != mirror { -1.0 } else { 1.0 }), + (true, false) => aspect, + }; + return; + } + if kind == GradientKind::Diamond { + let (lu, lw) = (lin(u), lin(perp(u) * self.aspect)); + self.start = start; + self.end = start + lu; + let aspect = (lw.dot(perp(lu)) / lu.hypot2()).abs(); + self.aspect = if lu.hypot2() > 1e-18 && aspect.is_finite() { aspect } else { 1.0 }; return; } if kind != GradientKind::Radial { @@ -724,8 +793,24 @@ impl GradientGeom { /// The gradient parameter (0 at the start, 1 at the end) at document point `p`: the projection /// onto the vector for linear gradients, the elliptical radius (honouring `aspect`) for radial, /// measured from the focal point (each level is the ellipse scaled about the line from the - /// focal point to the centre). + /// focal point to the centre). For conic gradients it is the turn from the vector in + /// [`Self::conic_frame`], clockwise on the page (counterclockwise when mirrored), in 0..=1. + /// For diamond gradients it is the size of the square through `p`, as a fraction of the one + /// [`Self::diamond_frame`] gives (1 everywhere for a diamond without a frame). pub fn param_at(&self, kind: GradientKind, p: Point) -> f64 { + if kind == GradientKind::Conic { + let q = (self.conic_frame().inverse() * p).to_vec2(); + let t = q.y.atan2(q.x) / std::f64::consts::TAU; + let t = if t < 0.0 { t + 1.0 } else { t }; + return if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + } + if kind == GradientKind::Diamond { + // Without a frame the square has no inside: every point is past its edge. + let Some(m) = self.diamond_frame() else { return 1.0 }; + let q = (m.inverse() * p).to_vec2(); + let t = q.x.abs() + q.y.abs(); + return if t.is_nan() { 1.0 } else { t }; + } let u = self.end - self.start; if u.hypot2() < 1e-18 { return 0.0; @@ -746,13 +831,92 @@ impl GradientGeom { (-b - (b * b - a * d.hypot2()).max(0.0).sqrt()) / a } - /// The map from the unit circle onto a radial's extent ellipse: (1, 0) to the end, (0, 1) to - /// `aspect` × the radius across the vector. None when the ellipse is flat (no inverse). + /// The map from the unit circle onto a radial's (or conic's) extent ellipse: (1, 0) to the + /// end, (0, 1) to `aspect` × the radius across the vector (a conic's negative aspect mirrors + /// it). None when the ellipse is flat (no inverse). pub fn unit_frame(&self) -> Option { let u = self.end - self.start; (u.hypot2() * self.aspect.abs() > 1e-18).then(|| Affine::new([u.x, u.y, -u.y * self.aspect, u.x * self.aspect, self.start.x, self.start.y])) } + /// The frame a conic gradient sweeps in: its [`Self::unit_frame`], or, when the extent + /// ellipse is flat or not finite (a vector without length, an aspect of 0, or a file's + /// out-of-range numbers), the unit circle about the start turning from the vector's direction + /// (from the right when the vector has none), mirrored by a negative aspect. The canvas, + /// Expand and every export draw a conic in this frame. + pub fn conic_frame(&self) -> Affine { + if let Some(m) = self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18) { + return m; + } + if !self.start.is_finite() { + return Affine::IDENTITY; + } + let u = self.end - self.start; + let len = u.hypot(); + let d = if len.is_finite() && len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) }; + let s = if self.aspect.is_sign_negative() && !self.aspect.is_nan() { -1.0 } else { 1.0 }; + Affine::new([d.x, d.y, -d.y * s, d.x * s, self.start.x, self.start.y]) + } + + /// Is the sweep mirrored (counterclockwise on the page): a conic's negative aspect? + pub fn is_mirrored(&self) -> bool { + self.conic_frame().determinant() < 0.0 + } + + /// A conic gradient as `n` solid wedges around its center (at most [`MAX_CONIC_WEDGES`]), for + /// formats without conic gradients: each wedge's outline (the center, then an arc that + /// reaches past every corner of `b`) and the turn its color is sampled at (its middle). With + /// `overlap` (opaque stops), each wedge runs on to the seam and the next is drawn over it, so + /// no hairline of what lies below shows between neighbors and the seam stays sharp. + pub fn conic_wedges(&self, b: Rect, n: usize, overlap: bool) -> Vec<(Vec, f64)> { + let n = n.clamp(1, MAX_CONIC_WEDGES); + let frame = self.conic_frame(); + let r = fan_radius(frame, b); + (0..n) + .map(|k| { + let from = k as f64 / n as f64; + let to = if overlap { 1.0 } else { (k + 1) as f64 / n as f64 }; + (fan(frame, r, from, to), (k as f64 + 0.5) / n as f64) + }) + .collect() + } + + /// The frame a diamond gradient is drawn in: its [`Self::unit_frame`], which maps the square + /// with corners (±1, 0) and (0, ±1) onto the diamond (its first corner at the end of the + /// vector). `None` when the square is flat or not finite (a vector without length, an aspect + /// of 0, or a file's out-of-range numbers): such a diamond has no inside, and every point + /// takes its last stop. + pub fn diamond_frame(&self) -> Option { + self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18) + } + + /// A diamond gradient as four linear gradients, one for each quadrant of its + /// [`Self::diamond_frame`], for formats without diamond gradients: each quadrant's outline (the + /// center, then an arc that reaches past every corner of `b`) and the linear gradient that + /// equals the diamond there (its stops run across the square's edge in that quadrant), in the + /// order they are drawn. Each of the first three runs on past its last edge under the next, + /// and the first also back past its first edge under the last, so every edge drawn lies on + /// the quadrant before it and no hairline of what lies below shows between them; where they + /// overlap, translucent stops would add up, so the stops must be opaque. `None` for a diamond + /// without a frame. + pub fn diamond_quadrants(&self, b: Rect) -> Option<[(Vec, GradientGeom); 4]> { + let frame = self.diamond_frame()?; + let r = fan_radius(frame, b); + Some(std::array::from_fn(|k| { + let first = k as f64 / 4.0; + let (from, to) = match k { + 0 => (-0.125, 0.375), + 3 => (0.75, 1.0), + _ => (first, first + 0.375), + }; + // The quadrant's corner of the square, halfway along whose edge t is 1/2. + let (sx, sy) = [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)][k]; + let mut geom = GradientGeom { start: Point::ORIGIN, end: Point::new(sx / 2.0, sy / 2.0), aspect: 1.0, focal: None }; + geom.transform(frame, GradientKind::Linear); + (fan(frame, r, from, to), geom) + })) + } + /// The map that squashes a radial gradient's circle (centre `start`, radius the vector's /// length) into its extent ellipse: by `aspect` across the vector, about the centre. pub fn radial_squash(&self) -> Affine { @@ -799,6 +963,34 @@ impl GradientGeom { } } +/// Arc points of [`fan`] are at most this much of a turn apart. +const FAN_ARC: f64 = 1.0 / 32.0; + +/// The radius of the unit circle of `frame` at which the chords of [`fan`]'s arcs stay outside +/// every corner of `b`. +fn fan_radius(frame: Affine, b: Rect) -> f64 { + let to_unit = frame.inverse(); + let corners = [b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + let reach = corners.iter().map(|&c| (to_unit * c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6); + let reach = if reach.is_finite() { reach * 1.01 } else { 1.0 }; + reach / (std::f64::consts::PI * FAN_ARC).cos() +} + +/// The sector of `frame`'s unit circle, scaled to radius `r`, from turn `from` to turn `to` +/// (counted from the frame's x axis toward its y axis) as an outline: the center, then points on +/// the arc at most [`FAN_ARC`] of a turn apart. +fn fan(frame: Affine, r: f64, from: f64, to: f64) -> Vec { + let at = |turn: f64| { + let a = turn * std::f64::consts::TAU; + frame * Point::new(r * a.cos(), r * a.sin()) + }; + let steps = ((to - from) / FAN_ARC).ceil().max(1.0) as usize; + let mut pts = Vec::with_capacity(steps + 2); + pts.push(frame * Point::ORIGIN); + pts.extend((0..=steps).map(|i| at(from + (to - from) * i as f64 / steps as f64))); + pts +} + /// `p` moved from box `from` to box `to`, keeping its position relative to the box (along a side /// `from` has no extent on, its offset from the centre). fn rebase_point(p: Point, from: Rect, to: Rect) -> Point { @@ -901,7 +1093,7 @@ impl GradientPaint { pub fn draws_as_pixels(&self, fill: bool) -> bool { self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic() } - /// A linear or radial gradient placed on box `bounds` as a `cols` × `rows` grid of + /// A linear, radial, conic or diamond gradient placed on box `bounds` as a `cols` × `rows` grid of /// unpremultiplied RGBA8 pixels over `area`, row by row, each sampled at its centre (colours /// as `rgb` gives them, mixed as the renderer mixes them: [`Ramp`]). Dithered and painting a /// fill (`fill`; dither applies to fills only), each colour channel of pixel (column, row) gets @@ -932,7 +1124,7 @@ impl GradientPaint { ) -> impl Iterator + use<> { self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false) } - /// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K + /// [`Self::pixels`] of a linear, radial, conic or diamond gradient whose stops are all CMYK, as C, M, Y, K /// and opacity levels mixed from the stops' inks; `None` when a stop is in another model, /// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`]. /// Dither's noise adds no ink where the ramp has none. diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 87372a1c24..0709d3068b 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -697,3 +697,360 @@ fn ink_pixels_stop_at_the_ink_mixes_limit() { assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none()); assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some()); } + +/// A conic placed at `center` with its vector `dx` long to the right and aspect `aspect`. +fn conic_at(center: Point, dx: f64, aspect: f64) -> GradientGeom { + GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None } +} + +#[test] +fn a_conic_turns_clockwise_on_the_page_from_its_vector() { + // The page's y runs down: a quarter turn clockwise from a vector pointing right is straight + // below the center. + let g = conic_at(Point::new(100.0, 100.0), 50.0, 1.0); + let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y)); + assert!(t(200.0, 100.0).abs() < 1e-12); + assert!((t(100.0, 130.0) - 0.25).abs() < 1e-12); + assert!((t(10.0, 100.0) - 0.5).abs() < 1e-12); + assert!((t(100.0, 3.0) - 0.75).abs() < 1e-12); + // Either side of the seam: the start of the ramp just below the vector, its end just above. + assert!(t(200.0, 100.01) < 1e-3); + let before = t(200.0, 99.99); + assert!(before > 0.999 && before <= 1.0, "{before}"); + // A flatter extent ellipse turns faster near the vector's line: half as tall, the point 1/8 + // of a turn around is half as far below it. + let squashed = conic_at(Point::new(100.0, 100.0), 50.0, 0.5); + let p = Point::new(150.0, 125.0); + assert!((squashed.param_at(GradientKind::Conic, p) - 0.125).abs() < 1e-12); + assert!(g.param_at(GradientKind::Conic, p) < 0.1); + // Mirrored (a negative aspect), it turns counterclockwise. + let mirrored = conic_at(Point::new(100.0, 100.0), 50.0, -1.0); + assert!(mirrored.is_mirrored() && !g.is_mirrored()); + assert!((mirrored.param_at(GradientKind::Conic, Point::new(100.0, 70.0)) - 0.25).abs() < 1e-12); +} + +#[test] +fn a_conic_follows_moves_turns_scales_and_mirrors() { + let c = Point::new(10.0, 20.0); + let g0 = conic_at(c, 30.0, 1.0); + let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0)]; + for a in [ + Affine::rotate(0.7), + Affine::scale(2.5), + Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0), + Affine::FLIP_X, + Affine::FLIP_Y * Affine::rotate(1.1), + Affine::scale_non_uniform(2.0, 0.5), + ] { + let mut g = g0; + g.transform(a, GradientKind::Conic); + assert!(g.start.distance(a * c) < 1e-9, "{a:?}"); + for p in probes { + let (want, got) = (g0.param_at(GradientKind::Conic, p), g.param_at(GradientKind::Conic, a * p)); + assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}"); + } + } + // A mirror and a mirror back: the same sweep. + let mut g = g0; + g.transform(Affine::FLIP_X, GradientKind::Conic); + assert!(g.is_mirrored()); + g.transform(Affine::FLIP_X, GradientKind::Conic); + assert!(!g.is_mirrored() && (g.aspect - 1.0).abs() < 1e-12); + // A conic without a vector, or with a flat extent, turns the other way under a mirror too. + for flat in [conic_at(c, 0.0, 1.0), conic_at(c, 30.0, 0.0)] { + let mut g = flat; + g.transform(Affine::FLIP_Y, GradientKind::Conic); + assert!(g.is_mirrored(), "{g:?}"); + g.transform(Affine::rotate(0.3), GradientKind::Conic); + assert!(g.is_mirrored(), "{g:?}"); + g.transform(Affine::FLIP_X, GradientKind::Conic); + assert!(!g.is_mirrored(), "{g:?}"); + } + // Under a shear the seam stays where the vector maps. + let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]); + let mut g = g0; + g.transform(shear, GradientKind::Conic); + let on_seam = shear * (c + Vec2::new(20.0, 0.0)); + assert!(g.param_at(GradientKind::Conic, on_seam) < 1e-9, "{g:?}"); +} + +#[test] +fn conic_kind_names_and_fit() { + for s in ["conic", "Conic", "angle", "CONICAL"] { + assert_eq!(GradientKind::parse(s), Some(GradientKind::Conic), "{s}"); + } + assert_eq!(GradientKind::parse("spiral"), None); + assert_eq!(GradientKind::Conic.label(), "Conic"); + assert!(GradientKind::Conic.is_centered() && GradientKind::Radial.is_centered() && !GradientKind::Linear.is_centered()); + let fit = GradientGeom::fit(GradientKind::Conic, Rect::new(0.0, 0.0, 200.0, 100.0), 90.0); + assert_eq!(fit.start, Point::new(100.0, 50.0)); + assert!(fit.end.distance(Point::new(100.0, -50.0)) < 1e-9); +} + +/// Is `p` inside polygon `poly` (non-zero winding)? +fn inside(poly: &[Point], p: Point) -> bool { + let mut w = 0i32; + for (i, &a) in poly.iter().enumerate() { + let c = poly[(i + 1) % poly.len()]; + let cross = (c - a).cross(p - a); + if a.y <= p.y && c.y > p.y && cross > 0.0 { + w += 1; + } else if a.y > p.y && c.y <= p.y && cross < 0.0 { + w -= 1; + } + } + w != 0 +} + +#[test] +fn conic_wedges_cover_the_box_and_meet_at_the_seam() { + let b = Rect::new(0.0, 0.0, 200.0, 100.0); + let g = conic_at(Point::new(60.0, 40.0), 30.0, 0.5); + let wedges = g.conic_wedges(b, 36, false); + assert_eq!(wedges.len(), 36); + // Each point of the box lies in the wedge whose share of the turn holds it. + for (x, y) in [(1.0, 1.0), (199.0, 99.0), (150.0, 30.0), (10.0, 90.0), (61.0, 39.0), (59.0, 41.0)] { + let p = Point::new(x, y); + let t = g.param_at(GradientKind::Conic, p); + let k = ((t * 36.0).floor() as usize).min(35); + assert!(inside(&wedges[k].0, p), "({x}, {y}) at {t} is not in wedge {k}"); + assert!((wedges[k].1 - (k as f64 + 0.5) / 36.0).abs() < 1e-12); + } + // Overlapping wedges run on from their own start to the seam. + let over = g.conic_wedges(b, 36, true); + let frame = g.unit_frame().unwrap(); + let on = |turn: f64| frame * Point::new(0.5 * (turn * std::f64::consts::TAU).cos(), 0.5 * (turn * std::f64::consts::TAU).sin()); + assert!(inside(&over[0].0, on(0.5)) && inside(&over[0].0, on(35.9 / 36.0))); + assert!(inside(&over[20].0, on(35.9 / 36.0)) && !inside(&over[20].0, on(19.9 / 36.0))); + // The count is kept to what a file can hold. + assert_eq!(g.conic_wedges(b, 0, false).len(), 1); + assert_eq!(g.conic_wedges(b, usize::MAX, false).len(), MAX_CONIC_WEDGES); +} + +/// A conic whose extent can't be drawn (a vector without length, an aspect of 0, or numbers out +/// of range, as a file can hold them) sweeps from the right about its start, or the origin; the +/// parameter, the frame and the wedges stay finite. +#[test] +fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() { + let c = Point::new(50.0, 50.0); + for g in [ + conic_at(c, 0.0, 1.0), + conic_at(c, 30.0, 0.0), + conic_at(c, 30.0, f64::NAN), + conic_at(c, 30.0, f64::INFINITY), + conic_at(c, f64::INFINITY, 1.0), + GradientGeom { end: Point::new(f64::NAN, 3.0), ..conic_at(c, 30.0, 1.0) }, + ] { + assert!(g.conic_frame().as_coeffs().iter().all(|v| v.is_finite()), "{g:?}"); + let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y)); + assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}"); + assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}"); + let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false); + assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}"); + } + // A flat extent keeps the vector's direction and the sign of its aspect. + let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) }; + assert!(down.param_at(GradientKind::Conic, Point::new(50.0, 90.0)).abs() < 1e-12); + assert!((down.param_at(GradientKind::Conic, Point::new(10.0, 50.0)) - 0.25).abs() < 1e-12); + for g in [conic_at(c, 0.0, -1.0), conic_at(c, 30.0, -0.0), conic_at(c, 30.0, f64::NEG_INFINITY)] { + assert!(g.is_mirrored(), "{g:?}"); + assert!((g.param_at(GradientKind::Conic, Point::new(50.0, 10.0)) - 0.25).abs() < 1e-12, "{g:?}"); + } + let lost = GradientGeom { start: Point::new(f64::NAN, 0.0), ..conic_at(c, 30.0, 1.0) }; + assert_eq!(lost.conic_frame(), Affine::IDENTITY); + for p in [Point::new(3.0, 4.0), Point::new(f64::NAN, 1.0), Point::new(f64::INFINITY, 0.0)] { + let t = lost.param_at(GradientKind::Conic, p); + assert!((0.0..=1.0).contains(&t), "{t}"); + } +} + +/// A conic's pixels (what SVG and PDF draw a dithered or Perceptual one as) follow the sweep, +/// with one stop as well as many. +#[test] +fn conic_pixels_follow_the_sweep() { + let b = Rect::new(0.0, 0.0, 4.0, 4.0); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, Gradient::default().stops)); + g.geom = Some(conic_at(Point::new(2.0, 2.0), 1.0, 1.0)); + let px: Vec<[u8; 4]> = g.pixels(b, b, 4, 4, true, &Color::to_rgb).collect(); + // Below right of the center, early in the sweep: light. Above right, late: dark. + assert!(px[3 * 4 + 3][0] > 180 && px[3][0] < 75, "{px:?}"); + let one = GradientPaint { gradient: Gradient::new(GradientKind::Conic, vec![GradientStop::new(0.3, Color::rgb(1.0, 0.0, 0.0))]), ..g.clone() }; + assert!(one.pixels(b, b, 4, 4, true, &Color::to_rgb).all(|p| p == [255, 0, 0, 255])); + let many = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray((i % 2) as f32))).collect(); + let many = GradientPaint { gradient: Gradient::new(GradientKind::Conic, many), ..g }; + assert_eq!(many.pixels(b, b, 4, 4, true, &Color::to_rgb).count(), 16); +} + +/// A diamond placed at `center` with its vector `dx` long to the right and aspect `aspect`. +fn diamond_at(center: Point, dx: f64, aspect: f64) -> GradientGeom { + GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None } +} + +#[test] +fn a_diamond_runs_from_its_center_out_to_a_square_with_a_corner_at_the_end_of_its_vector() { + let g = diamond_at(Point::new(100.0, 100.0), 50.0, 1.0); + let t = |x: f64, y: f64| g.param_at(GradientKind::Diamond, Point::new(x, y)); + assert!(t(100.0, 100.0).abs() < 1e-12); + // The square's corners: at the end of the vector and a quarter turn on from it each way. + for (x, y) in [(150.0, 100.0), (100.0, 150.0), (50.0, 100.0), (100.0, 50.0)] { + assert!((t(x, y) - 1.0).abs() < 1e-12, "({x}, {y})"); + } + // Halfway along an edge, and halfway out along a diagonal (the middle of the edge's half size). + assert!((t(125.0, 125.0) - 1.0).abs() < 1e-12); + assert!((t(112.5, 87.5) - 0.5).abs() < 1e-12); + // Past the square: more than 1 (the last stop pads on). + assert!((t(200.0, 200.0) - 4.0).abs() < 1e-12); + // The aspect stretches the square across the vector into a rhombus. + let tall = diamond_at(Point::new(100.0, 100.0), 50.0, 2.0); + assert!((tall.param_at(GradientKind::Diamond, Point::new(100.0, 200.0)) - 1.0).abs() < 1e-12); + assert!((tall.param_at(GradientKind::Diamond, Point::new(150.0, 100.0)) - 1.0).abs() < 1e-12); + // Turned: the corner follows the vector. + let turned = GradientGeom { end: Point::new(130.0, 140.0), ..g }; + assert!((turned.param_at(GradientKind::Diamond, Point::new(130.0, 140.0)) - 1.0).abs() < 1e-12); + assert!((turned.param_at(GradientKind::Diamond, Point::new(115.0, 120.0)) - 0.5).abs() < 1e-12); +} + +#[test] +fn diamond_kind_names_and_fit() { + for s in ["diamond", "Diamond", "DIAMOND"] { + assert_eq!(GradientKind::parse(s), Some(GradientKind::Diamond), "{s}"); + } + assert_eq!(GradientKind::Diamond.label(), "Diamond"); + assert!(GradientKind::Diamond.is_centered()); + assert!(GradientKind::ALL.contains(&GradientKind::Diamond)); + // Level: the square's edges pass through the box's corners, so it covers the box exactly. + let b = Rect::new(0.0, 0.0, 200.0, 100.0); + let fit = GradientGeom::fit(GradientKind::Diamond, b, 0.0); + assert_eq!(fit.start, Point::new(100.0, 50.0)); + assert!(fit.end.distance(Point::new(250.0, 50.0)) < 1e-9, "{fit:?}"); + for c in [Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)] { + assert!((fit.param_at(GradientKind::Diamond, c) - 1.0).abs() < 1e-9, "{c:?}"); + } + // At any angle the square covers the box and runs through its farthest corner, on a square + // box too. + for b in [b, Rect::new(0.0, 0.0, 100.0, 100.0)] { + for angle in [30.0, 45.0, 90.0, -120.0] { + let fit = GradientGeom::fit(GradientKind::Diamond, b, angle); + let levels = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] + .map(|c| fit.param_at(GradientKind::Diamond, c)); + assert!(levels.iter().all(|&t| t <= 1.0 + 1e-9), "{angle}: {levels:?}"); + assert!(levels.iter().any(|&t| (t - 1.0).abs() < 1e-9), "{angle}: {levels:?}"); + } + } +} + +#[test] +fn a_diamond_follows_moves_turns_scales_and_mirrors() { + let c = Point::new(10.0, 20.0); + let g0 = diamond_at(c, 30.0, 0.5); + let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0), c + Vec2::new(-20.0, -4.0)]; + for a in [ + Affine::rotate(0.7), + Affine::scale(2.5), + Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0), + Affine::FLIP_X, + Affine::FLIP_Y * Affine::rotate(1.1), + // Along and across the vector. + Affine::scale_non_uniform(2.0, 0.5), + Affine::scale_non_uniform(-3.0, 0.25), + ] { + let mut g = g0; + g.transform(a, GradientKind::Diamond); + assert!(g.start.distance(a * c) < 1e-9, "{a:?}"); + // A mirror changes nothing a diamond shows: its aspect stays a size. + assert!(g.aspect > 0.0, "{a:?}: {g:?}"); + for p in probes { + let (want, got) = (g0.param_at(GradientKind::Diamond, p), g.param_at(GradientKind::Diamond, a * p)); + assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}"); + } + } + // Under a shear the corner stays where the vector maps. + let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]); + let mut g = g0; + g.transform(shear, GradientKind::Diamond); + assert!((g.param_at(GradientKind::Diamond, shear * (c + Vec2::new(30.0, 0.0))) - 1.0).abs() < 1e-9, "{g:?}"); + // Out-of-range numbers: a finite aspect after any transform. + for bad in [diamond_at(c, 30.0, f64::NAN), diamond_at(c, f64::INFINITY, 1.0), diamond_at(c, 0.0, 1.0)] { + let mut g = bad; + g.transform(Affine::rotate(0.4), GradientKind::Diamond); + assert!(g.aspect.is_finite(), "{g:?}"); + } +} + +/// A diamond without a frame (no vector, a flat or a not-finite extent) has no inside: every +/// point is past its edge and takes the last stop. Points that aren't numbers do too. +#[test] +fn a_diamond_with_no_extent_or_bad_numbers_is_its_last_stop() { + let c = Point::new(50.0, 50.0); + for g in [ + diamond_at(c, 0.0, 1.0), + diamond_at(c, 30.0, 0.0), + diamond_at(c, 30.0, f64::NAN), + diamond_at(c, f64::INFINITY, 1.0), + GradientGeom { start: Point::new(f64::NAN, 0.0), ..diamond_at(c, 30.0, 1.0) }, + ] { + assert!(g.diamond_frame().is_none(), "{g:?}"); + assert!(g.diamond_quadrants(Rect::new(0.0, 0.0, 100.0, 100.0)).is_none(), "{g:?}"); + assert_eq!(g.param_at(GradientKind::Diamond, Point::new(60.0, 40.0)), 1.0, "{g:?}"); + } + let g = diamond_at(c, 30.0, 1.0); + assert_eq!(g.param_at(GradientKind::Diamond, Point::new(f64::NAN, 1.0)), 1.0); + assert!(g.param_at(GradientKind::Diamond, Point::new(f64::INFINITY, 1.0)) >= 1.0); +} + +/// The four linear gradients a format without diamond gradients gets, drawn in order, equal the +/// diamond everywhere, and each edge drawn lies on the quadrant drawn before it. +#[test] +fn diamond_quadrants_are_linear_gradients_that_equal_the_diamond() { + let b = Rect::new(0.0, 0.0, 200.0, 100.0); + let probes: Vec = (0..=20).flat_map(|i| (0..=10).map(move |j| Point::new(i as f64 * 10.0 + 0.3, j as f64 * 10.0 + 0.7))).collect(); + // Squashed and turned, stretched twice as tall as wide, and stretched by a shear. + let mut turned = diamond_at(Point::new(60.0, 40.0), 30.0, 0.5); + turned.transform(Affine::rotate_about(0.4, Point::new(60.0, 40.0)), GradientKind::Diamond); + let mut sheared = diamond_at(Point::new(90.0, 50.0), 25.0, 1.0); + sheared.transform(Affine::new([2.0, 0.0, 0.7, 1.0, -60.0, 0.0]), GradientKind::Diamond); + for g in [turned, diamond_at(Point::new(100.0, 50.0), 20.0, 2.0), sheared] { + let quadrants = g.diamond_quadrants(b).expect("a frame"); + for p in &probes { + // The last quadrant drawn that holds the point paints it. + let Some((_, linear)) = quadrants.iter().rev().find(|(poly, _)| inside(poly, *p)) else { panic!("{p:?} is in no quadrant") }; + let (want, got) = (g.param_at(GradientKind::Diamond, *p), linear.param_at(GradientKind::Linear, *p)); + assert!((want - got).abs() < 1e-9, "{g:?} at {p:?}: {want} vs {got}"); + } + } + let g = turned; + let quadrants = g.diamond_quadrants(b).expect("a frame"); + // Next to each edge of a quadrant drawn later, on either side, the quadrant drawn before it + // lies underneath (the first quadrant's edges are covered by the second and the last). + let frame = g.diamond_frame().expect("a frame"); + for (unit, under) in [ + // The second quadrant's first edge, on the first. + (Point::new(0.01, 0.5), 0), + (Point::new(-0.01, 0.5), 0), + // The third's, on the second. + (Point::new(-0.5, 0.01), 1), + (Point::new(-0.5, -0.01), 1), + // The last's two, on the third and on the first. + (Point::new(-0.01, -0.5), 2), + (Point::new(0.01, -0.5), 2), + (Point::new(0.5, -0.01), 0), + (Point::new(0.5, 0.01), 0), + ] { + assert!(inside(&quadrants[under].0, frame * unit), "{unit:?} lies on quadrant {under}"); + } +} + +/// A diamond's pixels (what SVG and PDF draw a dithered or Perceptual one as, and what the canvas +/// draws) follow the squares. +#[test] +fn diamond_pixels_follow_the_squares() { + let b = Rect::new(0.0, 0.0, 5.0, 5.0); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, Gradient::default().stops)); + g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0)); + let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect(); + // White at the center, black in the corners, and the same on each side of it. + assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}"); + assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]); + assert_eq!(px[5 + 2], px[3 * 5 + 2]); + assert_eq!(px[2 * 5 + 1], px[5 + 2]); +} diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index e96760d5c5..5fc952a061 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, OnceLock}; use serde::{Deserialize, Serialize}; -use crate::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup}; +use crate::{Color, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup}; /// A library: its name, its ungrouped swatches and its colour groups. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -72,6 +72,8 @@ pub const GRADIENT_LIBRARIES: &[BuiltinLibrary] = &[ lib!("spectrum-gradients", "Spectrum Gradients", spectrum_gradients), lib!("sky-gradients", "Sky Gradients", sky_gradients), lib!("neutral-gradients", "Neutral Gradients", neutral_gradients), + lib!("organic-fades", "Organic Fades", organic_fades), + lib!("holographic", "Holographic", holographic), lib!("duotone-gradients", "Duotone Gradients", duotone_gradients), lib!("radial-glows", "Radial Glows", radial_glows), ]; @@ -179,6 +181,14 @@ pub(crate) fn gradient(name: &str, kind: GradientKind, stops: &[(f32, Color, f32 Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops)))), global: false, spot: false } } +/// A gradient swatch mixed by `method` through `stops` of (offset, color, opacity, midpoint). +fn gradient_with(name: &str, kind: GradientKind, method: GradientMethod, stops: &[(f32, Color, f32, f32)]) -> Swatch { + let stops = + stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect(); + let gradient = Gradient { method, ..Gradient::new(kind, stops) }; + Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(gradient))), global: false, spot: false } +} + /// `n` steps of OKLCH lightness from `l0` to `l1`, chroma `c(t)` and hue `h(t)` (`t` in 0..=1), /// named "`name` 1"… fn ramp(name: &str, n: usize, (l0, l1): (f64, f64), c: impl Fn(f64) -> f64, h: impl Fn(f64) -> f64) -> SwatchGroup { @@ -387,6 +397,197 @@ fn radial_glows() -> (Vec, Vec) { (s, vec![]) } +/// A stop of [`organic_fades`]: offset, OKLCH `(l, c, h°)`, opacity and midpoint. +type FadeStop = (f32, (f64, f64, f64), f32, f32); + +/// Soft fades through a few unevenly spaced stops with off-center midpoints, mixed perceptually, +/// that thin out to transparent: at the end of the linear ones and at the edge of the radial ones. +fn organic_fades() -> (Vec, Vec) { + use GradientKind::{Linear, Radial}; + let fades: [(&str, GradientKind, &[FadeStop]); 15] = [ + ( + "Mist", + Linear, + &[ + (0.0, (0.94, 0.012, 240.0), 1.0, 0.38), + (0.35, (0.86, 0.03, 235.0), 0.85, 0.62), + (0.7, (0.8, 0.035, 230.0), 0.4, 0.45), + (1.0, (0.78, 0.035, 230.0), 0.0, 0.5), + ], + ), + ( + "Petal", + Linear, + &[ + (0.0, (0.82, 0.09, 350.0), 1.0, 0.42), + (0.28, (0.88, 0.07, 10.0), 0.9, 0.66), + (0.64, (0.93, 0.04, 30.0), 0.45, 0.35), + (1.0, (0.95, 0.03, 40.0), 0.0, 0.5), + ], + ), + ("Fern", Linear, &[(0.0, (0.52, 0.1, 145.0), 1.0, 0.6), (0.4, (0.68, 0.11, 135.0), 0.75, 0.4), (1.0, (0.85, 0.08, 120.0), 0.0, 0.5)]), + ( + "Smoke", + Linear, + &[ + (0.0, (0.35, 0.01, 260.0), 1.0, 0.3), + (0.22, (0.48, 0.012, 255.0), 0.8, 0.58), + (0.58, (0.62, 0.01, 250.0), 0.35, 0.7), + (1.0, (0.72, 0.008, 250.0), 0.0, 0.5), + ], + ), + ( + "Honey", + Linear, + &[ + (0.0, (0.72, 0.15, 70.0), 1.0, 0.55), + (0.3, (0.8, 0.14, 80.0), 0.9, 0.35), + (0.75, (0.9, 0.09, 90.0), 0.3, 0.6), + (1.0, (0.95, 0.05, 95.0), 0.0, 0.5), + ], + ), + ("Seafoam", Linear, &[(0.0, (0.7, 0.09, 175.0), 1.0, 0.45), (0.45, (0.84, 0.07, 170.0), 0.6, 0.65), (1.0, (0.95, 0.03, 165.0), 0.0, 0.5)]), + ( + "Lavender", + Linear, + &[ + (0.0, (0.62, 0.12, 300.0), 1.0, 0.36), + (0.3, (0.72, 0.1, 295.0), 0.85, 0.55), + (0.55, (0.82, 0.07, 290.0), 0.5, 0.68), + (0.82, (0.9, 0.04, 285.0), 0.15, 0.4), + (1.0, (0.93, 0.03, 285.0), 0.0, 0.5), + ], + ), + ("Driftwood", Linear, &[(0.0, (0.55, 0.04, 60.0), 1.0, 0.64), (0.38, (0.68, 0.035, 70.0), 0.7, 0.42), (1.0, (0.84, 0.025, 80.0), 0.0, 0.5)]), + ( + "Ink Wash", + Linear, + &[ + (0.0, (0.25, 0.05, 265.0), 1.0, 0.28), + (0.18, (0.35, 0.06, 262.0), 0.9, 0.6), + (0.5, (0.5, 0.05, 258.0), 0.45, 0.72), + (1.0, (0.65, 0.04, 255.0), 0.0, 0.5), + ], + ), + ( + "Tide", + Linear, + &[ + (0.0, (0.45, 0.1, 230.0), 1.0, 0.4), + (0.26, (0.6, 0.1, 215.0), 0.8, 0.62), + (0.72, (0.76, 0.08, 200.0), 0.35, 0.44), + (1.0, (0.88, 0.05, 195.0), 0.0, 0.5), + ], + ), + ( + "Bloom", + Radial, + &[ + (0.0, (0.92, 0.05, 40.0), 1.0, 0.4), + (0.22, (0.8, 0.12, 20.0), 0.95, 0.6), + (0.6, (0.7, 0.14, 355.0), 0.4, 0.35), + (1.0, (0.66, 0.13, 345.0), 0.0, 0.5), + ], + ), + ("Dew", Radial, &[(0.0, (0.97, 0.01, 200.0), 1.0, 0.3), (0.3, (0.88, 0.05, 195.0), 0.7, 0.58), (1.0, (0.8, 0.06, 190.0), 0.0, 0.5)]), + ( + "Pollen", + Radial, + &[ + (0.0, (0.96, 0.08, 100.0), 1.0, 0.45), + (0.18, (0.9, 0.15, 95.0), 1.0, 0.65), + (0.55, (0.82, 0.16, 85.0), 0.5, 0.4), + (1.0, (0.76, 0.15, 75.0), 0.0, 0.5), + ], + ), + // A ring: clear at the center, then a band that fades out to the edge. + ( + "Halo", + Radial, + &[ + (0.0, (0.98, 0.005, 90.0), 0.0, 0.6), + (0.42, (0.95, 0.02, 85.0), 0.0, 0.35), + (0.62, (0.92, 0.04, 80.0), 1.0, 0.55), + (1.0, (0.88, 0.05, 75.0), 0.0, 0.5), + ], + ), + ( + "Lichen", + Radial, + &[ + (0.0, (0.8, 0.07, 120.0), 1.0, 0.58), + (0.35, (0.7, 0.08, 130.0), 0.75, 0.4), + (0.74, (0.6, 0.07, 140.0), 0.25, 0.62), + (1.0, (0.55, 0.06, 145.0), 0.0, 0.5), + ], + ), + ]; + let s = fades + .iter() + .map(|&(name, kind, stops)| { + let stops: Vec<(f32, Color, f32, f32)> = stops.iter().map(|&(at, (l, c, h), opacity, mid)| (at, oklch(l, c, h), opacity, mid)).collect(); + gradient_with(name, kind, GradientMethod::Perceptual, &stops) + }) + .collect(); + (s, vec![]) +} + +/// The stops of a [`holographic`] look: offset, opacity and midpoint toward the next stop. +type Bands = [(f32, f32, f32)]; + +/// Foil: six opaque linear bands, a narrow bright one among them, with off-center midpoints. +const FOIL: &Bands = &[(0.0, 1.0, 0.37), (0.13, 1.0, 0.64), (0.34, 1.0, 0.28), (0.48, 1.0, 0.68), (0.71, 1.0, 0.42), (1.0, 1.0, 0.5)]; + +/// Glow: five radial rings from a bright center out to a clear edge. +const GLOW: &Bands = &[(0.0, 0.95, 0.4), (0.12, 1.0, 0.58), (0.31, 0.72, 0.34), (0.58, 0.3, 0.62), (1.0, 0.0, 0.5)]; + +/// A [`holographic`] look: name, kind, stops and the OKLCH color of each stop in order. +type Look = (&'static str, GradientKind, &'static Bands, Anchors); + +/// Iridescent looks mixed perceptually: linear foils of narrow pastel and pearl bands, and radial +/// glows that fade out to a clear edge. Each color is one stop of [`FOIL`] or [`GLOW`] in order. +fn holographic() -> (Vec, Vec) { + use GradientKind::{Linear, Radial}; + // Pale pearl, pastel and deep-violet OKLCH `(l, c, h°)` anchors. + const PEARL: (f64, f64, f64) = (0.97, 0.01, 90.0); + const SILVER: (f64, f64, f64) = (0.86, 0.015, 255.0); + const BLUSH: (f64, f64, f64) = (0.82, 0.055, 340.0); + const VIOLET: (f64, f64, f64) = (0.72, 0.1, 310.0); + const BLUE: (f64, f64, f64) = (0.73, 0.09, 255.0); + const CYAN: (f64, f64, f64) = (0.79, 0.09, 210.0); + const MINT: (f64, f64, f64) = (0.82, 0.08, 165.0); + const LIME: (f64, f64, f64) = (0.86, 0.085, 125.0); + const GOLD: (f64, f64, f64) = (0.89, 0.08, 85.0); + const AMBER: (f64, f64, f64) = (0.82, 0.1, 55.0); + const CORAL: (f64, f64, f64) = (0.78, 0.09, 25.0); + const DEEP_VIOLET: (f64, f64, f64) = (0.42, 0.04, 275.0); + let looks: [Look; 14] = [ + ("Prism Veil", Linear, FOIL, &[SILVER, BLUSH, PEARL, CYAN, VIOLET, SILVER]), + ("Opal Ribbon", Linear, FOIL, &[PEARL, MINT, BLUSH, PEARL, BLUE, SILVER]), + ("Pearl Flash", Linear, FOIL, &[SILVER, VIOLET, PEARL, GOLD, CYAN, PEARL]), + ("Aurora Foil", Linear, FOIL, &[BLUE, MINT, PEARL, BLUSH, CYAN, SILVER]), + ("Iris Sheen", Linear, FOIL, &[BLUSH, VIOLET, PEARL, CYAN, MINT, SILVER]), + ("Frost Spectrum", Linear, FOIL, &[CYAN, BLUE, PEARL, MINT, BLUSH, SILVER]), + ("Silver Tide", Linear, FOIL, &[SILVER, CYAN, PEARL, VIOLET, BLUE, SILVER]), + ("Rose Quartz Gleam", Radial, GLOW, &[PEARL, BLUSH, CORAL, VIOLET, BLUSH]), + ("Moonstone Shift", Radial, GLOW, &[PEARL, CYAN, MINT, BLUE, SILVER]), + ("Violet Edge", Radial, GLOW, &[PEARL, VIOLET, BLUSH, BLUE, DEEP_VIOLET]), + ("Mint Halo", Radial, GLOW, &[PEARL, MINT, CYAN, LIME, MINT]), + ("Amber Corona", Radial, GLOW, &[PEARL, GOLD, AMBER, CORAL, AMBER]), + ("Polar Glint", Radial, GLOW, &[PEARL, CYAN, BLUE, VIOLET, BLUE]), + ("Pastel Orbit", Radial, GLOW, &[PEARL, BLUSH, MINT, CYAN, VIOLET]), + ]; + let s = looks + .iter() + .map(|&(name, kind, bands, colors)| { + let stops: Vec<(f32, Color, f32, f32)> = + bands.iter().zip(colors).map(|(&(at, opacity, mid), &(l, c, h))| (at, oklch(l, c, h), opacity, mid)).collect(); + gradient_with(name, kind, GradientMethod::Perceptual, &stops) + }) + .collect(); + (s, vec![]) +} + /// The sequential scales of [`perceptual`]: name and anchors of rising lightness. const SEQUENTIAL: [(&str, Anchors); 5] = [ ("Ember", &[(0.22, 0.10, 300.0), (0.55, 0.18, 30.0), (0.93, 0.15, 100.0)]), @@ -532,6 +733,99 @@ mod tests { let st = &g.gradient.stops; assert!(st.len() >= 2 && st.windows(2).all(|w| w[0].offset <= w[1].offset), "{}", s.name); assert!(st.iter().all(|s| (0.0..=1.0).contains(&s.offset) && (0.0..=1.0).contains(&s.opacity))); + assert!(st.iter().all(|s| (0.01..=0.99).contains(&s.midpoint)), "{}: a midpoint out of range", s.name); + } + } + } + } + + #[test] + fn organic_fades_are_perceptual_multi_stop_fades_to_transparent() { + let lib = builtin_library("organic-fades").unwrap(); + assert_eq!(GRADIENT_LIBRARIES.iter().map(|b| b.name).position(|n| n == "Organic Fades"), Some(3), "after Neutral Gradients"); + assert!(lib.groups.is_empty() && (12..=16).contains(&lib.len()), "{} swatches", lib.len()); + let radial = lib.iter().filter(|s| matches!(&s.paint, Paint::Gradient(g) if g.gradient.kind == GradientKind::Radial)).count(); + assert!(radial >= 3 && radial * 2 <= lib.len(), "{radial} radial of {}", lib.len()); + for s in lib.iter() { + let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) }; + let (g, n) = (&g.gradient, &s.name); + assert_eq!(g.method, GradientMethod::Perceptual, "{n}"); + assert!((3..=5).contains(&g.stops.len()), "{n}: {} stops", g.stops.len()); + assert!(g.stops.windows(2).all(|w| w[0].offset < w[1].offset), "{n}: rising offsets"); + assert_eq!((g.stops[0].offset, g.stops[g.stops.len() - 1].offset), (0.0, 1.0), "{n}"); + // Unevenly spaced: some gap differs from an even step. + let even = 1.0 / (g.stops.len() - 1) as f32; + assert!(g.stops.windows(2).any(|w| (w[1].offset - w[0].offset - even).abs() > 0.02), "{n}: uneven stops"); + // Every segment's midpoint is off center and within the Gradient panel's 13 to 87%. + let segments = &g.stops[..g.stops.len() - 1]; + assert!(segments.iter().all(|st| (st.midpoint - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&st.midpoint)), "{n}: midpoints"); + // Fully opaque somewhere, and clear at the end (the edge of a radial one). + assert!(g.stops.iter().any(|st| st.opacity == 1.0), "{n}: an opaque stop"); + assert_eq!(g.stops[g.stops.len() - 1].opacity, 0.0, "{n}: clear at the end"); + } + } + + #[test] + fn holographic_holds_seven_opaque_foils_and_seven_glows_to_a_clear_edge() { + let lib = builtin_library("holographic").unwrap(); + let order: Vec<&str> = GRADIENT_LIBRARIES.iter().map(|b| b.name).collect(); + assert_eq!(order.iter().position(|n| *n == "Holographic"), Some(4), "after Organic Fades: {order:?}"); + assert!(lib.groups.is_empty()); + assert_eq!(lib.len(), 14); + // No name another built-in gradient has, in any case. + let mut others = std::collections::HashSet::new(); + for other in builtins().filter(|b| b.id != "holographic").map(|b| builtin_library(b.id).unwrap()) { + others.extend(other.iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| s.name.to_lowercase())); + } + assert!(lib.iter().all(|s| !others.contains(&s.name.to_lowercase())), "a name another library has"); + let (mut foils, mut glows) = (0, 0); + for s in lib.iter() { + let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) }; + let (g, n) = (&g.gradient, &s.name); + assert_eq!(g.method, GradientMethod::Perceptual, "{n}"); + let bands = match &g.kind { + GradientKind::Linear => { + foils += 1; + FOIL + } + GradientKind::Radial => { + glows += 1; + GLOW + } + kind => panic!("{n}: {kind:?}"), + }; + // Every stop takes its band's offset, opacity and midpoint, and none is dropped. + let shape: Vec<(f32, f32, f32)> = g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect(); + assert_eq!(shape, bands, "{n}"); + assert!(g.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{n}"); + } + assert_eq!((foils, glows), (7, 7)); + // Foils are opaque; a glow is clear at the edge. + assert!(FOIL.iter().all(|&(_, opacity, _)| opacity == 1.0)); + assert_eq!(GLOW.last().map(|b| b.1), Some(0.0)); + // Every segment's midpoint is off center and within the Gradient panel's 13 to 87%. + for bands in [FOIL, GLOW] { + assert!(bands[..bands.len() - 1].iter().all(|&(_, _, m)| (m - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&m))); + assert!(bands.windows(2).all(|w| w[0].0 < w[1].0) && bands[0].0 == 0.0 && bands[bands.len() - 1].0 == 1.0); + } + // Sampled colors: Prism Veil's bright band is the pearl anchor, and Violet Edge ends in deep violet. + let stop = |name: &str, i: usize| match &lib.swatch(name).unwrap().paint { + Paint::Gradient(g) => g.gradient.stops[i].color, + _ => panic!("{name} is a gradient"), + }; + assert_eq!(stop("Prism Veil", 2), oklch(0.97, 0.01, 90.0)); + assert_eq!(stop("Violet Edge", 4), oklch(0.42, 0.04, 275.0)); + let [l, ..] = to_oklab(&stop("Violet Edge", 4)); + assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}"); + } + + #[test] + fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() { + for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) { + for s in builtin_library(b.id).unwrap().iter() { + if let Paint::Gradient(g) = &s.paint { + assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name); + assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name); } } } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index b331d43e6a..800785f6f7 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -189,10 +189,39 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { let value = match &w.paint { Paint::Solid { color, .. } => css_color(color, 1.0), Paint::Gradient(g) if g.gradient.kind != GradientKind::Freeform => { + // A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops + // are written mirrored about the seam instead. + let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored()); + let stop = |s: &crate::GradientStop| { + let at = if mirrored { 1.0 - s.offset } else { s.offset }; + format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0) + }; let stops: Vec = - g.gradient.stops.iter().map(|s| format!("{} {}%", css_color(&s.color, s.opacity), s.offset * 100.0)).collect(); + if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() }; match g.gradient.kind { GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")), + // CSS sweeps clockwise from straight up; the angle is counted counterclockwise + // from the right. + GradientKind::Conic => { + format!("conic-gradient(from {}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")) + } + // CSS has no diamond gradient: four layers, each a quarter of the box with + // the stops running from the center out to its corner at a diagonal angle, + // make the diamond its fit gives a box of any shape: the level at a point + // is its distance from the center along both axes over the box's + // half-width plus half-height + // (https://www.w3.org/TR/css-images-3/#linear-gradients). Turned by an angle + // that is not a multiple of 90 degrees, its corners leave the box's axes, + // and a circle stands in for it, as for a radial swatch. + GradientKind::Diamond if (1e-9..90.0 - 1e-9).contains(&g.angle.rem_euclid(90.0)) => { + format!("radial-gradient(circle, {})", stops.join(", ")) + } + GradientKind::Diamond => { + let stops = stops.join(", "); + [("top left", 315), ("top right", 45), ("bottom right", 135), ("bottom left", 225)] + .map(|(corner, deg)| format!("linear-gradient({deg}deg, {stops}) {corner} / 50% 50% no-repeat")) + .join(", ") + } _ => format!("linear-gradient({}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")), } } diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index b0342d7a52..eaee50dd59 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -166,6 +166,75 @@ fn css_escapes_names_and_writes_gradients() { assert!(read(&text, "x").is_err(), "CSS is written only"); } +/// A conic gradient swatch is a CSS conic gradient starting where its angle points (CSS turns +/// clockwise from straight up); a mirrored one, which turns counterclockwise, has its stops mirrored +/// about the seam so each color lies on the same side. +#[test] +fn css_writes_conic_gradient_swatches() { + let one = |name: &str, g: GradientPaint| SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { name: name.into(), paint: Paint::Gradient(Box::new(g)), global: false, spot: false }], + groups: vec![], + }; + let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..Gradient::default() }); + conic.angle = 90.0; + let text = written(&one("Sweep", conic.clone()), PaletteFormat::Css); + assert!(text.contains("--sweep: conic-gradient(from 0deg, #ffffff 0%, #000000 100%);"), "{text}"); + conic.gradient.stops[0].offset = 0.2; + conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None }); + let text = written(&one("Back", conic), PaletteFormat::Css); + assert!(text.contains("--back: conic-gradient(from 0deg, #000000 0%, #ffffff 80%);"), "{text}"); +} + +/// A diamond gradient swatch (CSS has none) is four layered linear gradients, one a quarter of the +/// box running from the center out to its corner, for the `background` shorthand. +#[test] +fn css_writes_diamond_gradient_swatches_as_four_corner_layers() { + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { + name: "Gem".into(), + paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() }))), + global: false, + spot: false, + }], + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + // Diagonal angles, not `to `: on a box that isn't square, `to ` would turn + // each layer's lines to run through the quarter's other two corners. + let layer = |corner: &str, deg: u32| format!("linear-gradient({deg}deg, #ffffff 0%, #000000 100%) {corner} / 50% 50% no-repeat"); + let want = + format!("--gem: {}, {}, {}, {};", layer("top left", 315), layer("top right", 45), layer("bottom right", 135), layer("bottom left", 225)); + assert!(text.contains(&want), "{text}"); + // CSS's gradient line for a diagonal angle on a quarter box w × h is (w + h) / √2 long and + // starts at the quarter's corner at the box's center: the level at a point x, y from the + // center is (|x| + |y|) / (w + h), the level the diamond fitted to the whole box has there. + let (w, h) = (100.0f64, 50.0f64); + let length = (w + h) / std::f64::consts::SQRT_2; + let fit = crate::GradientGeom::fit(GradientKind::Diamond, kurbo::Rect::new(-w, -h, w, h), 0.0); + for (x, y) in [(0.0, -50.0), (-100.0, 0.0), (-30.0, -20.0), (-100.0, -50.0)] { + // The top-left quarter's layer runs toward (-1, -1). + let css = (-x - y) / std::f64::consts::SQRT_2 / length; + let model = fit.param_at(GradientKind::Diamond, kurbo::Point::new(x, y)); + assert!((css - model).abs() < 1e-9, "({x}, {y}): {css} vs {model}"); + } + // Turned a quarter or a half turn, it is the same diamond; turned 30 degrees, a circle stands + // in for it. + let turned = |angle: f64| { + let mut gp = GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() }); + gp.angle = angle; + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { name: "Gem".into(), paint: Paint::Gradient(Box::new(gp)), global: false, spot: false }], + groups: vec![], + }; + written(&lib, PaletteFormat::Css) + }; + assert!(turned(90.0).contains(&want) && turned(-180.0).contains(&want), "{}", turned(90.0)); + assert!(turned(30.0).contains("--gem: radial-gradient(circle, #ffffff 0%, #000000 100%);"), "{}", turned(30.0)); +} + #[test] fn css_preserves_fractional_gradient_stop_positions() { for kind in [GradientKind::Linear, GradientKind::Radial] { diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 2e19ad44a3..b1aa9727ba 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -444,13 +444,14 @@ impl Appearance { } } /// Map placed gradients through a warp, given its local affine approximation at a point (taken - /// at each gradient's centre: the start of a radial, the middle of a linear vector). Freeform - /// points each follow the warp at their own position. + /// at each gradient's center: the start of a radial, conic or diamond, the middle of a linear + /// vector). + /// Freeform points each follow the warp at their own position. pub fn warp_gradients(&mut self, near: &dyn Fn(vectorcraft_geom::Point) -> vectorcraft_geom::Affine) { for g in self.gradients_mut() { let freeform = g.freeform.take(); if let Some(geom) = g.geom { - let c = if g.gradient.kind == vectorcraft_color::GradientKind::Radial { geom.start } else { geom.start.midpoint(geom.end) }; + let c = if g.gradient.kind.is_centered() { geom.start } else { geom.start.midpoint(geom.end) }; g.transform(near(c)); } g.freeform = freeform.map(|mut f| { diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 0887961730..407780177e 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -26,11 +26,16 @@ impl WidthProfile { pub fn at(&self, t: f64) -> (f64, f64) { Self::at_points(&self.points, t) } - /// [`Self::at`] of a profile's points (a preset's or a saved profile's). Each side runs through - /// its points on a monotone cubic curve (Fritsch–Carlson): it flows through a width point - /// without a kink, turns flat at a point wider or narrower than both neighbours, and never - /// goes past either point of the span it is in (#5714). Points on one straight line stay on - /// it. A step (two points at one position, [`Self::around`]) ends the curve on each side of it. + /// [`Self::at`] of a profile's points (a preset's or a saved profile's). + /// + /// Each side runs through its points on a cubic Hermite curve, its slope at each one the + /// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1 continuous + /// and monotone between points, so it never overshoots them, a point eases into its neighbours + /// instead of making a corner, and moving one reshapes the curve as far as its neighbours' + /// neighbours (their slopes depend on it). The ends of a run use the one-sided PCHIP slope + /// from its first two secants, or the secant when it has only two points, so a two-point + /// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still + /// a step: each run either side ends independently at it. pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { if p.is_empty() { return (1.0, 1.0); @@ -71,9 +76,10 @@ impl WidthProfile { // Two swells between narrow necks. ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] }, ]; - /// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. Each - /// side stays between the widths of the two points of each span ([`Self::at_points`]), but the - /// two sides needn't peak together, so a span counts its wider left and its wider right. + /// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. + /// Each side's smooth curve stays between the widths of the two points of each span + /// ([`Self::at_points`]), but the two sides needn't peak together, so a span counts its wider + /// left and its wider right. pub fn widest(&self) -> f64 { let p = &self.points; if p.is_empty() { @@ -249,11 +255,27 @@ impl AngleProfile { /// How close two width points' positions are to make a step ([`WidthProfile::around`]). const STEP: f64 = 1e-7; +/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants. +/// A sign change caps the slope, and a slope that turns back on the first secant is flattened. +/// Runs of only two points use their secant instead (see [`tangent`]). +fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 { + let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); + if !m.is_finite() || m * d0 <= 0.0 { + return 0.0; + } + if d0 * d1 < 0.0 { + return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) }; + } + m +} + /// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in /// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where -/// the point is wider or narrower than both neighbours, the weighted harmonic mean of the slopes -/// of the spans on either side elsewhere (never more than three times either, so no span -/// overshoots its points), and the span's own slope at an end of the profile or beside a step. +/// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the +/// slopes of the spans on either side elsewhere (never more than three times either, so no span +/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their +/// secant when the run has only two points; a step ends the run on each side, so the points either +/// side of it do not see across it. fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 { let Some(q) = p.get(j) else { return 0.0 }; let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP); @@ -268,8 +290,18 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f let (h0, h1) = (q.0 - a.0, b.0 - q.0); 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) } - (Some(a), None) => slope(a, q), - (None, Some(b)) => slope(q, b), + // The end of a run: its previous two points set a one-sided three-point slope, or its + // secant when the run has only two points (the point before `a` is on the other side of a + // step, or does not exist). + (Some(a), None) => { + let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) }; + end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a)) + } + // The start of a run, symmetrically. + (None, Some(b)) => { + let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) }; + end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next)) + } (None, None) => 0.0, } } @@ -424,12 +456,12 @@ mod tests { #[test] fn widths_run_smoothly_through_width_points() { // A swell in the middle: flat at its widest, and a quarter of the way along above the - // straight ramp from 1 to 3 (2). + // straight ramp from 1 to 3 (2) because the end eases out of the first point. let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] }; let (before, after) = slopes(&swell, 0.5); assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}"); let (l, r) = swell.at(0.25); - assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}"); + assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}"); // Rising on both sides of a point: the slope is the same either side of it. let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] }; let (before, after) = slopes(&rise, 0.3); diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index 0a1b3e1a5d..aa2ba0100c 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -197,12 +197,85 @@ fn strokes_without_pressure_round_trip_unchanged() { fn profile_interp() { let p = WidthProfile::lens(); assert_eq!(p.at(0.5), (1.0, 1.0)); - // Half way up the lens the width curves above the straight ramp (0.5), flattening into its - // widest point (#5714). - assert_eq!(p.at(0.25), (0.625, 0.625)); + // The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the + // 0.5 a straight taper would give. + assert_eq!(p.at(0.25), (0.75, 0.75)); assert_eq!(p.at(2.0), (0.0, 0.0)); } +/// The width runs smoothly between points: it passes through them, has one slope either side +/// of one, and never overshoots the widths its points set. +#[test] +fn profile_is_smooth_between_points() { + let p = [(0.0, 1.0, 2.0), (0.5, 0.2, 2.0), (1.0, 1.0, 2.0)]; + assert!((WidthProfile::at_points(&p, 0.5).0 - 0.2).abs() < 1e-12); + let slope = |t: f64| (WidthProfile::at_points(&p, t + 1e-6).0 - WidthProfile::at_points(&p, t - 1e-6).0) / 2e-6; + // A local minimum at the middle point is flat there, so the two sides agree. + assert!(slope(0.5).abs() < 1e-3, "{}", slope(0.5)); + for k in 0..=100 { + let w = WidthProfile::at_points(&p, k as f64 / 100.0).0; + assert!((0.2..=1.0).contains(&w), "{w} at {k}"); + } + // The side with no points of its own stays flat. + for k in 0..=100 { + assert!((WidthProfile::at_points(&p, k as f64 / 100.0).1 - 2.0).abs() < 1e-12); + } +} + +/// A run with only two points takes its secant as both end slopes, so it stays a straight +/// taper on each side instead of becoming a smoothstep. +#[test] +fn profile_two_point_runs_are_linear() { + let p = [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)]; + for k in 0..=100 { + let t = k as f64 / 100.0; + let (l, r) = WidthProfile::at_points(&p, t); + assert!((l - t).abs() < 1e-12, "left {l} at {t}"); + assert!((r - (1.0 - t)).abs() < 1e-12, "right {r} at {t}"); + } +} + +/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75, +/// above the 0.5 a straight line between its points would give. +#[test] +fn profile_lens_is_convex() { + let p = WidthProfile::lens(); + assert!((p.at(0.25).0 - 0.75).abs() < 1e-12); + assert!((p.at(0.75).0 - 0.75).abs() < 1e-12); + for k in 1..25 { + let t = k as f64 / 100.0; + assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0); + assert!(p.at(1.0 - t).0 > 2.0 * t, "{} at {}", p.at(1.0 - t).0, 1.0 - t); + } +} + +/// A step still steps, and the smooth runs either side meet it flat. +#[test] +fn profile_steps_stay_steps() { + let p = [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 2.0, 2.0)]; + assert_eq!(WidthProfile::at_points(&p, 0.5), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.5 + 1e-6), (2.0, 2.0)); + assert_eq!(WidthProfile::at_points(&p, 0.5 - 1e-6), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.25), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.75), (2.0, 2.0)); +} + +/// Moving a point only reshapes the segments beside it (local influence), not the whole path. +#[test] +fn profile_points_only_affect_the_curve_around_them() { + // A monotone run, so no neighbouring slope is held flat by a local extremum. + let a = [(0.0, 0.0, 0.0), (0.25, 0.3, 0.3), (0.5, 0.5, 0.5), (0.75, 0.7, 0.7), (1.0, 1.0, 1.0)]; + let mut b = a; + b[3] = (0.75, 0.9, 0.9); + // Moving p[3] changes the slopes at p[2] and p[3], so p[1] and p[4] also shape the + // curve: nothing before p[1] may move. + for k in 0..=24 { + let t = k as f64 / 100.0; + assert_eq!(WidthProfile::at_points(&a, t), WidthProfile::at_points(&b, t), "at {t}"); + } + assert_ne!(WidthProfile::at_points(&a, 0.3), WidthProfile::at_points(&b, 0.3)); +} + #[test] fn profile_presets_round_trip_their_ids() { for p in WidthProfile::PRESETS { diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index ac5db48c76..fd06ea9093 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -1,4 +1,4 @@ -use super::{Arc, Deserialize, LayerColor, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip}; +use super::{Arc, Deserialize, LayerColor, Node, NodeId, Rect, Serialize, SymbolBoxes, skip}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Artboard { @@ -204,12 +204,7 @@ impl LockedArtboards<'_> { /// [`LockedArtboards::holds`] for new art too: is `n` on a locked artboard, whether or not it /// is new art? pub fn overlaps(&self, n: &Node) -> bool { - if self.rects.is_empty() - || !n.visible - || n.is_layer() - || matches!(n.kind, NodeKind::Path { guide: true, .. }) - || self.pattern_art.contains(&n.id) - { + if self.rects.is_empty() || !n.visible || n.is_layer() || n.is_guide() || self.pattern_art.contains(&n.id) { return false; } if let Some(held) = self.held.borrow().get(&n.id) { diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d6b7eda2c5..4e51777060 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1051,17 +1051,51 @@ fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option> { /// - a pinned spine (`key_anchors`): the stored spine's first subpath with each key's anchor (and /// its handles) moved onto the key's centre, so moving a key moves its end of the spine; /// - a spine from Replace Spine: its first subpath, `None` for the anchors (the keys spread -/// evenly along it by arc length). +/// evenly along it by arc length) while the keys sit there; once one is moved off, pinned as +/// above at the anchors where they were spread. +/// +/// `None` for a blend made without a spine ([`BlendSpec::no_spine`]). pub fn blend_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Option>)> { + if spec.no_spine { + return None; + } + layout_spine(keys, spec) +} + +/// The spine `spec` stores, unless the blend was made without one. +fn stored_spine(spec: &BlendSpec) -> Option<&PathData> { + spec.spine.as_ref().filter(|_| !spec.no_spine) +} + +/// [`blend_spine`] for placing the steps: a blend made without a spine still places them on the +/// straight lines between its key centers. +fn layout_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Option>)> { if keys.len() < 2 { return None; } - let Some(stored) = &spec.spine else { + let Some(stored) = stored_spine(spec) else { let centers: Vec = keys.iter().map(|k| center_of(k)).collect(); return Some((PathData::single(SubPath::polyline(¢ers, false)), Some((0..keys.len()).collect()))); }; let mut first = stored.subpaths.first()?.clone(); - let Some(ka) = pinned(spec, keys.len(), first.anchors.len()) else { return Some((PathData::single(first), None)) }; + let Some(ka) = pinned(spec, keys.len(), first.anchors.len()) else { + let mut path = PathData::single(first); + // A key moved off where Replace Spine spread it takes its point of the spine along, as + // on a pinned spine; otherwise the steps would put it back on the spine (#6809). + if Spine::new(&path).is_none_or(|sp| keys_spread_along(keys, &sp)) { + return Some((path, None)); + } + let Some(mut ka) = spread_anchors(&mut path, keys.len()) else { return Some((path, None)) }; + let mut first = path.subpaths.into_iter().next()?; + open_at_start(&mut first, &mut ka); + for (k, &ai) in keys.iter().zip(&ka) { + if let Some(a) = first.anchors.get_mut(ai) { + let d = center_of(k) - a.p; + a.translate(d); + } + } + return Some((PathData::single(first), Some(ka))); + }; for (k, &ai) in keys.iter().zip(&ka) { let c = center_of(k); if let Some(a) = first.anchors.get_mut(ai) { @@ -1075,21 +1109,62 @@ pub fn blend_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Op /// [`blend_spine`] with every key on an anchor: a spine from Replace Spine gets anchors where its /// keys sit (by arc length), so editing it keeps them in place. pub fn pin_spine(keys: &[Arc], spec: &BlendSpec) -> Option<(PathData, Vec)> { - let (mut path, anchors) = blend_spine(keys, spec)?; - if let Some(a) = anchors { - return Some((path, a)); + // A spine from Replace Spine is pinned as stored, even with a key moved off it (where + // [`blend_spine`] moves that key's point along): the layout is the same. + if keys.len() >= 2 + && let Some(first) = stored_spine(spec).and_then(|s| s.subpaths.first()) + && pinned(spec, keys.len(), first.anchors.len()).is_none() + { + let mut path = PathData::single(first.clone()); + let mut out = spread_anchors(&mut path, keys.len())?; + // A closed spine's end keys get points of their own, so that once pinned each still + // moves only its own end. + let mut sp = path.subpaths.into_iter().next()?; + open_at_start(&mut sp, &mut out); + return Some((PathData::single(sp), out)); } + let (path, anchors) = blend_spine(keys, spec)?; + Some((path, anchors?)) +} + +/// Do `keys` sit where a spine from Replace Spine spreads them: evenly along `spine` by arc length +/// (within a hundredth of a point, as [`anchor_at_length`] matches anchors)? +fn keys_spread_along(keys: &[Arc], spine: &Spine) -> bool { let k = keys.len(); - let total = Spine::new(&path)?.length(); + keys.iter().enumerate().all(|(i, key)| { + let f = if k > 1 { i as f64 / (k - 1) as f64 } else { 0.0 }; + center_of(key).distance(spine.at(f).0) < 0.01 + }) +} + +/// Open closed spine `sp` at its first anchor when the last key sits there with the first (as +/// [`spread_anchors`] puts them): a copy of that anchor at the end takes the closing segment and +/// the last key, so the two end keys move their ends of the spine apart. +fn open_at_start(sp: &mut SubPath, ka: &mut [usize]) { + let Some(&start) = sp.anchors.first() else { return }; + if !sp.closed || ka.len() < 2 { + return; + } + if let Some(last) = ka.last_mut().filter(|a| **a == 0) { + *last = sp.anchors.len(); + sp.anchors.push(start); + sp.closed = false; + } +} + +/// The anchors of `path`'s first subpath that `k` keys spread evenly along it by arc length sit +/// on, splitting segments where none is. +fn spread_anchors(path: &mut PathData, k: usize) -> Option> { + let total = Spine::new(path)?.length(); let closed = path.subpaths.first().is_some_and(|s| s.closed); let mut out = vec![0usize]; for i in 1..k.saturating_sub(1) { let s = total * i as f64 / (k - 1) as f64; - out.push(anchor_at_length(&mut path, s)?); + out.push(anchor_at_length(path, s)?); } let last = path.subpaths.first().map_or(0, |sp| if closed { 0 } else { sp.anchors.len().saturating_sub(1) }); out.push(last); - Some((path, out)) + Some(out) } /// The anchor of the first subpath at arc length `s`: an existing one within a hundredth of a @@ -1127,10 +1202,10 @@ impl Rail { /// `None` when nothing moves: no stored spine and the steps keep the page's orientation. fn new(keys: &[Arc], spec: &BlendSpec) -> Option { let rotate = spec.orientation == BlendOrientation::AlignToPath; - if spec.spine.is_none() && !rotate { + if stored_spine(spec).is_none() && !rotate { return None; } - let (path, anchors) = blend_spine(keys, spec)?; + let (path, anchors) = layout_spine(keys, spec)?; let spine = Spine::new(&path)?; let total = spine.length(); let k = keys.len(); @@ -1192,10 +1267,10 @@ impl Rail { /// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing /// moves. pub(crate) fn rail_reach(keys: &[Arc], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option { - if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath { + if stored_spine(spec).is_none() && spec.orientation != BlendOrientation::AlignToPath { return None; } - let spine = blend_spine(keys, spec)?.0.bounds()?; + let spine = layout_spine(keys, spec)?.0.bounds()?; let radius = keys .iter() .filter_map(|k| { @@ -1404,7 +1479,9 @@ pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { for j in 1..=n { // Even position of the step, then where the easing puts its shape and its colours. let u = j as f64 / (n + 1) as f64; - let (t, tc) = (if rail.is_some() { spec.ease.apply(u) } else { u }, spec.color_position(u)); + // Easing needs a spine: a blend made without one keeps its steps evenly spaced. + let eased = rail.is_some() && !spec.no_spine; + let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u)); let mut s = lerp.at_eased(t, tc); if let Some(r) = &rail { r.place(&mut s, i, t); diff --git a/crates/doc/src/canvas_range.rs b/crates/doc/src/canvas_range.rs index 1142356968..491b79f158 100644 --- a/crates/doc/src/canvas_range.rs +++ b/crates/doc/src/canvas_range.rs @@ -15,7 +15,8 @@ pub struct BeyondCanvas { /// Objects removed whole (a layer or group keeps its children within the canvas). pub objects: usize, pub artboards: usize, - /// Guides beyond the canvas, and the artboard guides of the artboards removed. + /// Guides beyond the canvas, the artboard guides of the artboards removed, and the layer + /// guides of the layers removed. pub guides: usize, /// The ruler origin was beyond the canvas and is back at the origin. pub ruler_origin: bool, @@ -100,11 +101,20 @@ fn layers_in(n: &Node, layers: &mut Vec) { } } +/// How many ruler guides the layers in `n` hold, if it is a layer or group. +fn guides_in(n: &Node) -> usize { + match clipping(n) { + None => 0, + Some(_) => n.children().into_iter().flatten().map(|c| if c.is_ruler_guide() { 1 } else { guides_in(c) }).sum(), + } +} + /// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its /// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything /// else goes whole. Only containers holding such an object are copied. Recursion follows the -/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`. -fn drop_children_beyond(node: &mut Arc, dropped: &mut usize, layers: &mut Vec) { +/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and +/// the ruler guides they held to `guides`. +fn drop_children_beyond(node: &mut Arc, dropped: &mut usize, layers: &mut Vec, guides: &mut usize) { if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) { return; } @@ -114,15 +124,34 @@ fn drop_children_beyond(node: &mut Arc, dropped: &mut usize, layers: &mut return true; } if clipping(c).is_some() && !clips_beyond(c) { - drop_children_beyond(c, dropped, layers); + drop_children_beyond(c, dropped, layers, guides); return true; } layers_in(c, layers); + *guides += guides_in(c); *dropped += 1; false }); } +/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many +/// to `dropped`. Only layers holding one are copied. +fn drop_guides(layer: &mut Arc, out: &impl Fn(&Node) -> bool, dropped: &mut usize) { + fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool { + n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out))) + } + if !holds(layer, out) { + return; + } + let Some(children) = Arc::make_mut(layer).children_mut() else { return }; + let before = children.len(); + children.retain(|c| !out(c)); + *dropped += before - children.len(); + for c in children.iter_mut().filter(|c| c.is_layer()) { + drop_guides(c, out, dropped); + } +} + impl Document { /// Remove what a read file has beyond the canvas ([`MAX_COORD`], or not finite): objects /// (see [`BeyondCanvas::objects`]; a top-level layer clipping by a path beyond it is emptied @@ -141,12 +170,14 @@ impl Document { for c in children.iter() { layers_in(c, &mut layers); } - gone.objects += children.len(); - children.clear(); + // The layer's own ruler guides stay; only its art goes, with its sublayers' guides. + gone.objects += children.iter().filter(|c| !c.is_ruler_guide()).count(); + gone.guides += children.iter().filter(|c| !c.is_ruler_guide()).map(|c| guides_in(c)).sum::(); + children.retain(|c| c.is_ruler_guide()); *clip = false; } } else { - drop_children_beyond(layer, &mut gone.objects, &mut layers); + drop_children_beyond(layer, &mut gone.objects, &mut layers, &mut gone.guides); } } if gone.objects > 0 { @@ -161,9 +192,18 @@ impl Document { self.retire_artboard_id(*id); } gone.artboards = removed.len(); - let guides = self.guides.len(); - self.guides.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l))); - gone.guides = guides - self.guides.len(); + // The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]). + let guides = self.saved_guides.len(); + self.saved_guides + .retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l))); + gone.guides += guides - self.saved_guides.len(); + let out = |n: &Node| match n.kind { + NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)), + _ => false, + }; + for layer in &mut self.layers { + drop_guides(layer, &out, &mut gone.guides); + } if !(in_range(self.ruler_origin.x) && in_range(self.ruler_origin.y)) { self.ruler_origin = Point::ZERO; gone.ruler_origin = true; @@ -232,12 +272,18 @@ mod tests { let far = Artboard { id: 9, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() }; d.artboards.push(far); let guide = |pos: f64, artboard| Guide { artboard, ..Guide::new(false, pos) }; - d.guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))]; + d.saved_guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))]; d.ruler_origin = Point::new(1e17, 0.0); + // The same guides as nodes, as a document has them once read. + let mut nodes = d.clone(); + assert_eq!(nodes.guides_into_nodes(), 4); let gone = d.drop_beyond_canvas(); assert_eq!(gone, BeyondCanvas { objects: 0, artboards: 1, guides: 3, ruler_origin: true }); assert_eq!(d.artboards.len(), 1); - assert_eq!(d.guides, [guide(50.0, None)], "the far artboard's own guide goes with it"); + assert_eq!(d.saved_guides, [guide(50.0, None)], "the far artboard's own guide goes with it"); + assert_eq!(nodes.drop_beyond_canvas(), gone); + let left: Vec<(bool, f64, Option)> = nodes.ruler_guides().iter().map(|g| (g.vertical, g.pos, g.artboard)).collect(); + assert_eq!(left, [(false, 50.0, None)]); assert_eq!(d.ruler_origin, Point::ZERO); assert_eq!( gone.note().unwrap(), @@ -290,6 +336,21 @@ mod tests { let layer = d2.layers[0].id.0; assert_eq!(d2.drop_beyond_canvas().objects, 1); assert_eq!(ids(&d2), [layer, 10]); + // The guides of a sublayer emptied out of a top-level layer go with it, counted. + let probe = Document::new(1.0, 1.0); + let sub = sublayer(&probe, 40, vec![rect(41, 0.0)], false); + let mut d3 = doc(vec![rect(10, 1e17), sub]); + if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut d3.layers[0]).kind { + *clip = true; + } + d3.saved_guides = + vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d3.layers[0].id), ..Guide::new(true, 5.0) }]; + let mut nodes = d3.clone(); + assert_eq!(nodes.guides_into_nodes(), 2); + let gone = d3.drop_beyond_canvas(); + assert_eq!((gone.objects, gone.guides), (2, 1), "the clipping path, the sublayer and its guide; the layer's own guide stays"); + assert_eq!(nodes.drop_beyond_canvas(), gone); + assert_eq!(nodes.ruler_guides().len(), 1); assert_eq!(d.drop_beyond_canvas(), BeyondCanvas::default()); } @@ -310,7 +371,8 @@ mod tests { let probe = Document::new(1.0, 1.0); let sub = sublayer(&probe, 40, vec![rect(41, 1e17), rect(42, 0.0)], true); let mut d = doc(vec![rect(10, 0.0), rect(11, 1e17), sub]); - d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }]; + d.saved_guides = + vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }]; d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into(); d.assets = vec![ crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None }, @@ -318,9 +380,14 @@ mod tests { ]; d.variables.bindings.insert(NodeId(11), ["v".to_string()].into()); d.variables.bindings.insert(NodeId(10), ["w".to_string()].into()); + // The same guides as nodes, as a document has them once read. + let mut nodes = d.clone(); + assert_eq!(nodes.guides_into_nodes(), 2); let gone = d.drop_beyond_canvas(); assert_eq!((gone.objects, gone.guides), (2, 1), "the far rectangle, the clipping sublayer and its layer guide"); - assert_eq!(d.guides.len(), 1, "the guide of a layer that stays, stays"); + assert_eq!(nodes.drop_beyond_canvas(), gone, "a guide node goes with its sublayer, counted as a saved one is"); + assert_eq!(nodes.ruler_guides().len(), 1); + assert_eq!(d.saved_guides.len(), 1, "the guide of a layer that stays, stays"); assert_eq!(d.saved_selections[0].objects, [NodeId(10)]); assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::>(), [(2, vec![NodeId(10)])]); assert_eq!(d.variables.bindings.keys().copied().collect::>(), [NodeId(10)]); diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 5abba9c63b..63b7e0ce7c 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -132,7 +132,7 @@ fn limit(nodes: &mut Vec>, depth: usize) -> bool { out.push(a); continue; } - let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); + let clip = n.clips(); let (visible, locked) = (n.visible, n.locked); let mut held = n.children_mut().map(std::mem::take).unwrap_or_default(); if clip && !held.is_empty() { @@ -148,6 +148,13 @@ fn limit(nodes: &mut Vec>, depth: usize) -> bool { // What it held takes its place, and is looked at in its turn. left.extend(held.into_iter().rev()); } + // The ruler guides of a sublayer merged into its parent layer go above the parent's art, with + // the parent's own. + if out.iter().any(|c| c.is_ruler_guide()) { + let (guides, art): (Vec<_>, Vec<_>) = out.into_iter().partition(|c| c.is_ruler_guide()); + out = art; + out.extend(guides); + } *nodes = out; true } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index fecdc9bacb..708d0aee03 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -10,7 +10,7 @@ use super::{ impl Document { /// Is everything but the layers the same in `other`, as the next version of the document after - /// an edit of its art? The id counter and the id index are left out, and art outside the layers + /// an edit of its art? The id counter and the caches are left out, and art outside the layers /// (symbols, patterns, graph designs) compares by identity, which an edit keeps for what it /// doesn't change: quick for every frame of an animation. pub fn same_outside_layers(&self, other: &Self) -> bool { @@ -38,7 +38,7 @@ impl Document { text_threads, symbols, graph_designs, - guides, + saved_guides, views, saved_selections, variables, @@ -77,6 +77,7 @@ impl Document { opened_artboard: _, units_from_file: _, index: _, + guide_cache: _, } = self; *version == other.version && *title == other.title @@ -98,7 +99,7 @@ impl Document { && symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) && graph_designs.len() == other.graph_designs.len() && graph_designs.iter().zip(&other.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) - && *guides == other.guides + && *saved_guides == other.saved_guides && *views == other.views && *saved_selections == other.saved_selections && *variables == other.variables @@ -221,7 +222,7 @@ impl Document { text_threads: vec![], symbols: vec![], graph_designs: vec![], - guides: vec![], + saved_guides: vec![], views: vec![], saved_selections: Default::default(), variables: Default::default(), @@ -260,6 +261,7 @@ impl Document { opened_artboard: None, units_from_file: false, index: Default::default(), + guide_cache: Default::default(), }; let id = d.alloc_id(); d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0)))); @@ -501,11 +503,13 @@ impl Document { } } - /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). + /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes + /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). pub fn insert(&mut self, parent: Option, index: usize, node: Node) -> Result { let id = node.id; + self.check_ruler_guide_place(&node, parent)?; let ch = self.children_mut(parent)?; - let i = index.min(ch.len()); + let i = Node::insert_index(ch, index, &node); ch.insert(i, Arc::new(node)); Ok(id) } @@ -522,20 +526,33 @@ impl Document { Ok(ch.remove(idx)) } - /// Move a node to `parent` at `index` (index measured after removal). + /// Move a node to `parent` at `index` (index measured after removal), clamped as + /// [`Document::insert`] clamps it. pub fn move_node(&mut self, id: NodeId, parent: Option, index: usize) -> Result<(), DocError> { if let Some(p) = parent && self.ancestry(p).is_some_and(|a| a.contains(&id)) { return Err(DocError::Invalid("cannot move an object into itself".into())); } + if let Some(n) = self.node(id) { + self.check_ruler_guide_place(n, parent)?; + } let n = self.remove(id)?; let ch = self.children_mut(parent)?; - let i = index.min(ch.len()); + let i = Node::insert_index(ch, index, &n); ch.insert(i, n); Ok(()) } + /// An error when `n` is a ruler guide and `parent` is not a layer or sublayer: a ruler guide is + /// always a direct child of one ([`NodeKind::RulerGuide`]). + fn check_ruler_guide_place(&self, n: &Node, parent: Option) -> Result<(), DocError> { + if n.is_ruler_guide() && !parent.and_then(|p| self.node(p)).is_some_and(Node::is_layer) { + return Err(DocError::Invalid("a ruler guide goes only directly in a layer or sublayer".into())); + } + Ok(()) + } + /// Position of `id` within its parent: (parent, index, sibling count). pub fn position(&self, id: NodeId) -> Option<(Option, usize, usize)> { let parent = self.parent_of(id); @@ -739,7 +756,7 @@ impl Document { for c in n.children().into_iter().flatten() { if c.is_layer() { objects(c, out); - } else { + } else if !c.is_ruler_guide() { out.insert(c.id); } } @@ -757,7 +774,8 @@ impl Document { } /// The object of a layer or sublayer that holds node `id`: `id` itself when it is one, else - /// the group or other object around it right inside a layer. None for a layer or sublayer. + /// the group or other object around it right inside a layer. None for a layer, a sublayer or a + /// ruler guide. pub fn layer_object(&self, id: NodeId) -> Option<&Node> { self.layer_object_at(&self.index_path(id)?) } @@ -768,6 +786,9 @@ impl Document { let mut nodes = &self.layers; for &i in path { let n = nodes.get(i)?; + if n.is_ruler_guide() { + return None; + } if !n.is_layer() { return Some(n.as_ref()); } diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index ebb2fc44eb..0f1ec463c4 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -56,9 +56,12 @@ impl Document { if self.saved_selections.is_empty() { return; } + // A saved selection names objects; ruler guides are not among them. let mut ids = std::collections::HashSet::new(); self.walk(|n| { - ids.insert(n.id); + if !n.is_ruler_guide() { + ids.insert(n.id); + } }); let mut kept: Vec = vec![]; for s in std::mem::take(&mut self.saved_selections) { @@ -101,12 +104,13 @@ impl Document { /// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The /// layer is removed wherever it is, also as a sublayer of another layer; an id that names - /// anything other than a layer is left alone. + /// anything other than a layer is left alone. Ruler guides on the layer stay in the document + /// ([`Self::remove_edit_layer`]). pub fn drop_edit_modes(&mut self) { let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)]; for id in layers.into_iter().flatten() { if self.node(id).is_some_and(Node::is_layer) { - let _ = self.remove(id); + let _ = self.remove_edit_layer(id); } } } diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 510de3a4de..4ec7aab1f6 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -1,6 +1,8 @@ use super::document_ext::free_id; use super::guides::Guide; +use super::limits::MAX_NEXT_ID; use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds}; +use std::collections::{BTreeMap, HashSet}; impl Document { /// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol @@ -151,7 +153,7 @@ impl Document { rest.iter().any(|m| has(m, s, inside, true)) } NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect, exact)), - NodeKind::Path { guide: true, .. } => false, + NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => false, _ => art_box_meets(c, s, rect, exact), } } @@ -171,6 +173,195 @@ impl Document { art } + /// Put the ruler guide nodes a file holds where ruler guides go: directly in a layer or + /// sublayer, above its art. A ruler guide below art in a layer moves up to the layer's other + /// guides, keeping their order. A ruler guide anywhere else (at the top level, in a group or + /// another object, in opacity-mask art, in a symbol, a graph design or a pattern) is removed. + /// Returns how many were removed. + pub fn tidy_ruler_guides(&mut self) -> usize { + let mut gone = self.layers.len(); + self.layers.retain(|l| !l.is_ruler_guide()); + gone -= self.layers.len(); + for l in &mut self.layers { + if layer_untidy(l) { + gone += tidy_layer(Arc::make_mut(l)); + } + } + let others = self + .symbols + .iter_mut() + .map(|s| &mut s.art) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in others { + if root.is_ruler_guide() { + *root = Arc::new(Node::group(root.id, vec![])); + gone += 1; + } else if any_guide(root) { + gone += drop_guides_below(Arc::make_mut(root)); + } + } + gone + } + + /// Make the saved ruler guides (read from a file: [`Document::guides_to_saved`]'s list) into + /// [`NodeKind::RulerGuide`] nodes, each at the top of its layer, in list order. A guide on a + /// layer or sublayer the document has goes on it; one on no layer, or on a layer that is gone, + /// goes on the top visible, unlocked layer ([`Self::default_layer`]), or on a new "Layer 1" + /// when there is none. A guide keeps its saved id when no other node, slice or guide has it, + /// and its name, lock and visibility. The saved list is emptied, so running this again does + /// nothing. Returns how many guides became nodes. + pub fn guides_into_nodes(&mut self) -> usize { + let saved = std::mem::take(&mut self.saved_guides); + if saved.is_empty() { + return 0; + } + let mut used = HashSet::new(); + self.walk(|n| { + used.insert(n.id); + }); + used.extend(self.slices.iter().map(|s| s.id)); + used.extend(self.assets.iter().map(|a| NodeId(a.id))); + let kept: Vec> = saved.iter().map(|g| g.id.filter(|id| id.0 > 0 && id.0 < MAX_NEXT_ID && used.insert(*id))).collect(); + if let Some(max) = kept.iter().flatten().map(|id| id.0).max() { + self.raise_next_id(max.saturating_add(1)); + } + let mut home = None; + // The guides of each layer, in list order. + let mut by_layer: BTreeMap>> = BTreeMap::new(); + let mut order = vec![]; + for (g, id) in saved.iter().zip(kept) { + let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) { + Some(l) => l, + None => match home { + Some(h) => h, + None => { + let h = self.default_layer().unwrap_or_else(|| self.add_layer(None)); + home = Some(h); + h + } + }, + }; + let id = id.unwrap_or_else(|| self.alloc_id()); + let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }); + n.name = g.name.clone(); + n.locked = g.locked; + n.visible = !g.hidden; + if !by_layer.contains_key(&layer) { + order.push(layer); + } + by_layer.entry(layer).or_default().push(Arc::new(n)); + } + for layer in order { + let guides = by_layer.remove(&layer).unwrap_or_default(); + if let Ok(ch) = self.children_mut(Some(layer)) { + ch.extend(guides); + } + } + saved.len() + } + + /// Take the ruler guide nodes out of the layers and put them in the saved list, by ascending + /// id, each naming its layer, after any entries not yet made into nodes: the form a file keeps + /// them in, readable by versions from before ruler guides were nodes. For saving a copy of + /// the document; [`Self::guides_into_nodes`] reverses it. + pub fn guides_to_saved(&mut self) { + let guides = self.ruler_guides(); + if guides.is_empty() { + return; + } + for l in &mut self.layers { + if l.holds_ruler_guides() { + Arc::make_mut(l).strip_ruler_guides(); + } + } + self.saved_guides.extend(guides); + } + + /// Every ruler guide, by ascending id, with the layer or sublayer it is on, its id, name and + /// its own lock and visibility. A guide's place in this list is its index in the guide + /// commands. + pub fn ruler_guides(&self) -> Vec { + if let Some(listed) = self.guide_cache.get(&self.layers) { + return listed.as_ref().clone(); + } + fn visit(layer: &Node, out: &mut Vec) { + for c in layer.children().into_iter().flatten() { + if let Some(g) = guide_of(c, layer.id) { + out.push(g); + } else if c.is_layer() { + visit(c, out); + } + } + } + let mut out = vec![]; + for l in &self.layers { + visit(l, &mut out); + } + out.sort_by_key(|g| g.id); + self.guide_cache.set(&self.layers, &out); + out + } + + /// Ruler guide `id`, as [`Self::ruler_guides`] lists it. None when `id` is not a ruler guide + /// on a layer. + pub fn ruler_guide(&self, id: NodeId) -> Option { + let layer = self.parent_of(id)?; + guide_of(self.node(id)?, layer) + } + + /// Change ruler guide `id` with `f` (its line, its artboard; the layer, id, name, lock and + /// visibility fields are not read back). Returns false when `id` is not a ruler guide. + pub fn edit_ruler_guide(&mut self, id: NodeId, f: impl FnOnce(&mut Guide)) -> bool { + let Some(mut g) = self.ruler_guide(id) else { return false }; + f(&mut g); + let Some(n) = self.node_mut(id) else { return false }; + n.kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }; + true + } + + /// Add ruler guide `g` as a node with a new id at the top of its layer: `g.layer` when the + /// document has that layer or sublayer, else the top visible, unlocked layer + /// ([`Self::default_layer`]), or a new "Layer 1" when there is none. Its name, lock and + /// visibility come from `g`. Returns the new id. + pub fn add_ruler_guide(&mut self, g: &Guide) -> NodeId { + let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) { + Some(l) => l, + None => self.default_layer().unwrap_or_else(|| self.add_layer(None)), + }; + let id = self.alloc_id(); + let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }); + n.name = g.name.clone(); + n.locked = g.locked; + n.visible = !g.hidden; + if let Ok(ch) = self.children_mut(Some(layer)) { + ch.push(Arc::new(n)); + } + id + } + + /// Remove node `id`, the temporary layer of opacity-mask, symbol or pattern editing, keeping the + /// ruler guides on it and on its sublayers: they go to the top of the top visible, unlocked + /// layer left ([`Self::default_layer`]), or of a new "Layer 1" when no layer is left, where a + /// saved guide whose layer is gone opens. Returns the removed node, without the guides. + pub fn remove_edit_layer(&mut self, id: NodeId) -> Result, crate::DocError> { + let mut layer = self.remove(id)?; + if !layer.holds_ruler_guides() { + return Ok(layer); + } + let mut guides = vec![]; + layer.walk(&mut |c| { + if c.is_ruler_guide() { + guides.push(Arc::new(c.clone())); + } + }); + Arc::make_mut(&mut layer).strip_ruler_guides(); + let home = self.default_layer().unwrap_or_else(|| self.add_layer(None)); + self.children_mut(Some(home))?.extend(guides); + Ok(layer) + } + /// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its /// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose /// artboard is gone. @@ -179,79 +370,39 @@ impl Document { Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }) } + /// The ruler guide node `g` names, if this document has it. + fn guide_node(&self, g: &Guide) -> Option { + g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide)) + } + /// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has. fn guide_layer(&self, g: &Guide) -> Option { g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) } - /// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is - /// visible? A guide whose layer is gone shows as one on no layer. + /// Is ruler guide `g` shown: its node, and the layers it is on, visible? A guide that is not a + /// node of this document shows unless hidden itself or on a hidden layer. pub fn guide_shown(&self, g: &Guide) -> bool { - self.guide_layer(g).is_none_or(|l| self.is_visible(l)) - } - - /// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked? - pub fn guide_editable(&self, g: &Guide) -> bool { - self.guide_layer(g).is_none_or(|l| self.is_editable(l)) - } - - /// Put the ruler guides on no layer this document has (from files saved before guides had - /// layers, or of layers merged into `layer`) on layer `layer`. Returns how many. - pub fn rehome_guides(&mut self, layer: NodeId) -> usize { - let lost: Vec = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect(); - let mut n = 0; - for (g, lost) in self.guides.iter_mut().zip(lost) { - if lost { - g.layer = Some(layer); - n += 1; - } + match self.guide_node(g) { + Some(id) => self.is_visible(id), + None => !g.hidden && self.guide_layer(g).is_none_or(|l| self.is_visible(l)), } - n } - /// Put the ruler guides on no layer (from files saved before guides had layers), or on one that - /// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many. - pub fn adopt_guides(&mut self) -> usize { - self.default_layer().map_or(0, |home| self.rehome_guides(home)) + /// Can ruler guide `g` be picked, moved and deleted: shown, and neither it nor its layers + /// locked? + pub fn guide_editable(&self, g: &Guide) -> bool { + match self.guide_node(g) { + Some(id) => self.is_editable(id), + None => !g.hidden && !g.locked && self.guide_layer(g).is_none_or(|l| self.is_editable(l)), + } } - /// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in - /// step. Guides on no layer stay. Returns how many went. - pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize { - let gone: Vec = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect(); - self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false)) - } - - /// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made - /// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies - /// the objects on it. Returns how many. - pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize { - let layers = |n: &Node| { - let mut out = vec![]; - n.walk(&mut |c| { - if c.is_layer() { - out.push(c.id); - } - }); - out - }; - let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect(); - let copies: Vec = self - .guides - .iter() - .filter_map(|g| { - let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1; - Some(Guide { layer: Some(to), ..g.clone() }) - }) - .collect(); - let n = copies.len(); - self.guides.extend(copies); - n - } - - /// The ruler guides on layer `layer` (not its sublayers'), by index. - pub fn guides_on(&self, layer: NodeId) -> impl Iterator + '_ { - self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer)) + /// The ruler guides directly on layer `layer` (not its sublayers'), by ascending id. + pub fn guides_on(&self, layer: NodeId) -> Vec { + let mut out: Vec = self.children(Some(layer)).into_iter().flatten().filter_map(|c| guide_of(c, layer)).collect(); + out.sort_by_key(|g| g.id); + out } /// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)? @@ -260,45 +411,86 @@ impl Document { self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol) } - /// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their - /// place among the rest (the selected art stays selected). Returns how many went. - pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize { - let kept: Vec = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect(); - // Where each kept guide ends up. - let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0); - for k in &kept { - to.push(k.then_some(n)); - n += usize::from(*k); + /// Keep the ruler guides `keep` accepts, deleting the others; `sel` forgets the deleted ones + /// (the selected art stays selected). Returns how many went. + pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(&Guide) -> bool) -> usize { + let gone: HashSet = self.ruler_guides().into_iter().filter(|g| !keep(g)).filter_map(|g| g.id).collect(); + if gone.is_empty() { + return 0; + } + fn drop(layer: &mut Arc, gone: &HashSet) { + fn holds(n: &Node, gone: &HashSet) -> bool { + n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone))) + } + if !holds(layer, gone) { + return; + } + let Some(ch) = Arc::make_mut(layer).children_mut() else { return }; + ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id))); + for c in ch.iter_mut().filter(|c| c.is_layer()) { + drop(c, gone); + } + } + for l in &mut self.layers { + drop(l, &gone); + } + sel.guides.retain(|id| !gone.contains(id)); + if sel.key_guide.is_some_and(|k| gone.contains(&k)) { + sel.key_guide = None; + } + gone.len() + } + + /// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its + /// position). + fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) { + fn visit(layer: &mut Arc, id: u32, f: &mut impl FnMut(bool, &mut f64)) { + fn holds(n: &Node, id: u32) -> bool { + n.is_layer() + && n.children().is_some_and(|ch| { + ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id)) + }) + } + if !holds(layer, id) { + return; + } + let Some(ch) = Arc::make_mut(layer).children_mut() else { return }; + for c in ch.iter_mut() { + if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) { + if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind { + f(*vertical, pos); + } + } else if c.is_layer() { + visit(c, id, f); + } + } + } + for l in &mut self.layers { + visit(l, id, f); } - sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect(); - sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten()); - let before = self.guides.len(); - let mut flags = kept.into_iter(); - self.guides.retain(|_| flags.next().unwrap_or(true)); - before - self.guides.len() } /// Move the guides of artboard `id` by `d` (along with their artboard). pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) { - for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) { - *g = g.moved(d); - } + self.edit_artboard_guides(id, &mut |vertical, pos| *pos += if vertical { d.x } else { d.y }); } /// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork /// with Artboard). pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) { - for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) { - g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y }; - } + self.edit_artboard_guides(id, &mut |vertical, pos| { + *pos = if vertical { (xf * Point::new(*pos, 0.0)).x } else { (xf * Point::new(0.0, *pos)).y }; + }); } /// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their - /// artboard). + /// artboard), each on its guide's layer with a new id. pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) { let copies: Vec = - self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect(); - self.guides.extend(copies); + self.ruler_guides().into_iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect(); + for g in &copies { + self.add_ruler_guide(g); + } } /// An id for a new artboard: one no artboard has, above the ids given out before and the ids of @@ -311,6 +503,19 @@ impl Document { id } + /// [`Document::next_artboard_id`] when `top` is the highest id the artboards have (`None`: there + /// are none). It reads no artboard unless that id is `u32::MAX`, so a caller that adds many + /// artboards and keeps `top` up to date gets each id in constant time. + pub fn next_artboard_id_above(&self, top: Option) -> u32 { + match top.unwrap_or(0).max(self.retired_artboard_id.get()).checked_add(1) { + Some(id) => { + self.retired_artboard_id.raise(id); + id + } + None => self.next_artboard_id(), + } + } + /// Record that the artboard with `id` was deleted: no later artboard takes its id. pub fn retire_artboard_id(&self, id: u32) { self.retired_artboard_id.raise(id); @@ -367,3 +572,122 @@ impl Document { n } } + +/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide? +fn any_guide(n: &Node) -> bool { + let mut any = false; + crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide()); + any +} + +/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself +/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went. +fn drop_guides_below(n: &mut Node) -> usize { + let mut gone = drop_mask_guides(n); + if let Some(ch) = n.children_mut() { + let before = ch.len(); + ch.retain(|c| !c.is_ruler_guide()); + gone += before - ch.len(); + for c in ch.iter_mut().filter(|c| any_guide(c)) { + gone += drop_guides_below(Arc::make_mut(c)); + } + } + gone +} + +/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide +/// becomes an empty group. Returns how many went. +fn drop_mask_guides(n: &mut Node) -> usize { + let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 }; + if mask.art.is_ruler_guide() { + mask.art = Arc::new(Node::group(mask.art.id, vec![])); + 1 + } else if any_guide(&mask.art) { + drop_guides_below(Arc::make_mut(&mut mask.art)) + } else { + 0 + } +} + +/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so +/// in one of its sublayers? +fn layer_untidy(l: &Node) -> bool { + let Some(ch) = l.children() else { return false }; + let start = Node::guide_run_start(ch); + l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art)) + || ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) }) +} + +/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed. +fn tidy_layer(l: &mut Node) -> usize { + let mut gone = drop_mask_guides(l); + let Some(ch) = l.children_mut() else { return gone }; + for c in ch.iter_mut() { + if c.is_layer() { + if layer_untidy(c) { + gone += tidy_layer(Arc::make_mut(c)); + } + } else if !c.is_ruler_guide() && any_guide(c) { + gone += drop_guides_below(Arc::make_mut(c)); + } + } + if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) { + let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide()); + *ch = art; + ch.extend(guides); + } + gone +} + +/// Node `n`, on layer `layer`, as a [`Guide`] value, if it is a ruler guide. +fn guide_of(n: &Node, layer: NodeId) -> Option { + let NodeKind::RulerGuide { vertical, pos, artboard } = n.kind else { return None }; + Some(Guide { vertical, pos, artboard, layer: Some(layer), id: Some(n.id), name: n.name.clone(), locked: n.locked, hidden: !n.visible }) +} + +/// The list [`Document::ruler_guides`] last made, with weak pointers to the top-level layers it was +/// made from. While a weak pointer to a layer's allocation is held, nothing else can be at that +/// address, and the layer can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut` +/// moves it), so any edit inside a layer, and any layer added, removed or replaced, gives a list of +/// layers the cache does not match. Clones of a document share the cached list. +#[derive(Default)] +pub(crate) struct GuideCache(std::sync::RwLock>); + +/// The top-level layers a guide list was made from, and the list. +type Listed = (Vec>, Arc>); + +impl GuideCache { + /// The cached list, when it was made from `layers`. + fn get(&self, layers: &[Arc]) -> Option>> { + let g = self.0.read().ok()?; + let (from, listed) = g.as_ref()?; + let same = from.len() == layers.len() && from.iter().zip(layers).all(|(w, l)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(l))); + same.then(|| listed.clone()) + } + + /// Keep `listed`, made from `layers`. + fn set(&self, layers: &[Arc], listed: &[Guide]) { + if let Ok(mut g) = self.0.write() { + *g = Some((layers.iter().map(Arc::downgrade).collect(), Arc::new(listed.to_vec()))); + } + } +} + +impl Clone for GuideCache { + fn clone(&self) -> Self { + GuideCache(std::sync::RwLock::new(self.0.read().ok().and_then(|g| g.clone()))) + } +} + +/// A cache, not document content: two documents are equal whatever their caches hold. +impl PartialEq for GuideCache { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl std::fmt::Debug for GuideCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GuideCache") + } +} diff --git a/crates/doc/src/guides.rs b/crates/doc/src/guides.rs index 08f828391b..a3fb9969eb 100644 --- a/crates/doc/src/guides.rs +++ b/crates/doc/src/guides.rs @@ -1,5 +1,8 @@ use super::{Deserialize, NodeId, Serialize, Vec2}; +/// A ruler guide as a value: an entry of the saved `guides` list, or a ruler guide node of a +/// document as [`crate::Document::ruler_guides`] lists it. In a document, ruler guides are +/// [`crate::NodeKind::RulerGuide`] nodes on their layers. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Guide { /// true = vertical guide at `pos` (x), false = horizontal at `pos` (y). @@ -14,12 +17,25 @@ pub struct Guide { /// from before guides had layers, and from files that don't say), always there. #[serde(default, skip_serializing_if = "Option::is_none")] pub layer: Option, + /// The id of its node. None in an entry written before ruler guides were nodes: it gets a new + /// id when the document is read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + /// The name it shows in the Layers panel, if it was given one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Locked on its own (its layer's lock is separate). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub locked: bool, + /// Hidden on its own (its layer's visibility is separate). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub hidden: bool, } impl Guide { /// A canvas guide. pub fn new(vertical: bool, pos: f64) -> Self { - Self { vertical, pos, artboard: None, layer: None } + Self { vertical, pos, artboard: None, layer: None, id: None, name: None, locked: false, hidden: false } } /// Moved by `d` (a vertical guide across, a horizontal one down). diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 3412a7ff40..6eae9c1488 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -588,7 +588,8 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols if !c.visible || editable_only && (c.locked || c.is_template()) { return false; } - if opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + // A ruler guide is picked by the guide commands, never by an object hit test. + if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) { return false; } // (An envelope's content sits where it was, not where the envelope draws it.) @@ -794,6 +795,10 @@ thread_local! { static LEAVES_TESTED: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// What a click at `p` hits on leaf object `n`: its outline, strokes and fills, its frame or its +/// bounds, by kind. Raster effects (drop shadows, glows, blurs) do not take clicks: the area they +/// paint beyond the object is left out here and in [`cull_reach`], so a click there reaches the +/// object under it. fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { #[cfg(test)] LEAVES_TESTED.with(|c| c.set(c.get() + 1)); @@ -1256,7 +1261,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), + Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), // A single object isolated: only it. None => doc .parent_of(s.id) @@ -1285,7 +1290,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if c.visible && !c.locked && !c.is_template() { out.extend(layer_objects(c, r)); } - } else { + } else if !c.is_ruler_guide() { out.push((c, r)); } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 2c0a6984d0..3eac4202b6 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -450,7 +450,7 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() { envelope, NodeKind::Envelope { content, - kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }), + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), fidelity: 100.0, editing: false, options: Default::default(), @@ -1192,7 +1192,7 @@ fn objects_at_edit_contents_uses_general_order() { d.alloc_id(), NodeKind::Envelope { content: vec![inner(a), inner(b)], - kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }), + kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }), fidelity: 100.0, editing: true, options: Default::default(), diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 1f555b74e3..2c5759f202 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -207,8 +207,12 @@ pub struct Document { /// Object › Graph › Design…: art graphs can draw as markers. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub graph_designs: Vec, - #[serde(default)] - pub guides: Vec, + /// The saved form of the ruler guides: read from a file, then made into + /// [`NodeKind::RulerGuide`] nodes on their layers ([`Document::guides_into_nodes`]), and + /// written from those nodes when saving ([`Document::guides_to_saved`]). Empty in between. + /// Each entry read counts as an object against the read's node budget. + #[serde(default, rename = "guides", deserialize_with = "crate::node::counted_list")] + saved_guides: Vec, /// View → New View… (at most [`SavedView::MAX`]); saved with the document. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub views: Vec, @@ -263,7 +267,7 @@ pub struct Document { /// they were copied from instead of the current layer. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub paste_remembers_layers: bool, - /// File → File Info (the title is [`Document::title`]). + /// File → File Info (its title is [`Document::info_title`]). #[serde(default, skip_serializing_if = "skip::is_default")] pub metadata: DocMetadata, /// Effect → Document Raster Effects Settings besides the resolution @@ -351,6 +355,9 @@ pub struct Document { /// Where each node is in the tree, for lookups by id ([`id_index`]): a cache, never saved. #[serde(skip)] index: id_index::IdIndex, + /// The ruler guides as [`Document::ruler_guides`] lists them: a cache, never saved. + #[serde(skip)] + guide_cache: document_guides::GuideCache, } fn ppi72() -> f64 { diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 304c4e70f6..d1eb20ed21 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -49,7 +49,7 @@ mod expand; mod mesh; mod warp; -pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec}; +pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec, BlendSpineMode}; #[cfg(test)] use blend_spec::{blend_color_shift, blend_ramp}; pub use envelope::{ @@ -60,12 +60,12 @@ pub use envelope::{ pub(crate) use expand::max_outset; pub use expand::{ Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with, - expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, subtree_has_live, + expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live, }; #[cfg(test)] use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; -pub use warp::{WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, warp_point}; +pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version}; #[cfg(test)] mod tests { @@ -132,6 +132,200 @@ mod tests { let (r0, a) = (4.0 / PI, 0.5 / (4.0 / PI)); assert!((nx - (r0 - 0.25) * a.sin()).abs() < 1e-12 && (ny - (r0 - (r0 - 0.25) * a.cos())).abs() < 1e-12); } + + /// Each warp style's Bézier net, at points worked out by a separate implementation of the same + /// nets: (style, bend %, horizontal and vertical distortion %, vertical, box w × h, (u, v)) → + /// the point in the box (origin at its top left, y down). + #[test] + fn warp_nets_bend_each_style_as_its_own_patch() { + #[rustfmt::skip] + let samples = [ + ("arc", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -31.1605665, 30.1243045), + ("arc", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 170.241998, 58.8743443), + ("arc", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 50.6087118, 47.6275948), + ("arcLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 18.8784581, 35.5028749), + ("arcLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.486168, 119.348666), + ("arcLower", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 38.1073767, 36.0911629), + ("arcUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 17.3830689, 17.1599587), + ("arcUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.498463, 86.7390371), + ("arcUpper", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 46.1081993, 36.0252855), + ("arch", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 16.261527, 11.6570838), + ("arch", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.984631, 57.3903712), + ("arch", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 49.2508226, 36.2064484), + ("bulge", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 16.261527, 22.6628335), + ("bulge", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 164.984631, 116.087703), + ("bulge", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.965576, 36.2064484), + ("shellLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 10.6489723, 25.9914004), + ("shellLower", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 208.565464, 99.4817585), + ("shellLower", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 41.043987, 36.1302767), + ("shellUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -21.8346746, 41.6042708), + ("shellUpper", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.791499, 90.3680631), + ("shellUpper", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.9282896, 36.1475509), + ("flag", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 55.92), + ("flag", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 55.44), + ("flag", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 58.098, 35.91), + ("wave", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 40.8864), + ("wave", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 83.7792), + ("wave", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 42.33, 35.91), + ("fish", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 19.632), + ("fish", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 62.352), + ("fish", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 44.994, 35.91), + ("rise", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 20.0, 146.64), + ("rise", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 160.0, 102.48), + ("rise", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 118.686, 35.91), + ("fisheye", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 9.1136, 27.2784), + ("fisheye", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 166.2208, 94.1472), + ("fisheye", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 47.514, 35.7048), + ("inflate", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, -0.16, 27.84), + ("inflate", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 166.48, 97.68), + ("inflate", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.75, 36.54), + ("squeeze", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 40.16, 27.84), + ("squeeze", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 153.52, 97.68), + ("squeeze", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.75, 36.0), + ("twist", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.1, 0.3, 32.2472, 27.9588), + ("twist", 60.0, 0.0, 0.0, false, 200.0, 100.0, 0.8, 0.9, 149.1136, 89.2224), + ("twist", -40.0, 30.0, -50.0, true, 150.0, 60.0, 0.25, 0.6, 45.56325, 33.8769), + ]; + for (style, bend, dh, dv, vertical, w, h, u, v, x, y) in samples { + let Some(st) = WarpStyle::from_id(style) else { panic!("{style}") }; + let p = WarpNet::new(st, bend / 100.0, dh / 100.0, dv / 100.0, w, h, vertical).at(u, v); + assert!(p.distance(Point::new(x, y)) < 1e-6, "{style} {bend} {dh} {dv} {vertical} ({u}, {v}): {p:?} vs ({x}, {y})"); + } + } + + /// Arc's edges are concentric circles: at 100 % on a 200 × 100 box the bottom edge is the half + /// circle through the bottom corners about the bottom's middle, and the top edge the one 100 + /// further out. One cubic for a half circle strays up to 1.84 % of the radius from the circle. + #[test] + fn warp_net_arc_edges_are_concentric_circles() { + let net = WarpNet::new(WarpStyle::Arc, 1.0, 0.0, 0.0, 200.0, 100.0, false); + let center = Point::new(100.0, 100.0); + for i in 0..=20 { + let u = f64::from(i) / 20.0; + for (v, r) in [(0.0, 200.0), (1.0, 100.0)] { + let d = net.at(u, v).distance(center); + assert!((d - r).abs() < 0.0184 * r, "u {u}, v {v}: {d} from the center, not {r}"); + // Its ends and middle lie on the circle. + if i % 10 == 0 { + assert!((d - r).abs() < 1e-9, "u {u}, v {v}: {d} from the center, not {r}"); + } + } + } + // Bend 0 leaves the box as it is. + for st in [WarpStyle::Arc, WarpStyle::ShellLower, WarpStyle::Bulge, WarpStyle::Twist] { + let flat = WarpNet::new(st, 0.0, 0.0, 0.0, 200.0, 100.0, false); + assert!(flat.at(0.3, 0.7).distance(Point::new(60.0, 70.0)) < 1e-9, "{st:?}"); + } + } + + /// The horizontal distortion scales each column of the net about its middle (narrowing the left + /// side for a positive value), then the vertical one each row (narrowing the top). + #[test] + fn warp_net_distortion_scales_the_columns_then_the_rows() { + let corners = |dh: f64, dv: f64| { + let net = WarpNet::new(WarpStyle::Arc, 0.0, dh, dv, 200.0, 100.0, false); + [net.at(0.0, 0.0), net.at(1.0, 0.0), net.at(0.0, 1.0), net.at(1.0, 1.0)] + }; + let near = |got: [Point; 4], want: [(f64, f64); 4]| got.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-9); + assert!(near(corners(0.5, 0.0), [(0.0, 25.0), (200.0, -25.0), (0.0, 75.0), (200.0, 125.0)]), "{:?}", corners(0.5, 0.0)); + assert!(near(corners(0.0, 0.5), [(50.0, 0.0), (150.0, 0.0), (-50.0, 100.0), (250.0, 100.0)]), "{:?}", corners(0.0, 0.5)); + // Both coordinates scale: after the columns the top row runs from (0, 15) to (200, -15), and + // it then scales by 1.4 about its middle, (100, 0). + assert!(near(corners(0.3, -0.4), [(-40.0, 21.0), (240.0, -21.0), (40.0, 91.0), (160.0, 109.0)]), "{:?}", corners(0.3, -0.4)); + } + + /// Numbers no warp can take still give a finite net: a bend or distortion that isn't a number + /// counts as 0, and out of range as its limit; a size that isn't a number as 0. + #[test] + fn warp_net_takes_any_numbers() { + for st in [WarpStyle::Arc, WarpStyle::ShellUpper, WarpStyle::Wave, WarpStyle::Inflate, WarpStyle::Twist] { + for (b, dh, w, h) in + [(f64::NAN, 0.2, 10.0, 10.0), (5.0, f64::INFINITY, 10.0, 0.0), (-1e300, -3.0, f64::NAN, 1e-300), (1e-300, 0.0, 0.0, 0.0)] + { + for vertical in [false, true] { + let p = WarpNet::new(st, b, dh, dh, w, h, vertical).at(0.3, 0.6); + assert!(p.x.is_finite() && p.y.is_finite(), "{st:?} {b} {dh} {w} {h}: {p:?}"); + } + } + } + let clamped = WarpNet::new(WarpStyle::Flag, 7.0, 0.0, 0.0, 200.0, 100.0, false); + assert_eq!(clamped, WarpNet::new(WarpStyle::Flag, 1.0, 0.0, 0.0, 200.0, 100.0, false)); + } + + /// A box near the largest finite size still warps: Flag on a 1e308 × 100 box moves points only + /// up and down, as on a 1 × 1e-306 one scaled up, and on a 1e308 × 1e-300 box keeps the box's + /// height. Fisheye at 100 % on a 1.7e308 square, whose net goes past the largest finite number, + /// gives finite points inside the box and past it, and the unit square's points scaled up where + /// those are finite. Fisheye moves y by the height alone, so on boxes of the largest finite + /// width and a height of 1e-300 or 100 every y is the unit square's times the height, also + /// where x goes past the largest finite number. + #[test] + fn warp_net_bends_a_huge_box_without_overflowing() { + let w = 1e308; + let flag = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, w, 100.0, false); + let small = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, 1.0, 100.0 / w, false); + for (u, v) in [(0.0, 0.0), (0.3, 0.6), (0.9, 1.0), (1.0, 0.5)] { + let (p, q) = (flag.at(u, v), small.at(u, v)); + assert!(p.is_finite(), "({u}, {v}): {p:?}"); + assert!((p.x - u * w).abs() <= 1e-12 * w, "({u}, {v}): {p:?}"); + assert!((p.y - q.y * w).abs() <= 1e-9 * p.y.abs().max(1.0), "({u}, {v}): {p:?} against {q:?}"); + } + let thin = WarpNet::new(WarpStyle::Flag, 0.5, 0.0, 0.0, w, 1e-300, false); + assert_eq!(thin.at(0.0, 1.0), Point::new(0.0, 1e-300)); + let fisheye = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, 1.7e308, 1.7e308, false); + for (u, v) in [(0.1, 0.1), (0.8, 0.3), (1.5, 0.5), (3.0, 3.0)] { + let p = fisheye.at(u, v); + assert!(p.is_finite(), "({u}, {v}): {p:?}"); + } + let unit = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, 1.0, 1.0, false); + let near = |a: f64, b: f64| (a - b).abs() <= 1e-12 * b.abs().max(f64::MIN_POSITIVE); + let (p, q) = (fisheye.at(0.1, 0.1), unit.at(0.1, 0.1)); + assert!(near(p.x, q.x * 1.7e308) && near(p.y, q.y * 1.7e308), "{p:?} against {q:?}"); + // The bottom of a box with a subnormal height stays exactly at that height: the net is + // built on the box halved, and the height's lowest bit but one is set. + let low = f64::MIN_POSITIVE / 4.0 + f64::from_bits(2); + let sub = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, f64::MAX, low, false).at(0.0, 1.0); + assert_eq!(sub.y, low, "{sub:?}"); + for h in [1e-300, 100.0] { + let tall = WarpNet::new(WarpStyle::Fisheye, 1.0, 0.0, 0.0, f64::MAX, h, false); + for (u, v) in [(0.1, 0.1), (0.9, 0.4), (0.5, 0.8)] { + let (p, q) = (tall.at(u, v), unit.at(u, v)); + assert!(p.is_finite() && near(p.y, q.y * h), "h {h}, ({u}, {v}): {p:?} against {q:?}"); + } + } + } + + /// Content with no width or no height takes the middle of a warp envelope's patch along that + /// side: under Arc a vertical line stays vertical, under Bulge a horizontal line stays straight. + #[test] + fn warp_envelopes_bend_flat_content_as_the_middle_of_the_patch() { + let warp = |style: &str| EnvelopeKind::Warp { style: style.into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; + let arc = warp("arc"); + let map = envelope_mapper(&arc, Rect::new(100.0, 0.0, 100.0, 100.0)); + for y in [0.0, 30.0, 100.0] { + let p = map(Point::new(100.0, y)); + assert!((p.x - 100.0).abs() <= 1e-9, "{y}: {p:?}"); + } + let bulge = warp("bulge"); + let map = envelope_mapper(&bulge, Rect::new(0.0, 50.0, 200.0, 50.0)); + for x in [0.0, 70.0, 200.0] { + let p = map(Point::new(x, 50.0)); + assert!((p.y - 50.0).abs() <= 1e-9, "{x}: {p:?}"); + } + } + + /// A warp envelope's map version: none in a file reads as 0 (the earlier map), 0 is written + /// as none, so files keep their bytes, and the nets' version is written. + #[test] + fn warp_envelopes_write_their_map_version_only_when_it_has_one() { + let old: EnvelopeKind = serde_json::from_str(r#"{"type":"warp","style":"arc","bend":20}"#).unwrap(); + assert!(matches!(old, EnvelopeKind::Warp { version: 0, .. }), "{old:?}"); + assert!(!serde_json::to_string(&old).unwrap().contains("version")); + let new = EnvelopeKind::Warp { style: "arc".into(), bend: 20.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; + let text = serde_json::to_string(&new).unwrap(); + assert!(text.contains(r#""version":1"#), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), new); + } use vectorcraft_geom::shapes; fn rect_node(x: f64, y: f64, w: f64, h: f64, c: Color) -> Arc { @@ -537,7 +731,7 @@ mod tests { #[test] fn an_envelope_maps_from_its_box_with_its_margins() { let rect = Node::path(NodeId(2), vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)), crate::Appearance::default_art()); - let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let content = [Arc::new(rect)]; let src = |content: &[Arc], frame: Affine, options: EnvelopeOptions| EnvelopeMap::new(content, &kind, frame, options).unwrap().src(); // Top, bottom, left and right. diff --git a/crates/doc/src/live/blend_spec.rs b/crates/doc/src/live/blend_spec.rs index 75df5eee1f..56405e0d18 100644 --- a/crates/doc/src/live/blend_spec.rs +++ b/crates/doc/src/live/blend_spec.rs @@ -107,6 +107,11 @@ pub struct BlendSpec { /// on anchor points); `None`: chosen so closed shapes don't twist. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub starts: Vec>, + /// The blend was made without a spine (Create Spine › Never): it has no spine to show, edit, + /// reverse or release, and no easing. Its steps still sit on the straight lines between the + /// key centers. Replace Spine gives it one. + #[serde(default, rename = "noSpine", skip_serializing_if = "is_false", deserialize_with = "lenient_bool")] + pub no_spine: bool, } impl BlendSpec { @@ -116,6 +121,41 @@ impl BlendSpec { } } +/// The Blend panel's Create Spine setting: whether a new blend gets a spine. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BlendSpineMode { + /// The usual rule: every new blend gets a spine, the straight lines between its key centers. + #[default] + Auto, + /// Every new blend gets a spine, whatever its key objects are. + Always, + /// New blends get no spine. + Never, +} + +impl BlendSpineMode { + /// Every mode, in the order the Blend panel lists them. + pub const ALL: [Self; 3] = [Self::Auto, Self::Always, Self::Never]; + + pub fn id(self) -> &'static str { + match self { + Self::Auto => "auto", + Self::Always => "always", + Self::Never => "never", + } + } + + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|m| m.id() == id) + } + + /// Whether a new blend made with this mode gets a spine. + pub fn creates_spine(self) -> bool { + self != Self::Never + } +} + /// Blend Options set with no blend selected: what new blends start with. #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct BlendDefaults { @@ -123,6 +163,29 @@ pub struct BlendDefaults { pub spacing: BlendSpacing, #[serde(default)] pub orientation: BlendOrientation, + /// Create Spine (`object.blend.createSpine`). + #[serde(default, rename = "createSpine", skip_serializing_if = "is_auto", deserialize_with = "spine_mode")] + pub create_spine: BlendSpineMode, +} + +fn is_false(v: &bool) -> bool { + !*v +} + +fn is_auto(v: &BlendSpineMode) -> bool { + *v == BlendSpineMode::Auto +} + +/// Reading a native file never fails over a `noSpine` that is not a boolean: the blend keeps its +/// spine. +fn lenient_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::Value::deserialize(d)?.as_bool().unwrap_or(false)) +} + +/// Reading the preferences never fails over an unknown Create Spine value: it becomes Auto. +fn spine_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(v.as_str().and_then(BlendSpineMode::from_id).unwrap_or_default()) } /// Reading a native file never fails over one bad blend number: out-of-range values clamp, diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 8f9b197048..f197837020 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -3,6 +3,10 @@ use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, surface_of}; use super::{Affine, Arc, Color, Deserialize, Node, NodeId, NodeKind, PathData, Point, Rect, Serialize, Vec2, yes}; use vectorcraft_geom::Homography; +fn is_zero(n: &u32) -> bool { + *n == 0 +} + /// How an envelope distorts its content. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -19,6 +23,10 @@ pub enum EnvelopeKind { v: f64, #[serde(default = "yes")] horizontal: bool, + /// The map the warp draws with: [`WARP_NET`](super::WARP_NET) for its style's Bézier net, + /// 0 (as in files from before the version existed) for [`warp_point`](super::warp_point). + #[serde(default, skip_serializing_if = "is_zero")] + version: u32, }, /// A `(rows+1)×(cols+1)` grid of points (row-major) the content's bounding box maps onto. Mesh { @@ -78,7 +86,9 @@ pub struct EnvelopeOptions { /// Rasters: Preserve Shape Using. pub preserve_shape: PreserveShape, /// Distort Appearance: strokes and live effects are applied before the distortion, so they - /// bend with the art (off: they apply to the distorted paths). + /// bend with the art (off: they apply to the distorted paths). Type's strokes are the exception: + /// they paint along its distorted glyph outlines at their own weight either way, as `.ai` files + /// draw them (#6644). pub distort_appearance: bool, /// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art. pub distort_linear_gradients: bool, @@ -638,6 +648,7 @@ pub(super) fn expand_envelope( hooks, options, depth: 0, + type_outlines: false, }; content.iter().map(|c| map_node(c, &w)).collect() } diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index 66d20f27b6..7c80866ee7 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -21,6 +21,11 @@ pub struct Hooks<'a> { /// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None` /// when it has none to bake). pub appearance: Outliner<'a>, + /// Distort Appearance for the pieces of type's glyph outlines: their geometry effects baked + /// as [`Hooks::appearance`] bakes them, their strokes left as strokes, which then paint along + /// the bent outlines at their own weight (#6644). `None` when a piece has nothing to bake, and + /// without this hook nothing in type's outlines is baked. + pub type_appearance: Outliner<'a>, /// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]). pub pattern: Option>, /// The document whose symbols' art counts toward the instance budget of a Repeat of their @@ -61,6 +66,12 @@ pub(super) struct Warper<'a> { pub(super) options: EnvelopeOptions, /// How many hooks the art being mapped came through. pub(super) depth: u32, + /// Are groups marked as type's glyph outlines ([`crate::NodeExtras::type_outlines`]) in the art + /// being mapped type that live evaluation outlined: the type of the envelope's contents, or of + /// a live object in them, such as an envelope inside the envelope? Their strokes then paint + /// along the bent outlines at their own weight (#6644). Groups so marked in the contents as + /// they are, art an earlier Expand made of type, are plain art. + pub(super) type_outlines: bool, } impl Warper<'_> { @@ -117,6 +128,13 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node { *live = None; } NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + // Type's glyph outlines: with Distort Appearance too, their strokes paint along the + // bent outlines at their own weight, as `.ai` files draw them (#6644). Their pieces are + // baked by `type_appearance`, which keeps strokes as strokes; their geometry effects, + // gradients and pattern fills follow the options as a path's do. The group's opacity + // mask, mapped above, bends as other art does. + let typed = Warper { hooks: Hooks { appearance: w.hooks.type_appearance, ..w.hooks }, ..*w }; + let w = if w.type_outlines && n.extras().type_outlines { &typed } else { w }; for c in children.iter_mut() { *c = Arc::new(map_node(c, w)); } @@ -124,14 +142,17 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node { NodeKind::Mesh(m) => m.map(w.f), NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { if let Some(d) = &deeper { - return map_node(&expanded_group_hooks(n, w.hooks), d); + // The type's outlines in its art are type (an envelope inside the envelope, #6644). + return map_node(&expanded_group_hooks(n, w.hooks), &Warper { type_outlines: true, ..*d }); } } NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => { if let Some(d) = &deeper && let Some(o) = w.hooks.outline.and_then(|h| h(n)) { - return map_node(&carry_look(n, o), d); + // Type's outlines are type (#6644, the group arm above). + let d = Warper { type_outlines: d.type_outlines || matches!(n.kind, NodeKind::Text(_)), ..*d }; + return map_node(&carry_look(n, o), &d); } } NodeKind::Image(im) => { @@ -140,6 +161,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node { } // Its art is plain, so it warps at this depth. NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w), + // A ruler guide has no shape to warp. + NodeKind::RulerGuide { .. } => {} } out } @@ -155,29 +178,46 @@ fn affine_between(s: [Point; 3], d: [Point; 3]) -> Option { a.is_finite().then_some(a) } -/// Image `n` (`im`) pushed through the warp as a raster mesh warp: its frame cut into -/// `w.cells`² cells of two triangles, each a clip group showing the image under the affine map -/// that takes the triangle where the warp takes its corners (with Preserve Shape Using -/// Transparency, the image masked by the triangle; with Anti-Alias off, drawn without smoothing). -/// Each piece reaches a little past its edges (at most half a point) so neighbours overlap and no -/// seams show. +/// Image `n` (`im`) pushed through the envelope's warp as a raster mesh warp ([`mesh_warp_image`] +/// with `w.cells` cells, Preserve Shape Using Transparency and Anti-Alias as the envelope's +/// options say). fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { let k = w.cells.max(1); - // Two triangles a cell, three objects each; an image an inner envelope already cut into - // pieces is cut again here, so the pieces count against [`MAX_GENERATED`]. Past it, the image - // is left out. - if !Generating::charge(k.saturating_mul(k).saturating_mul(6)) { + // An image an inner envelope already cut into pieces is cut again here, so the pieces count + // against [`MAX_GENERATED`]. Past it, the image is left out. + if !Generating::charge(mesh_warp_cost(k)) { let mut g = n.clone(); g.kind = NodeKind::Group { children: vec![], clip: false }; return g; } + mesh_warp_image(n, im, w.f, k, !w.options.anti_alias, w.options.preserve_shape == PreserveShape::Transparency) +} + +/// How many objects [`mesh_warp_image`] makes of one image with `cells` rows and columns: two +/// triangles a cell, three objects each. +pub fn mesh_warp_cost(cells: usize) -> usize { + let k = cells.max(1); + k.saturating_mul(k).saturating_mul(6) +} + +/// Image `n` (`im`) pushed through point map `f` as a raster mesh warp: its frame cut into +/// `cells`² cells of two triangles, each a clip group showing the image under the affine map +/// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the +/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past +/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the +/// color `n` colorizes a grayscale image with. The result is a group with `n`'s id, name, +/// transparency, opacity mask and appearance. +pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node { + let k = cells.max(1); + // A grayscale image's fill color colorizes each piece; the group of pieces takes none. + let colorize = n.extras().colorize.clone(); let (pw, ph) = (im.width as f64, im.height as f64); let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64); let mut pieces = Vec::with_capacity(2 * k * k); for j in 0..k { for i in 0..k { let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]; - let d = s.map(|p| (w.f)(im.xf * p)); + let d = s.map(|p| f(im.xf * p)); for t in [[0, 1, 2], [0, 2, 3]] { let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v])); let Some(xf) = affine_between(st, dt) else { continue }; @@ -193,8 +233,9 @@ fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { .collect(); let shape = PathData::single(SubPath::polyline(&tri, true)); let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); - image.extras_mut().pixelated = !w.options.anti_alias; - if w.options.preserve_shape == PreserveShape::Transparency { + image.extras_mut().pixelated = pixelated; + image.extras_mut().colorize = colorize.clone(); + if masked { // Preserve Shape Using Transparency: the triangle is the piece's alpha (a // white opacity mask) instead of its clipping path. let white = Node::path(n.id, shape, Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0)); @@ -211,6 +252,9 @@ fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { } let mut g = n.clone(); g.kind = NodeKind::Group { children: pieces, clip: false }; + if let Some(e) = g.extras_if_any() { + e.colorize = None; + } g } @@ -437,8 +481,11 @@ pub fn subtree_has_live(n: &Node) -> bool { any } -/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the -/// outsets in the art of the symbols its instances show count too +/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the +/// reach of symbol art), type's character strokes included as type's own visual bounds measure them +/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight +/// around the bent glyphs, past its grid where the glyphs reach its edge (#6644). With +/// `symbols`, the outsets in the art of the symbols its instances show count too /// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made /// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad /// does. @@ -447,6 +494,9 @@ pub(crate) fn max_outset(nodes: &[Arc], symbols: Option<&crate::SymbolBoxe for n in nodes { n.walk(&mut |c| { o = o.max(c.appearance.outset()); + if let NodeKind::Text(t) = &c.kind { + o = o.max(t.char_stroke_outset()); + } if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind) && let Some(art) = s.art(symbol) { diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index c59374dee9..be865e2769 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -1,5 +1,5 @@ use super::envelope::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, envelope_grid, mesh_at}; -use super::warp::{WarpStyle, flatten_subpath, resample, warp_point}; +use super::warp::{WarpNet, WarpStyle, flatten_subpath, resample, uses_net, warp_point}; use super::{ Affine, Anchor, Arc, Color, CubicBez, Deserialize, Node, ParamCurve, PathData, Point, Rect, Serialize, Shape, SubPath, Vec2, fifty, lerp_color, one, @@ -1731,10 +1731,19 @@ pub(super) fn grid_eval(rows: usize, cols: usize, pts: &[Point], u: f64, v: f64) pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -> Box Point + 'a> { let flat = move |u: f64, v: f64| frame * Point::new(src.x0 + u * src.width(), src.y0 + v * src.height()); match kind { - EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal } => { + EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal, version } => { let st = WarpStyle::from_id(style).unwrap_or(WarpStyle::Arc); let b = bend.clamp(-100.0, 100.0) / 100.0; let (dh, dv) = (dh.clamp(-100.0, 100.0) / 100.0, dv.clamp(-100.0, 100.0) / 100.0); + if uses_net(*version) { + let net = WarpNet::new(st, b, dh, dv, src.width(), src.height(), !*horizontal); + // Content with no width or no height takes the middle of the patch along that side. + let (flat_u, flat_v) = (src.width() <= 0.0, src.height() <= 0.0); + return Box::new(move |u: f64, v: f64| { + let (u, v) = (if flat_u { 0.5 } else { u }, if flat_v { 0.5 } else { v }); + frame * (src.origin() + net.at(u, v).to_vec2()) + }); + } let c = src.center(); let (hw, hh) = (src.width() / 2.0, src.height() / 2.0); let horizontal = *horizontal; diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index 6d7392ac5f..08bef91140 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -109,6 +109,337 @@ pub fn warp_point(style: WarpStyle, b: f64, dh: f64, dv: f64, aspect: f64, x: f6 (x2, y2) } +// ===================================================================================== +// Warp nets: each style as one Bézier patch over its box +// ===================================================================================== + +/// The `version` a Warp effect's params or a warp envelope carries for the [`WarpNet`] map. With +/// none (or 0) a warp draws with [`warp_point`], as every warp did before, so saved documents keep +/// their look; new and imported warps are given this one. +pub const WARP_NET: u32 = 1; + +/// Does a warp of map `version` draw with [`WarpNet`]? A version newer than this build knows draws +/// with the newest map it has. +pub fn uses_net(version: u32) -> bool { + version >= WARP_NET +} + +/// The map version `v` names when it is one this build draws: a whole number from 0 to +/// [`WARP_NET`], written as an integer or as a float (`1` or `1.0`). +pub fn warp_version(v: &serde_json::Value) -> Option { + let n = v.as_f64()?; + (n.fract() == 0.0 && (0.0..=f64::from(WARP_NET)).contains(&n)).then_some(n as u32) +} + +/// A style's own control net: `rows` × `cols` points (2 to 4 each) of a Bézier patch, row by row +/// from the top, in the box's coordinates (origin at its top left, y down). +#[derive(Clone, Copy, Debug)] +struct Net { + rows: usize, + cols: usize, + p: [[Point; 4]; 4], +} + +impl Net { + /// The undistorted box `w` × `h` as a `rows` × `cols` net. + fn flat(w: f64, h: f64, rows: usize, cols: usize) -> Self { + let mut p = [[Point::ZERO; 4]; 4]; + for (r, row) in p.iter_mut().enumerate().take(rows) { + for (c, q) in row.iter_mut().enumerate().take(cols) { + *q = Point::new(w * (c as f64 / (cols - 1) as f64), h * (r as f64 / (rows - 1) as f64)); + } + } + Self { rows, cols, p } + } + + /// Upside down within a box `h` high: the rows in reverse order, each point mirrored. + fn mirrored(self, h: f64) -> Self { + let mut out = self; + for (to, from) in out.p[..self.rows].iter_mut().zip(self.p[..self.rows].iter().rev()) { + for (q, f) in to.iter_mut().zip(from).take(self.cols) { + *q = Point::new(f.x, h - f.y); + } + } + out + } + + /// Rows and columns exchanged, and x with y: a net made on the box turned on its side. + fn transposed(self) -> Self { + let mut out = Self { rows: self.cols, cols: self.rows, p: [[Point::ZERO; 4]; 4] }; + for (r, row) in self.p[..self.rows].iter().enumerate() { + for (c, q) in row[..self.cols].iter().enumerate() { + out.p[c][r] = Point::new(q.y, q.x); + } + } + out + } + + /// Each column scaled about the midpoint of its end points by `1 + a (2t - 1)`, `t` running from + /// 0 at the left column to 1 at the right: a horizontal distortion `a` (-1..1). + fn distort_columns(&mut self, a: f64) { + let (rows, cols) = (self.rows, self.cols); + for c in 0..cols { + let s = 1.0 + a * (2.0 * c as f64 / (cols - 1) as f64 - 1.0); + let mid = half_way(self.p[0][c], self.p[rows - 1][c]); + for row in &mut self.p[..rows] { + row[c] = mid + (row[c] - mid) * s; + } + } + } + + /// Each row scaled about the midpoint of its end points by `1 + a (2t - 1)`, `t` running from 0 + /// at the top row to 1 at the bottom: a vertical distortion `a` (-1..1). + fn distort_rows(&mut self, a: f64) { + let (rows, cols) = (self.rows, self.cols); + for (r, row) in self.p[..rows].iter_mut().enumerate() { + let s = 1.0 + a * (2.0 * r as f64 / (rows - 1) as f64 - 1.0); + let mid = half_way(row[0], row[cols - 1]); + for q in &mut row[..cols] { + *q = mid + (*q - mid) * s; + } + } + } + + /// The same patch as a bicubic net (degree elevation, which leaves the surface as it is). + fn bicubic(self) -> [[Point; 4]; 4] { + let rows: Vec<[Point; 4]> = self.p[..self.rows].iter().map(|row| cubic_line(&row[..self.cols])).collect(); + let mut out = [[Point::ZERO; 4]; 4]; + for c in 0..4 { + let col: Vec = rows.iter().map(|row| row[c]).collect(); + for (to, q) in out.iter_mut().zip(cubic_line(&col)) { + to[c] = q; + } + } + out + } +} + +/// The point half way from `a` to `b`, as halves added: two finite points always give a finite one. +fn half_way(a: Point, b: Point) -> Point { + Point::new(0.5 * a.x + 0.5 * b.x, 0.5 * a.y + 0.5 * b.y) +} + +/// A Bézier curve of 2 to 4 control points as the 4 of the same curve's cubic form. +fn cubic_line(p: &[Point]) -> [Point; 4] { + match *p { + [a, b] => [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b], + [a, b, c] => [a, a.lerp(b, 2.0 / 3.0), c.lerp(b, 2.0 / 3.0), c], + [a, b, c, d] => [a, b, c, d], + _ => [Point::ZERO; 4], + } +} + +/// The handle offsets (along the chord, across it) of a cubic circular arc over a chord `chord` +/// long that turns through θ = |`b`| × 180°: each handle is 4/3 tan(θ/4) of the radius long, along +/// the arc's end tangent. With the radius `chord / (2 sin(θ/2))` that length is +/// `chord / (3 cos²(θ/4))`, which a bend near 0 leaves at a third of the chord. +fn arc_handles(chord: f64, b: f64) -> (f64, f64) { + let th = b.abs().min(1.0) * PI; + let len = chord / (3.0 * (th / 4.0).cos().powi(2)); + (len * (th / 2.0).cos(), len * (th / 2.0).sin()) +} + +/// A row from (0, `y`) to (`w`, `y`) bent into a circular arc of |`b`| × 180°: up for a positive +/// `b` when `up`, down when not, the other way for a negative one. +fn arc_row(w: f64, y: f64, b: f64, up: bool) -> [Point; 4] { + let (ax, ay) = arc_handles(w, b); + let dy = if (b > 0.0) == up { -ay } else { ay }; + [Point::new(0.0, y), Point::new(ax, y + dy), Point::new(w - ax, y + dy), Point::new(w, y)] +} + +/// Arc at bend |`b`| as four rows: the bottom edge bends up through the bottom corners, the top +/// edge is the arc around the same center `h` further out, and the rows between are spaced evenly +/// along the radii. The top corners lie `h` out from the bottom ones along the radii, which lean +/// out by θ/2. +fn arc_rows(w: f64, h: f64, b: f64) -> [[Point; 4]; 4] { + let th = b.abs().min(1.0) * PI; + let (s, c) = (th / 2.0).sin_cos(); + let (tl, tr) = (Point::new(-h * s, h * (1.0 - c)), Point::new(w + h * s, h * (1.0 - c))); + let (ax, ay) = arc_handles(tr.x - tl.x, b); + let top = [tl, Point::new(tl.x + ax, tl.y - ay), Point::new(tr.x - ax, tr.y - ay), tr]; + let bottom = arc_row(w, h, b.abs(), true); + let mut out = [[Point::ZERO; 4]; 4]; + for (r, row) in out.iter_mut().enumerate() { + for (q, (t, u)) in row.iter_mut().zip(top.iter().zip(bottom)) { + *q = t.lerp(u, r as f64 / 3.0); + } + } + out +} + +/// Warp style `style`'s own net at bend `b` (-1..1) over the box `w` × `h`, before distortion. +/// `vertical`: the net of the box turned on its side, where Rise moves the other half. +fn style_net(style: WarpStyle, b: f64, w: f64, h: f64, vertical: bool) -> Net { + use WarpStyle::*; + let two = |top: [Point; 4], bottom: [Point; 4]| { + let mut p = [[Point::ZERO; 4]; 4]; + (p[0], p[1]) = (top, bottom); + Net { rows: 2, cols: 4, p } + }; + let flat_row = |y: f64| [0.0, 1.0, 2.0, 3.0].map(|c| Point::new(w * c / 3.0, y)); + match style { + Arc => { + let rows = arc_rows(w, h, b); + let net = two(rows[0], rows[3]); + if b < 0.0 { net.mirrored(h) } else { net } + } + ArcUpper => two(arc_row(w, 0.0, b, true), flat_row(h)), + ArcLower => two(flat_row(0.0), arc_row(w, h, b, false)), + Arch => { + let top = arc_row(w, 0.0, b, true); + two(top, top.map(|q| Point::new(q.x, q.y + h))) + } + Bulge => two(arc_row(w, 0.0, b, true), arc_row(w, h, b, false)), + ShellLower | ShellUpper => { + let a = arc_rows(w, h, b); + let mut net = Net::flat(w, h, 4, 4); + if b >= 0.0 { + // The outer arc and the ends of the row inside it, upside down for Shell Lower. + net.p[0] = a[0]; + (net.p[1][0], net.p[1][3]) = (a[1][0], a[1][3]); + if style == ShellLower { net.mirrored(h) } else { net } + } else { + // The inner arc and the ends of the row outside it, upside down for Shell Upper. + net.p[3] = a[3]; + (net.p[2][0], net.p[2][3]) = (a[2][0], a[2][3]); + if style == ShellUpper { net.mirrored(h) } else { net } + } + } + Flag | Fish | Rise => { + let mut net = Net::flat(w, h, 2, 4); + let d = 2.0 * b * h; + match style { + Flag => { + for row in &mut net.p[..2] { + (row[1].y, row[2].y) = (row[1].y + d, row[2].y - d); + } + } + Fish => { + (net.p[0][1].y, net.p[0][2].y) = (net.p[0][1].y - d, net.p[0][2].y + d); + (net.p[1][1].y, net.p[1][2].y) = (net.p[1][1].y + d, net.p[1][2].y - d); + } + _ => { + for row in &mut net.p[..2] { + if vertical { + (row[2].y, row[3].y) = (row[2].y - d, row[3].y - d); + } else { + (row[0].y, row[1].y) = (row[0].y + d, row[1].y + d); + } + } + } + } + net + } + Wave => { + let mut net = Net::flat(w, h, 3, 4); + let d = 2.0 * b * h; + (net.p[1][1].y, net.p[1][2].y) = (net.p[1][1].y + d, net.p[1][2].y - d); + net + } + Fisheye => { + let mut net = Net::flat(w, h, 4, 4); + let c = Point::new(w / 2.0, h / 2.0); + for row in &mut net.p[1..3] { + for q in &mut row[1..3] { + *q = c + (*q - c) * (1.0 + 4.0 * b); + } + } + net + } + Inflate | Squeeze => { + let mut net = Net::flat(w, h, 3, 3); + let side = if style == Inflate { b * w / 2.0 } else { -b * w / 2.0 }; + net.p[0][1].y -= b * h / 2.0; + net.p[2][1].y += b * h / 2.0; + net.p[1][0].x -= side; + net.p[1][2].x += side; + net + } + Twist => { + // The four inner points move round: clockwise for a positive bend. + let mut net = Net::flat(w, h, 4, 4); + let (dx, dy) = (b.abs() * w, b.abs() * h); + if b >= 0.0 { + net.p[1][1].x += dx; + net.p[1][2].y += dy; + net.p[2][2].x -= dx; + net.p[2][1].y -= dy; + } else { + net.p[1][1].y += dy; + net.p[1][2].x -= dx; + net.p[2][2].y -= dy; + net.p[2][1].x += dx; + } + net + } + } +} + +/// A warp as one bicubic Bézier patch over its box: the style's own net at the bend, its columns +/// scaled by the horizontal distortion and then its rows by the vertical one. Points are in the +/// box's coordinates (origin at its top left, y down). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WarpNet { + /// The control points over the box divided by `scale`. + net: [[Point; 4]; 4], + /// 1, or a power of two when the net over the box itself does not fit in finite numbers. + scale: f64, + w: f64, + h: f64, +} + +impl WarpNet { + /// The net of `style` over a box `w` × `h` at bend `b` and distortions `dh` and `dv` (each + /// -1..1, clamped); `vertical` bends along the box's height. + pub fn new(style: WarpStyle, b: f64, dh: f64, dv: f64, w: f64, h: f64, vertical: bool) -> Self { + let unit = |x: f64| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 }; + let size = |x: f64| if x.is_finite() { x.max(0.0) } else { 0.0 }; + let (b, dh, dv, w, h) = (unit(b), unit(dh), unit(dv), size(w), size(h)); + let build = |w: f64, h: f64| { + let mut net = if vertical { style_net(style, b, h, w, true).transposed() } else { style_net(style, b, w, h, false) }; + net.distort_columns(dh); + net.distort_rows(dv); + net.bicubic() + }; + // A box near the largest finite size can overflow the net. The net is then built on the box + // divided by the smallest power of two that fits (2 to 4096), an exact division for every + // side above the subnormal range, and points are multiplied back as they are read. + let mut out = Self { net: build(w, h), scale: 1.0, w, h }; + while out.scale < 4096.0 && !out.net.iter().flatten().all(|q| q.is_finite()) { + let scale = out.scale * 2.0; + out = Self { net: build(w / scale, h / scale), scale, w, h }; + } + out + } + + /// The point at `(u, v)` of the box (0..1 across and down; outside, the patch goes on). A + /// coordinate the patch would send past the largest finite number is the box's own, held to + /// the finite range. + pub fn at(&self, u: f64, v: f64) -> Point { + let p = self.at_scaled(u, v); + let held = |x: f64| if x.is_nan() { 0.0 } else { x.clamp(-f64::MAX, f64::MAX) }; + let coord = |x: f64, flat: f64| if (x * self.scale).is_finite() { x * self.scale } else { held(flat) }; + Point::new(coord(p.x, u * self.w), coord(p.y, v * self.h)) + } + + /// [`Self::at`] divided by the net's scale. + fn at_scaled(&self, u: f64, v: f64) -> Point { + let bern = |t: f64| { + let s = 1.0 - t; + [s * s * s, 3.0 * t * s * s, 3.0 * t * t * s, t * t * t] + }; + let (bu, bv) = (bern(u), bern(v)); + let (mut x, mut y) = (0.0, 0.0); + for (row, wv) in self.net.iter().zip(bv) { + for (q, wu) in row.iter().zip(bu) { + x += wv * wu * q.x; + y += wv * wu * q.y; + } + } + Point::new(x, y) + } +} + /// Segment as a cubic; straight lines get handles at 1/3 and 2/3 so a non-linear map bends them. fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { let c = sp.segment(i); diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index e431fc9d15..12d233ba37 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -46,7 +46,7 @@ impl Document { return (0, 0); } let own = size_of::() + ALLOC + ARC; - let mut w = Walk { docs: [self, other], seen: [None, None], bytes: [own, own] }; + let mut w = Walk { docs: [self, other], seen: [None, None], bytes: [own, own], appearances: Default::default() }; w.list(&self.layers, &other.layers); for i in 0..self.symbols.len().max(other.symbols.len()) { match (self.symbols.get(i), other.symbols.get(i)) { @@ -88,7 +88,7 @@ impl Document { } let mut n = 0; n += vec_bytes(&self.artboards) + self.artboards.iter().map(|a| a.name.capacity()).sum::(); - n += vec_bytes(&self.guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets); + n += vec_bytes(&self.saved_guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets); n += vec_bytes(&self.text_threads) + self.text_threads.iter().map(vec_bytes).sum::(); n += self.images.iter().map(|(k, b)| 4 * size_of::() + k.capacity() + b.mime.capacity() + size_of_val(b)).sum::(); n += map_bytes(&self.export_settings) + map_bytes(&self.extra) + self.print_setup.as_ref().map_or(0, json_bytes); @@ -134,6 +134,9 @@ struct Walk<'a> { seen: [Option>; 2], /// For each side, what it keeps that the other doesn't. bytes: [usize; 2], + /// For each side, the appearances counted so far (by address): objects that share one (a + /// graphic style applied to them all) count it once. + appearances: [HashSet; 2], } impl Walk<'_> { @@ -174,8 +177,9 @@ impl Walk<'_> { self.alone(1, b); return; } - self.bytes[0] += node_bytes(a, Some(b)); - self.bytes[1] += node_bytes(b, Some(a)); + let [ca, cb] = &mut self.appearances; + self.bytes[0] += node_bytes(a, Some(b), ca); + self.bytes[1] += node_bytes(b, Some(a), cb); match (a.children(), b.children()) { (Some(x), Some(y)) => self.list(x, y), (x, y) => { @@ -198,8 +202,8 @@ impl Walk<'_> { if self.other_holds(side, n) { return; } - if let Some(b) = self.bytes.get_mut(side) { - *b += node_bytes(n, None); + if let (Some(b), Some(counted)) = (self.bytes.get_mut(side), self.appearances.get_mut(side)) { + *b += node_bytes(n, None, counted); } for c in n.children().into_iter().flatten() { self.alone(side, c); @@ -242,14 +246,15 @@ impl Walk<'_> { } /// One node's own heap: the node, and what it owns besides its children and mask art (counted -/// as nodes of their own). Its appearance counts unless `other`, its other version, shares it. -fn node_bytes(n: &Node, other: Option<&Node>) -> usize { +/// as nodes of their own). Its appearance counts unless `other`, its other version, shares it, or +/// another node of the same side shares it and was counted already (its address is in `counted`). +fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> usize { fn boxed(b: &Option>) -> usize { b.as_ref().map_or(0, |_| ALLOC + size_of::()) } let mut b = ALLOC + ARC + size_of::(); b += n.name.as_ref().map_or(0, String::capacity); - if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) { + if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) && counted.insert(&*n.appearance as *const Appearance as usize) { b += ALLOC + ARC + appearance_heap_bytes(&n.appearance); } if let Some(e) = n.extras_box() { @@ -447,6 +452,29 @@ mod tests { assert!(added > kept + 3 * 300, "{added} for three new rectangles"); } + /// Objects given one shared appearance (a graphic style applied to them all) count it once. + #[test] + fn a_shared_appearance_counts_once() { + let n = 100; + let before = doc_with_rects(n); + let ids: Vec<_> = before.layers[0].children().unwrap().iter().map(|c| c.id).collect(); + let ap = Appearance::basic(Paint::None, Paint::solid(vectorcraft_color::Color::BLACK), 2.0); + let restyled = |each: bool| { + let mut d = before.clone(); + let one = Shared::new(ap.clone()); + for id in &ids { + d.node_mut(*id).unwrap().appearance = if each { Shared::new(ap.clone()) } else { one.clone() }; + } + d + }; + let (shared, copies) = (restyled(false), restyled(true)); + let (kept, added) = before.retained_bytes_each(&shared); + assert_eq!(shared.retained_bytes_each(&before), (added, kept)); + let (kept_copies, added_copies) = before.retained_bytes_each(&copies); + assert_eq!(kept, kept_copies, "the old version keeps the same either way"); + assert_eq!(added_copies - added, (n - 1) * (ALLOC + ARC + appearance_heap_bytes(&ap))); + } + #[test] fn a_resource_counts_only_when_changed() { let before = doc_with_rects(1); diff --git a/crates/doc/src/metadata.rs b/crates/doc/src/metadata.rs index 151365c5d2..908b649e4d 100644 --- a/crates/doc/src/metadata.rs +++ b/crates/doc/src/metadata.rs @@ -1,11 +1,15 @@ //! File → File Info: the document's descriptive metadata (author, description, keywords, rating, //! copyright) and its created and modified dates, which the SVG, PDF and PNG writers carry. The -//! document title is [`crate::Document::title`]. Every field is defaulted, so documents saved -//! before File Info existed load unchanged. +//! document title is [`Document::title`], the name it shows in its tab and offers Save As when it +//! has no file; a title the file it was opened from gave itself is [`DocMetadata::title`], and +//! [`Document::info_title`] is the title File Info shows and exports write. Every field is +//! defaulted, so documents saved before File Info existed load unchanged. use chrono::{Datelike, Timelike}; use serde::{Deserialize, Serialize}; +use crate::Document; + /// File Info → Copyright Status. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -44,6 +48,13 @@ pub const MAX_RATING: u8 = 5; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct DocMetadata { + /// The title the file this document was opened from gives itself (an SVG's root ``, a + /// PDF's XMP `dc:title` or Info `Title`), which File Info shows and exports write in place of + /// [`Document::title`], the document's display name. `None`: the file gave none, so the + /// display name is the title. Left out of a saved document when unset, so other documents + /// save as they did. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option<String>, pub author: String, /// The author's position or job title. pub author_title: String, @@ -83,6 +94,16 @@ impl DocMetadata { } } +impl Document { + /// The title File Info shows and the files an export writes carry (PDF `Title` and XMP + /// `dc:title`, SVG `<title>`, PNG `Title`): the title the file this document was opened from + /// gave itself ([`DocMetadata::title`]), else [`Document::title`]. The display name (the tab, the + /// default file name) is always [`Document::title`]. + pub fn info_title(&self) -> &str { + self.metadata.title.as_deref().filter(|t| !t.trim().is_empty()).unwrap_or(&self.title) + } +} + /// The time exported files record: PDF `CreationDate` and `ModDate`, the PNG `Creation Time` /// entry, a zip entry's date, and a saved document's `created` and `modified`. It is the clock, /// unless `SOURCE_DATE_EPOCH` is set, which replaces it so that the same commands produce the same @@ -191,6 +212,24 @@ mod tests { assert!(DocMetadata::default().png_text("").is_empty()); } + #[test] + fn the_info_title_is_the_files_own_title_else_the_display_name() { + let mut d = Document::new(10.0, 10.0); + d.title = "box.svg".into(); + assert_eq!(d.info_title(), "box.svg"); + d.metadata.title = Some("Access paths".into()); + assert_eq!((d.title.as_str(), d.info_title()), ("box.svg", "Access paths")); + d.metadata.title = Some(" ".into()); + assert_eq!(d.info_title(), "box.svg"); + // Saved only when set: other documents' metadata is as before, and the field comes back. + d.metadata.title = None; + assert!(!serde_json::to_string(&d.metadata).unwrap().contains("title")); + d.metadata.title = Some("Access paths".into()); + let json = serde_json::to_string(&d.metadata).unwrap(); + assert_eq!(serde_json::from_str::<DocMetadata>(&json).unwrap().title.as_deref(), Some("Access paths")); + assert_eq!(serde_json::from_str::<DocMetadata>("{}").unwrap().title, None); + } + /// `SOURCE_DATE_EPOCH` replaces the clock in exported output only when it is a non-negative /// decimal integer; anything else leaves the clock to decide, so an export is never refused. #[test] diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 774e824390..eeec6ab162 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -33,6 +33,7 @@ pub use live_shape::{LiveShape, Scaling}; pub use opacity::{Knockout, OpacityMask, whiten}; pub use ops::{flattens, keeps_gradient_fit}; use wire::NodeWire; +pub(crate) use wire::counted_list; pub use wire::{MAX_READ_NODES, with_node_budget}; fn yes() -> bool { diff --git a/crates/doc/src/node/clip.rs b/crates/doc/src/node/clip.rs index 208bdda7ff..cb66ba1148 100644 --- a/crates/doc/src/node/clip.rs +++ b/crates/doc/src/node/clip.rs @@ -19,7 +19,7 @@ impl Node { fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) { match &self.kind { - NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {} + NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } | NodeKind::SymbolInstance { .. } => {} NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)), NodeKind::Compound { children, rule } => { let mut bp = BezPath::new(); diff --git a/crates/doc/src/node/kind.rs b/crates/doc/src/node/kind.rs index 22470cbf3e..7f9e21a0ff 100644 --- a/crates/doc/src/node/kind.rs +++ b/crates/doc/src/node/kind.rs @@ -122,6 +122,17 @@ pub enum NodeKind { Intertwine { children: Vec<Arc<Node>>, }, + /// A ruler guide: a straight line across the canvas, or across one artboard, that draws on + /// screen only. It is always a direct child of a layer or sublayer, above the layer's other + /// children, and has no bounds. + RulerGuide { + /// true: a vertical guide at x = `pos`; false: a horizontal one at y = `pos`. + vertical: bool, + pos: f64, + /// The [`crate::Artboard::id`] of the artboard it runs across; None: across the canvas. + #[serde(default, skip_serializing_if = "Option::is_none")] + artboard: Option<u32>, + }, } /// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every @@ -215,6 +226,12 @@ mod kind_de { Intertwine { children: Vec<Arc<Node>>, }, + RulerGuide { + vertical: bool, + pos: f64, + #[serde(default)] + artboard: Option<u32>, + }, } impl<'de> Deserialize<'de> for NodeKind { diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index eb7e0d39b9..415b2946e3 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -80,6 +80,16 @@ impl Node { matches!(self.kind, NodeKind::Layer { .. }) } + /// A ruler guide ([`NodeKind::RulerGuide`]). + pub fn is_ruler_guide(&self) -> bool { + matches!(self.kind, NodeKind::RulerGuide { .. }) + } + + /// A guide of either kind: a ruler guide, or a path made into a guide. + pub fn is_guide(&self) -> bool { + matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. }) + } + /// A template layer (Layer Options → Template). pub fn is_template(&self) -> bool { matches!(self.kind, NodeKind::Layer { template: true, .. }) @@ -91,7 +101,7 @@ impl Node { pub fn layer_art(&self, editable: bool) -> Vec<NodeId> { fn visit(n: &Node, editable: bool, out: &mut Vec<NodeId>) { for c in n.children().into_iter().flatten() { - if editable && (!c.visible || c.locked || c.is_template()) { + if c.is_ruler_guide() || (editable && (!c.visible || c.locked || c.is_template())) { continue; } if c.is_layer() { @@ -142,6 +152,7 @@ impl Node { NodeKind::Repeat(r) => r.kind.label(), NodeKind::PlacedDocument(_) => "Placed Document", NodeKind::Intertwine { .. } => "Intertwine", + NodeKind::RulerGuide { .. } => "Guide", } } @@ -310,6 +321,8 @@ impl Node { NodeKind::PlacedDocument(p) => Some(p.bounds()), // The members drawn over the others are drawn where they are. NodeKind::Intertwine { children } => union(children), + // A ruler guide runs across the canvas (or an artboard): it adds nothing to a box. + NodeKind::RulerGuide { .. } => None, } } @@ -522,6 +535,9 @@ impl Node { } NodeKind::Mesh(m) => m.transform(a), NodeKind::Repeat(r) => r.transform(a, *sc), + // A ruler guide stays where it is when the art around it (its layer) is transformed: + // the guide commands move it. + NodeKind::RulerGuide { .. } => {} } // The frames of the objects attached to a path move with them, and the distances along the // path follow the path as it is now (a live shape's path is regenerated). @@ -557,10 +573,10 @@ impl Node { } } - /// Count of nodes in this subtree. + /// Count of nodes in this subtree, ruler guides left out. pub fn count(&self) -> usize { let mut n = 0; - self.walk(&mut |_| n += 1); + self.walk(&mut |c| n += usize::from(!c.is_ruler_guide())); n } @@ -569,7 +585,7 @@ impl Node { pub fn count_with_masks(&self) -> usize { let mut n = 0; self.walk(&mut |c| { - n += 1; + n += usize::from(!c.is_ruler_guide()); if let Some(m) = &c.extras().mask { n += m.art.count_with_masks(); } @@ -688,7 +704,7 @@ impl Node { /// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves. pub fn knockout_elements(children: &[Arc<Node>]) -> Vec<&Arc<Node>> { fn push<'a>(children: &'a [Arc<Node>], out: &mut Vec<&'a Arc<Node>>) { - for c in children.iter().filter(|c| c.visible) { + for c in children.iter().filter(|c| c.visible && !c.is_ruler_guide()) { match c.children() { Some(ch) if c.passes_knockout_through() => push(ch, out), _ => out.push(c), @@ -701,8 +717,62 @@ impl Node { } /// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest. + /// A layer whose first child is a ruler guide holds no art, so a guide never clips it. pub fn clips(&self) -> bool { - matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }) + match &self.kind { + NodeKind::Group { clip, .. } => *clip, + NodeKind::Layer { clip, children, .. } => *clip && children.first().is_none_or(|c| !c.is_ruler_guide()), + _ => false, + } + } + + /// Where the ruler guides at the end of `children` (a layer's) begin: the index past the last + /// child that is not one. Art goes below this index and ruler guides at or above it. + pub fn guide_run_start(children: &[Arc<Node>]) -> usize { + children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1) + } + + /// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none. + pub fn strip_ruler_guides(&mut self) { + if !self.holds_ruler_guides() { + return; + } + if let Some(ch) = self.children_mut() { + ch.retain(|c| !c.is_ruler_guide()); + for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) { + Arc::make_mut(c).strip_ruler_guides(); + } + } + } + + /// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and + /// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied. + pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) { + if !self.holds_ruler_guides() { + return; + } + if let Some(ch) = self.children_mut() { + for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) { + let c = Arc::make_mut(c); + match &mut c.kind { + NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos), + _ => c.map_ruler_guide_positions(f), + } + } + } + } + + /// Whether this layer or one of its sublayers holds a ruler guide. + pub fn holds_ruler_guides(&self) -> bool { + self.is_layer() && self.children().is_some_and(|ch| ch.iter().any(|c| c.is_ruler_guide() || c.holds_ruler_guides())) + } + + /// The index that an insert into `children` at `index` uses for `node`: art stays below the + /// layer's ruler guides and a ruler guide goes among them. + pub fn insert_index(children: &[Arc<Node>], index: usize, node: &Node) -> usize { + let start = Self::guide_run_start(children); + let i = index.min(children.len()); + if node.is_ruler_guide() { i.max(start) } else { i.min(start) } } /// Make this group or layer clip its children by its first child, or stop it. diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index b54d3f4b84..2722e7bee0 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -145,9 +145,10 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> { } /// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol -/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed -/// file of repeated empty items stays small while they take memory once read. -fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> { +/// overrides, a document's saved ruler guides), each item counting against [`with_node_budget`] +/// as an object does: a compressed file of repeated empty items stays small while they take +/// memory once read. +pub(crate) fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> { struct Items<T>(std::marker::PhantomData<T>); impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> { type Value = Vec<T>; diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index 2a98df62ce..d1333bef0b 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -584,6 +584,8 @@ impl<'a> NestedCount<'a> { (NodeKind::Repeat(r), _) => r.in_all(self), (NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 }, (NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) }, + // A ruler guide draws nothing, so a repeat makes no copies of it. + (NodeKind::RulerGuide { .. }, _) => Cost::default(), (_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }), _ => Cost { instances: 0, copies: 1 }, }; diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index f6b9a4d013..8279507e01 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -80,10 +80,8 @@ fn head_ends(st: &StrokeLayer, bp: &BezPath) -> Vec<(Point, Vec2, bool)> { /// at `t`): the profile at that fraction of the subpath's length, or wider where an end of the /// segment is a corner. The stroke draws the sides there straight to the corner's join and inner /// meeting point, which can lie outside the exact width all along the segment. -fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, t: f64) -> (f64, f64) { +fn profile_at(profile: &WidthProfile, segs: &[PathSeg], lens: &[f64], total: f64, closed: bool, i: usize, t: f64) -> (f64, f64) { let n = segs.len(); - let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect(); - let total: f64 = lens.iter().sum::<f64>().max(1e-12); let before = lens[..i].iter().sum::<f64>(); let mut w = profile.at((before + segs[i].subsegment(0.0..t).arclen(ARCLEN_ACCURACY)) / total); let corner = |a: usize, b: usize| (closed || a < b) && kink(&segs[a], &segs[b]); @@ -306,7 +304,8 @@ impl StrokeLayer { /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and /// outside strokes of closed paths count on their own side only (and within `tol` of the - /// path); a width profile counts at its width where `p` is nearest. + /// path); a width profile counts at the width of every segment that can reach `p`, as the + /// wider side of a farther one can paint past the nearest. pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { let reach = self.reach() + tol; if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) { @@ -330,17 +329,27 @@ impl StrokeLayer { let segs = drawn(&els[r]); let (half, region) = self.body(closed); let full = half * self.profile_max() * dash_caps.unwrap_or(1.0); - // The nearest point on this subpath. - let near = segs.iter().enumerate().map(|(i, s)| (i, s.nearest(p, 1e-9))).min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq)); - if let Some((i, nr)) = near - && nr.distance_sq.sqrt() <= full + tol - { + // Every segment near enough to reach `p`: with a width profile the wider side of a + // farther segment can paint past the nearest one, so the nearest alone is not enough. + let near = segs.iter().enumerate().filter_map(|(i, s)| { + let nr = s.nearest(p, 1e-9); + (nr.distance_sq.sqrt() <= full + tol).then_some((i, nr)) + }); + // The lengths are only needed when a profiled candidate reaches `p`; compute them + // once for the whole subpath rather than once per candidate. + let mut lengths: Option<(Vec<f64>, f64)> = None; + for (i, nr) in near { let d = nr.distance_sq.sqrt(); let factor = if dash_caps.is_some() { full / half.max(1e-12) } else { self.profile.as_ref().map_or(1.0, |pr| { - let (l, rt) = profile_at(pr, &segs, closed, i, nr.t); + let (lens, total) = lengths.get_or_insert_with(|| { + let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect(); + let total = lens.iter().sum::<f64>().max(1e-12); + (lens, total) + }); + let (l, rt) = profile_at(pr, &segs, lens, *total, closed, i, nr.t); // Nearest to a segment's end, `p` is beside a join or past a cap, which // spans the widths of both sides. let at_end = nr.t <= 1e-9 || nr.t >= 1.0 - 1e-9; diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 643f81c365..c514aab996 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -39,16 +39,16 @@ pub struct Selection { /// clears them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub slices: Vec<NodeId>, - /// Ruler guides selected with a selection tool, as indexes into [`Document::guides`]. A new + /// Ruler guides selected with a selection tool, by node id ([`Document::ruler_guides`]). A new /// selection ([`Self::set`]) clears them; Shift-adding or -removing objects keeps them, so /// guides and objects can be selected together, in either order. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub guides: Vec<usize>, - /// A selected ruler guide that is the key object for Align instead of [`Self::key`] (an index - /// into [`Document::guides`], one of [`Self::guides`]): the objects line up on it. Never set - /// with `key`; [`Self::prune`] clears it when no object is selected to align to it. + pub guides: Vec<NodeId>, + /// A selected ruler guide that is the key object for Align instead of [`Self::key`] (one of + /// [`Self::guides`]): the objects line up on it. Never set with `key`; [`Self::prune`] clears + /// it when no object is selected to align to it. #[serde(default, skip_serializing_if = "Option::is_none")] - pub key_guide: Option<usize>, + pub key_guide: Option<NodeId>, /// The new art on a locked artboard that this selection keeps editable /// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and /// the engine then sets the document's from it. Editing state, never saved. @@ -139,10 +139,10 @@ impl Selection { } } } - /// Select ruler guides `indexes` (see [`Selection::guides`]) and nothing else. - pub fn set_guides(&mut self, indexes: impl IntoIterator<Item = usize>) { + /// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else. + pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) { self.clear(); - for i in indexes { + for i in ids { if !self.guides.contains(&i) { self.guides.push(i); } @@ -150,7 +150,7 @@ impl Selection { } /// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a /// Shift-click on a guide). - pub fn toggle_guide(&mut self, i: usize) { + pub fn toggle_guide(&mut self, i: NodeId) { self.symbol_part = None; if let Some(k) = self.guides.iter().position(|g| *g == i) { self.guides.remove(k); @@ -201,7 +201,9 @@ impl Selection { pub fn prune(&mut self, doc: &Document) { // Every id this looks up, found in one walk of the tree. let ids = self.objects.iter().chain(self.anchors.keys()).chain(self.segments.keys()).copied().chain(self.key).chain(self.target); - let found = doc.index_paths(ids); + let mut found = doc.index_paths(ids); + // A ruler guide is selected in `guides` only, never as an object, an anchor or the key. + found.retain(|_, p| !doc.node_at(p).is_some_and(|n| n.is_ruler_guide())); self.objects.retain(|id| found.contains_key(id)); self.anchors.retain(|id, _| found.contains_key(id)); self.segments.retain(|id, refs| { @@ -209,8 +211,12 @@ impl Selection { refs.retain(|&(si, seg)| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count())); !refs.is_empty() && self.objects.contains(id) && self.anchors.contains_key(id) }); - // Guides on a hidden or locked layer can't stay selected. - self.guides.retain(|i| doc.guides.get(*i).is_some_and(|g| doc.guide_editable(g))); + // Guides that are gone, or hidden or locked (themselves or by their layer), can't stay + // selected. + if !self.guides.is_empty() { + let editable = doc.editable(); + self.guides.retain(|id| doc.node(*id).is_some_and(|n| n.is_ruler_guide()) && editable(*id)); + } // The key object stays while another selected object lies outside it, or while ruler // guides are selected for it to line up (#2143). let keep = self.key.and_then(|k| found.get(&k)).and_then(|p| doc.node_at(p)).is_some_and(|n| { diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index 7882fef731..d0d81faee6 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -20,25 +20,30 @@ fn basic_ops() { fn guides_are_selected_on_their_own() { let mut s = Selection::default(); s.add(NodeId(1)); - s.set_guides([2, 0, 2]); - assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![2, 0])); + let (g0, g2) = (NodeId(10), NodeId(12)); + s.set_guides([g2, g0, g2]); + assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![g2, g0])); assert!(s.has_objects_or_guides() && s.is_empty()); // Shift-adding an object keeps them; a new selection doesn't. s.add(NodeId(1)); - assert_eq!(s.guides, vec![2, 0]); + assert_eq!(s.guides, vec![g2, g0]); s.set([NodeId(1)]); assert!(s.guides.is_empty()); // Toggled, a guide joins (or leaves) the selected objects. - s.toggle_guide(0); - assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![0])); - s.toggle_guide(0); + s.toggle_guide(g0); + assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![g0])); + s.toggle_guide(g0); assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![])); - // Pruning drops guides the document no longer has. + // Pruning drops guides the document no longer has, ids of other objects, and guides that are + // locked or hidden themselves. let mut d = Document::new(100.0, 100.0); - d.guides.push(crate::Guide::new(true, 10.0)); - s.set_guides([0, 1]); + let layer = d.layers[0].id; + let kept = d.add_ruler_guide(&crate::Guide::new(true, 10.0)); + let locked = d.add_ruler_guide(&crate::Guide { locked: true, ..crate::Guide::new(true, 20.0) }); + let hidden = d.add_ruler_guide(&crate::Guide { hidden: true, ..crate::Guide::new(true, 30.0) }); + s.set_guides([kept, NodeId(9999), layer, locked, hidden]); s.prune(&d); - assert_eq!(s.guides, vec![0]); + assert_eq!(s.guides, vec![kept]); } /// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers @@ -131,16 +136,26 @@ fn guides_show_and_lock_with_their_layer() { assert!(d.guide_shown(&crate::Guide::new(false, 5.0))); let gone = crate::Guide { layer: Some(NodeId(9999)), ..crate::Guide::new(true, 1.0) }; assert!(d.guide_shown(&gone) && d.guide_editable(&gone)); - d.guides.push(g); - assert_eq!(d.guides_on(layer).count(), 1); - // Guides on no layer, or a gone one, are adopted by the top visible, unlocked layer. + // As a node, a guide shows and locks with its layer and on its own. + let id = d.add_ruler_guide(&g); + let node = d.ruler_guide(id).unwrap(); + assert_eq!(d.guides_on(layer), std::slice::from_ref(&node)); + assert!(!d.guide_shown(&node) && !d.guide_editable(&node), "its layer is hidden"); d.node_mut(layer).unwrap().visible = true; d.node_mut(layer).unwrap().locked = false; - d.guides.push(crate::Guide::new(false, 5.0)); - d.guides.push(gone); - assert_eq!(d.adopt_guides(), 2); - assert!(d.guides.iter().all(|g| g.layer == Some(layer))); - assert_eq!(d.adopt_guides(), 0, "once"); + assert!(d.guide_shown(&node) && d.guide_editable(&node)); + d.node_mut(id).unwrap().locked = true; + let node = d.ruler_guide(id).unwrap(); + assert!(d.guide_shown(&node) && !d.guide_editable(&node), "locked itself"); + d.node_mut(id).unwrap().visible = false; + assert!(!d.guide_shown(&node), "hidden itself"); + // Saved guides on no layer, or a gone one, go on the top visible, unlocked layer. + d.saved_guides.push(crate::Guide::new(false, 5.0)); + d.saved_guides.push(gone); + assert_eq!(d.guides_into_nodes(), 2); + assert!(d.ruler_guides().iter().all(|g| g.layer == Some(layer))); + assert_eq!(d.ruler_guides().len(), 3); + assert_eq!(d.guides_into_nodes(), 0, "once"); // A guide saved before guides had layers reads as one on no layer. let old: crate::Guide = serde_json::from_str(r#"{"vertical": true, "pos": 5.0}"#).unwrap(); assert_eq!(old.layer, None); @@ -267,7 +282,7 @@ fn random_selection(r: &mut u64, ids: &[NodeId]) -> Selection { s.key = s.objects.get(below(r, s.objects.len() as u64) as usize).copied(); s.target = ids.get(below(r, ids.len() as u64) as usize).copied().filter(|_| below(r, 2) == 0); s.slices = ids.iter().copied().take(below(r, 3) as usize).collect(); - s.guides = vec![1, 0]; + s.guides = vec![NodeId(1), NodeId(0)]; s } diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 781bec84ea..bc558d2702 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -314,6 +314,13 @@ pub struct DocSetup { /// <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/turn-fractional-character-widths-off-or-on.html> #[serde(default, rename = "systemLayout", skip_serializing_if = "crate::skip::is_default")] pub system_layout: bool, + /// Align New Objects to Pixel Grid (New Document › Advanced Options, Transform panel menu): + /// paths and compound paths drawn from then on are pixel-aligned. Objects already in the + /// document, and objects pasted, duplicated or placed, keep their own setting. Off by default + /// and for documents from before it, and saved only when on. + /// <https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html> + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub align_new_objects_to_pixel_grid: bool, } impl Default for DocSetup { @@ -337,6 +344,7 @@ impl Default for DocSetup { export_text: ExportText::Editable, background: Background::Transparent, system_layout: false, + align_new_objects_to_pixel_grid: false, } } } diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index f64bdb4300..1952060663 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -155,6 +155,8 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "shadows-glows", name: "Shadows and Glows", make: shadows_glows }, BuiltinStyleLibrary { id: "outlines-rules", name: "Outlines and Rules", make: outlines_rules }, BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn }, + BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures }, + BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched }, BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes }, BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, @@ -192,8 +194,14 @@ fn round(h: &str, width: f64) -> StrokeLayer { StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..stroke(h, width) } } -/// Live effect `id` with `params` (the others keep the effect's defaults). -fn fx(id: &str, params: Value) -> Effect { +/// Live effect `id` with `params` (the others keep the effect's defaults). A Warp draws with its +/// style's Bézier net, as a new Warp does. +fn fx(id: &str, mut params: Value) -> Effect { + if id.starts_with("warp.") + && let Value::Object(m) = &mut params + { + m.entry("version").or_insert(json!(crate::live::WARP_NET)); + } Effect { id: id.into(), params, visible: true } } @@ -322,6 +330,97 @@ fn hand_drawn() -> Vec<GraphicStyle> { ] } +/// Painted and Sketched: one catalog paint or sketch effect over the whole appearance, so it +/// repaints the fill and the stroke together (watercolor, dry brush, pastels, charcoal and ink). +fn painted_sketched() -> Vec<GraphicStyle> { + vec![ + style( + "Washed Blue", + vec![F(fill("#8ab9c9"))], + vec![fx("artistic.watercolor", json!({"brushDetail": 8.0, "shadowIntensity": 2.0, "texture": 2.0}))], + ), + style( + "Bristle Ochre", + vec![F(fill("#c4975a")), S(stroke("#76533d", 1.0))], + vec![fx("artistic.dryBrush", json!({"brushSize": 4.0, "brushDetail": 7.0, "texture": 2.0}))], + ), + style( + "Pastel Heather", + vec![F(fill("#a78ca5"))], + vec![fx( + "artistic.roughPastels", + json!({ + "strokeLength": 8.0, + "strokeDetail": 9.0, + "texture": "canvas", + "scaling": 100.0, + "relief": 5.0, + "lightDirection": "topLeft", + "invert": false + }), + )], + ), + style( + "Charcoal Shade", + vec![F(fill("#666666"))], + vec![fx("sketch.charcoal", json!({"thickness": 3.0, "detail": 3.0, "lightDarkBalance": 55.0}))], + ), + style( + "Ink Contour", + vec![F(fill("#d9e2df")), S(stroke("#26323b", 1.0))], + vec![fx("brushStrokes.inkOutlines", json!({"strokeLength": 6.0, "darkIntensity": 24.0, "lightIntensity": 8.0}))], + ), + style( + "Wet Ink", + vec![F(fill("#637b85"))], + vec![fx("brushStrokes.sumiE", json!({"strokeWidth": 7.0, "strokePressure": 5.0, "contrast": 20.0}))], + ), + style( + "Fine Pen", + vec![F(fill("#d8d4c6"))], + vec![fx("sketch.graphicPen", json!({"strokeLength": 6.0, "lightDarkBalance": 55.0, "strokeDirection": "rightDiagonal"}))], + ), + ] +} + +/// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and +/// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper). +fn textures() -> Vec<GraphicStyle> { + let surface = |texture: &str, scaling: f64, relief: f64, light: &str| { + fx("texture.texturizer", json!({"texture": texture, "scaling": scaling, "relief": relief, "lightDirection": light, "invert": false})) + }; + vec![ + style( + "Fine Grain", + vec![F(fill("#c9ada7")), S(stroke("#4a4e69", 1.0))], + vec![fx("texture.grain", json!({"intensity": 35.0, "contrast": 55.0, "grainType": "regular"}))], + ), + style("Canvas Weave", vec![F(fill("#e9d8a6"))], vec![surface("canvas", 100.0, 6.0, "topLeft")]), + style("Burlap Sack", vec![F(fill("#bc8a5f")), S(stroke("#6f4518", 1.5))], vec![surface("burlap", 120.0, 8.0, "top")]), + style( + "Cracked Glaze", + vec![F(fill("#94d2bd")), S(stroke("#005f73", 1.0))], + vec![fx("texture.craquelure", json!({"crackSpacing": 12.0, "crackDepth": 5.0, "crackBrightness": 8.0}))], + ), + style( + "Mosaic Floor", + vec![F(fill("#0a9396"))], + vec![fx("texture.mosaicTiles", json!({"tileSize": 10.0, "groutWidth": 3.0, "lightenGrout": 8.0}))], + ), + style("Quilted Squares", vec![F(fill("#ee9b00"))], vec![fx("texture.patchwork", json!({"squareSize": 5.0, "relief": 10.0}))]), + style( + "Leaded Glass", + vec![F(FillLayer::new(linear(-45.0, &[(0.0, "#ae2012", 1.0), (0.5, "#ee9b00", 1.0), (1.0, "#005f73", 1.0)])))], + vec![fx("texture.stainedGlass", json!({"cellSize": 8.0, "borderThickness": 4.0, "lightIntensity": 3.0}))], + ), + style( + "Damp Paper", + vec![F(fill("#4895ef")), S(stroke("#3f37c9", 1.0))], + vec![fx("sketch.waterPaper", json!({"fiberLength": 12.0, "brightness": 55.0, "contrast": 60.0}))], + ), + ] +} + fn gradient_finishes() -> Vec<GraphicStyle> { let rim = |h: &str| S(stroke(h, 1.0)); vec![ @@ -550,6 +649,66 @@ mod tests { assert_eq!(status.name, "Status Effects"); let status_names: Vec<&str> = status.styles.iter().map(|g| g.name.as_str()).collect(); assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); + let textures = builtin_style_library("textures").unwrap(); + assert_eq!(textures.name, "Textures"); + let texture_names: Vec<&str> = textures.styles.iter().map(|g| g.name.as_str()).collect(); + let expected = + ["Fine Grain", "Canvas Weave", "Burlap Sack", "Cracked Glaze", "Mosaic Floor", "Quilted Squares", "Leaded Glass", "Damp Paper"]; + assert_eq!(texture_names, expected); + for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "textures") { + let lib = builtin_style_library(b.id).unwrap(); + assert!(lib.styles.iter().all(|g| !expected.contains(&g.name.as_str())), "{} shares a name with Textures", b.id); + } + let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect(); + assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn"); + } + + /// The built-in styles' Warps draw with the map a new Warp takes. + #[test] + fn builtin_warp_styles_take_the_nets_map() { + let mut warps = 0; + for b in STYLE_LIBRARIES { + let lib = builtin_style_library(b.id).unwrap(); + for g in &lib.styles { + let mut effects: Vec<&Effect> = g.appearance.effects.iter().collect(); + effects.extend(g.appearance.items.iter().flat_map(|i| i.effects())); + for e in effects.into_iter().filter(|e| e.id.starts_with("warp.")) { + assert_eq!(e.params["version"], json!(crate::live::WARP_NET), "{} › {}: {}", b.id, g.name, e.id); + warps += 1; + } + } + } + assert!(warps >= 3, "{warps}"); + } + + #[test] + fn painted_and_sketched_follows_textures_with_one_effect_per_style() { + let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect(); + let at = ids.iter().position(|&id| id == "painted-sketched").expect("listed"); + assert_eq!(ids[at - 1], "textures"); + let lib = builtin_style_library("painted-sketched").unwrap(); + assert_eq!(lib.name, "Painted and Sketched"); + let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Washed Blue", "Bristle Ochre", "Pastel Heather", "Charcoal Shade", "Ink Contour", "Wet Ink", "Fine Pen"]); + let effects: Vec<&str> = lib.styles.iter().flat_map(|g| g.appearance.effects.iter().map(|e| e.id.as_str())).collect(); + assert_eq!( + effects, + [ + "artistic.watercolor", + "artistic.dryBrush", + "artistic.roughPastels", + "sketch.charcoal", + "brushStrokes.inkOutlines", + "brushStrokes.sumiE", + "sketch.graphicPen" + ] + ); + assert!(lib.styles.iter().all(|g| g.appearance.items.iter().all(|i| i.effects().is_empty())), "no effects on a fill or stroke"); + // No other built-in library holds a style of the same name. + for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "painted-sketched") { + let other = builtin_style_library(b.id).unwrap(); + assert!(other.styles.iter().all(|g| !names.contains(&g.name.as_str())), "{}", b.id); + } } #[test] diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 5aa6147fa9..80db3d923a 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -195,9 +195,10 @@ impl Document { /// The default name of a solid swatch: its values in its own colour model ("C=10 M=20 Y=30 K=0", /// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). pub fn color_name(c: Color) -> String { - // Clamped first, so a conversion's tiny negative never reads "-0". - let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round(); - let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round(); + // Clamped first, so a conversion's tiny negative never reads "-0". `clamp` keeps a -0.0, so + // `+ 0.0` turns it into 0. + let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round() + 0.0; + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() + 0.0; match c { Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), @@ -493,6 +494,13 @@ mod tests { assert_eq!(d.new_swatch_name(&Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "R=255 G=0 B=0"); } + #[test] + fn default_names_read_negative_zero_as_zero() { + assert_eq!(color_name(Color::Rgb { r: -0.0, g: 0.5, b: -0.0 }), "R=0 G=128 B=0"); + assert_eq!(color_name(Color::Cmyk { c: -0.0, m: 0.2, y: 0.3, k: -0.0 }), "C=0 M=20 Y=30 K=0"); + assert_eq!(color_name(Color::Gray { k: -0.0 }), "Gray K=0"); + } + #[test] fn free_swatch_names_match_naming_each_swatch_as_it_is_added() { let (mut d, _, _) = doc(); diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 995445f578..6949aa86fb 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -492,7 +492,8 @@ impl NineSliceMap { /// [`Self::most_placed`] for a container placed by [`Self::container`]. fn most_container(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 { let own = self.most_mask(n, boxes, depth).saturating_add(1); - n.children().into_iter().flatten().fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1))) + // As [`Self::container`] places it: a layer's ruler guides left out. + n.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1))) } /// [`Self::most_placed`] for the opacity mask of `n` as [`Self::place_mask`] places it: a @@ -560,7 +561,8 @@ impl NineSliceMap { let kids = out.children_mut().map(std::mem::take).unwrap_or_default(); out.transform(center, false); if let Some(children) = out.children_mut() { - *children = kids.iter().map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect(); + // A ruler guide of a layer is not art: it is not placed. + *children = kids.iter().filter(|c| !c.is_ruler_guide()).map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect(); } self.place_mask(n, &mut out, boxes, depth); out diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 21fe8d7ce9..dcbcd87028 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -91,6 +91,268 @@ fn an_inch_ruler_steps_in_binary_fractions() { assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0)); } +/// Ruler guide nodes on a layer and a sublayer are not art: Select All, a layer's target circle, +/// the object count, the art's bounds, clicks, the marquee and a knockout layer's elements are +/// the same as without them, and transforming the layer leaves them where they are. +#[test] +fn ruler_guide_nodes_are_not_art() { + use crate::hit::{HitOptions, hit_test, marquee, objects_at}; + let (mut d, a, b) = doc_with_rects(); + let layer = d.layers[0].id; + let sub = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(2))).unwrap(); + let s1 = d.alloc_id(); + d.insert(Some(sub), usize::MAX, Node::path(s1, shapes::rectangle(Rect::new(40.0, 0.0, 50.0, 10.0)), Appearance::default_art())).unwrap(); + let opt = HitOptions::default(); + let all = Rect::new(-100.0, -100.0, 700.0, 900.0); + let before = ( + d.selectable_art(), + d.layers[0].layer_art(false), + d.node_count(), + d.art_bounds(), + marquee(&d, all, None, false), + hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)), + ); + let guide = |id, vertical, pos| Node::new(id, NodeKind::RulerGuide { vertical, pos, artboard: None }); + let (g1, g2, g3) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + d.insert(Some(layer), usize::MAX, guide(g1, true, 5.0)).unwrap(); + d.insert(Some(layer), usize::MAX, guide(g2, false, 5.0)).unwrap(); + d.insert(Some(sub), usize::MAX, guide(g3, true, 45.0)).unwrap(); + let after = ( + d.selectable_art(), + d.layers[0].layer_art(false), + d.node_count(), + d.art_bounds(), + marquee(&d, all, None, false), + hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)), + ); + assert_eq!(after, before); + assert_eq!(after.0, [a, b, s1]); + for p in [Point::new(5.0, 300.0), Point::new(300.0, 5.0), Point::new(45.0, 300.0)] { + assert!(hit_test(&d, p, opt).is_none(), "nothing to click on the guide at {p:?}"); + assert!(objects_at(&d, p, opt, None).is_empty()); + } + let mut sel = Selection::default(); + sel.set_target(&d, layer); + assert_eq!(sel.objects, [a, b, s1]); + let children = d.layers[0].children().unwrap().clone(); + assert_eq!(Node::knockout_elements(&children).iter().map(|c| c.id).collect::<Vec<_>>(), [a, b, s1]); + assert!(d.node(g1).is_some_and(Node::is_ruler_guide) && d.node(g1).is_some_and(Node::is_guide)); + assert_eq!(d.node(g1).map(Node::geometric_bounds), Some(None)); + let mut moved = (*d.layers[0]).clone(); + moved.transform(Affine::translate((10.0, 10.0)), true); + let g = moved.children().unwrap().iter().find(|c| c.id == g1).unwrap(); + assert!(matches!(g.kind, NodeKind::RulerGuide { pos, .. } if pos == 5.0)); +} + +/// Art inserted or moved onto a layer goes below the layer's ruler guides, a ruler guide goes +/// among them, and a clipped layer whose art is gone does not clip by a guide. +#[test] +fn layer_art_stays_below_its_ruler_guides() { + let (mut d, a, b) = doc_with_rects(); + let layer = d.layers[0].id; + let guide = |id, pos| Node::new(id, NodeKind::RulerGuide { vertical: true, pos, artboard: None }); + let (g1, g2) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(layer), usize::MAX, guide(g1, 5.0)).unwrap(); + // Asked for the bottom, a guide still goes above the art. + d.insert(Some(layer), 0, guide(g2, 7.0)).unwrap(); + let ids = |d: &Document| d.layers[0].children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>(); + assert_eq!(ids(&d), [a, b, g2, g1]); + let c = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(c, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap(); + assert_eq!(ids(&d), [a, b, c, g2, g1]); + d.move_node(a, Some(layer), usize::MAX).unwrap(); + assert_eq!(ids(&d), [b, c, a, g2, g1]); + d.move_node(g1, Some(layer), 0).unwrap(); + assert_eq!(ids(&d), [b, c, a, g1, g2]); + assert!(d.layer_object(g1).is_none()); + assert_eq!(d.layer_object(a).map(|n| n.id), Some(a)); + + // A clipped layer clips by its first art object; with only guides left it clips nothing. + if let Some(NodeKind::Layer { clip, .. }) = d.node_mut(layer).map(|n| &mut n.kind) { + *clip = true; + } + assert!(d.node(layer).is_some_and(Node::clips)); + for id in [a, b, c] { + d.remove(id).unwrap(); + } + assert!(!d.node(layer).is_some_and(Node::clips)); + + // Reading a file that clips a layer by a path beyond the canvas empties the layer of its art + // only: its guides stay. + let far = d.alloc_id(); + d.insert(Some(layer), 0, Node::path(far, shapes::rectangle(Rect::new(0.0, 0.0, 1e9, 10.0)), Appearance::default_art())).unwrap(); + assert!(d.node(layer).is_some_and(Node::clips)); + let gone = d.drop_beyond_canvas(); + assert_eq!(gone.objects, 1); + assert_eq!(ids(&d), [g1, g2]); +} + +/// `ruler_guides` keeps its list while the layers are unchanged, and lists again after any change +/// inside a layer, made in place or on a shared copy, and after layers are added, removed or +/// reordered. +#[test] +fn ruler_guides_follow_every_edit() { + let (mut d, _, _) = doc_with_rects(); + let layer = d.layers[0].id; + let sub = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap(); + let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 5.0) }); + let g2 = d.add_ruler_guide(&Guide { layer: Some(sub), ..Guide::new(false, 6.0) }); + let line = |d: &Document| d.ruler_guides().iter().map(|g| (g.id, g.pos, g.hidden, g.layer)).collect::<Vec<_>>(); + assert_eq!(line(&d), [(Some(g1), 5.0, false, Some(layer)), (Some(g2), 6.0, false, Some(sub))]); + // Changed in place: the document is the only holder of its layers. + assert!(d.edit_ruler_guide(g2, |g| g.pos = 9.0)); + assert_eq!(line(&d)[1], (Some(g2), 9.0, false, Some(sub))); + d.node_mut(g1).unwrap().visible = false; + assert_eq!(line(&d)[0], (Some(g1), 5.0, true, Some(layer))); + // A copy shares the list until one of them changes. + let copy = d.clone(); + assert_eq!(line(©), line(&d)); + d.remove(g1).unwrap(); + assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub))]); + assert_eq!(line(©).len(), 2); + // A new layer with a guide, then the layers reordered and one removed. + let top = d.add_layer(None); + let g3 = d.add_ruler_guide(&Guide { layer: Some(top), ..Guide::new(true, 1.0) }); + assert_eq!(line(&d).len(), 2); + d.layers.reverse(); + assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub)), (Some(g3), 1.0, false, Some(top))]); + d.layers.retain(|l| l.id != layer); + assert_eq!(line(&d), [(Some(g3), 1.0, false, Some(top))]); +} + +#[test] +fn strip_ruler_guides_leaves_a_layers_art() { + let (mut d, a, b) = doc_with_rects(); + let layer = d.layers[0].id; + let guide = |id| Node::new(id, NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None }); + let sub = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap(); + let (g1, g2) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(layer), usize::MAX, guide(g1)).unwrap(); + d.insert(Some(sub), usize::MAX, guide(g2)).unwrap(); + let mut n = (*d.layers[0]).clone(); + assert!(n.holds_ruler_guides()); + n.strip_ruler_guides(); + assert!(!n.holds_ruler_guides()); + let mut left = vec![]; + n.walk(&mut |c| left.push(c.id)); + assert_eq!(left, [layer, a, b, sub]); + // Other nodes hold none and are left as they are. + let mut p = d.node(a).unwrap().clone(); + p.strip_ruler_guides(); + assert_eq!(&p, d.node(a).unwrap()); +} + +/// The saved `guides` list becomes ruler guide nodes and is written back from them unchanged: +/// guides on a layer, a sublayer, no layer and a deleted layer, with an artboard guide, keep their +/// order, ids, names and their own lock and visibility; a saved id that another node has is +/// replaced; and the saved form of an older entry still reads. +#[test] +fn saved_guides_become_nodes_and_are_saved_back_the_same() { + let (mut d, a, _) = doc_with_rects(); + let layer = d.layers[0].id; + let top = d.add_layer(Some("Top")); + let sub = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap(); + let json = serde_json::json!([ + {"vertical": true, "pos": 10.0, "layer": layer}, + {"vertical": false, "pos": 20.0, "layer": sub, "artboard": 1}, + {"vertical": true, "pos": 30.0}, + {"vertical": false, "pos": 40.0, "layer": 9999}, + {"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true}, + {"vertical": true, "pos": 60.0, "layer": layer, "id": a}, + ]); + d.saved_guides = serde_json::from_value(json).unwrap(); + let before = d.peek_next_id(); + assert_eq!(d.guides_into_nodes(), 6); + assert!(d.saved_guides.is_empty()); + let guides = d.ruler_guides(); + let lines: Vec<(f64, Option<NodeId>)> = guides.iter().map(|g| (g.pos, g.layer)).collect(); + // A guide on no layer, or on a deleted one, goes on the top visible, unlocked layer. + assert_eq!(lines[..4], [(50.0, Some(layer)), (10.0, Some(layer)), (20.0, Some(sub)), (30.0, Some(top))], "by id: the kept id first"); + assert_eq!(lines[4..], [(40.0, Some(top)), (60.0, Some(layer))]); + assert_eq!(guides[0].id, Some(NodeId(500))); + assert!(guides[1..].iter().all(|g| g.id.unwrap().0 > 500), "new ids start above a kept one"); + assert_ne!(guides[5].id, Some(a), "an id another object has is not reused"); + assert!(d.peek_next_id() > 500 && before <= 500); + let edge = d.node(NodeId(500)).unwrap(); + assert!(edge.locked && !edge.visible && edge.name.as_deref() == Some("Edge")); + assert_eq!(guides[2].artboard, Some(1)); + // Each layer's guides sit at its top, above its art and its sublayer. + let kids: Vec<bool> = d.node(layer).unwrap().children().unwrap().iter().map(|c| c.is_ruler_guide()).collect(); + assert_eq!(kids, [false, false, false, true, true, true]); + assert_eq!(d.guides_into_nodes(), 0, "a second run does nothing"); + + // Saved back: the guides leave the layers and the list names each one's layer and id. + let mut saved = d.clone(); + saved.guides_to_saved(); + assert!(saved.ruler_guides().is_empty()); + assert_eq!(saved.node_count(), d.node_count()); + assert_eq!(saved.saved_guides, guides); + let json = serde_json::to_value(&saved).unwrap(); + assert_eq!(json["guides"].as_array().map(Vec::len), Some(6)); + assert_eq!( + json["guides"][0], + serde_json::json!({"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true}) + ); + // Read again, the same guides come back with the same ids. + let mut back: Document = serde_json::from_value(json).unwrap(); + back.fix_next_id(); + back.guides_into_nodes(); + assert_eq!(back.ruler_guides(), guides); + // An older reader of the list ignores the new fields. + #[derive(serde::Deserialize, PartialEq, Debug)] + struct Old { + vertical: bool, + pos: f64, + #[serde(default)] + artboard: Option<u32>, + #[serde(default)] + layer: Option<NodeId>, + } + let old: Vec<Old> = serde_json::from_value(serde_json::to_value(&saved.saved_guides).unwrap()).unwrap(); + assert_eq!(old[0], Old { vertical: true, pos: 50.0, artboard: None, layer: Some(layer) }); + + // A document with no layer gets a "Layer 1" for its guides. + let mut empty = Document::new(10.0, 10.0); + empty.layers.clear(); + empty.saved_guides = vec![Guide::new(true, 1.0)]; + assert_eq!(empty.guides_into_nodes(), 1); + assert_eq!(empty.layers.len(), 1); + assert_eq!(empty.layers[0].name.as_deref(), Some("Layer 1")); + assert_eq!(empty.ruler_guides().len(), 1); +} + +/// Editing, deleting and the artboard moves of ruler guide nodes, and the selection keeping step. +#[test] +fn ruler_guide_nodes_are_edited_by_id() { + let (mut d, a, _) = doc_with_rects(); + let layer = d.layers[0].id; + let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 10.0) }); + let g2 = d.add_ruler_guide(&Guide { artboard: Some(1), ..Guide::new(false, 20.0) }); + assert!(d.edit_ruler_guide(g1, |g| g.pos = 15.0)); + assert!(!d.edit_ruler_guide(a, |g| g.pos = 15.0), "not a guide"); + assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0)); + d.move_artboard_guides(1, Vec2::new(5.0, 7.0)); + assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(27.0)); + d.map_artboard_guides(1, Affine::scale(2.0)); + assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(54.0)); + assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0), "a canvas guide stays"); + d.copy_artboard_guides(1, 2, Vec2::new(0.0, 100.0)); + let copies: Vec<(f64, Option<u32>)> = d.ruler_guides().iter().filter(|g| g.artboard == Some(2)).map(|g| (g.pos, g.artboard)).collect(); + assert_eq!(copies, [(154.0, Some(2))]); + let mut sel = Selection::default(); + sel.set_guides([g1, g2]); + sel.key_guide = Some(g2); + assert_eq!(d.retain_guides(&mut sel, |g| g.artboard.is_none()), 2); + assert_eq!(sel.guides, [g1]); + assert_eq!(sel.key_guide, None); + assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(g1)]); + assert_eq!(d.retain_guides(&mut sel, |_| true), 0); +} + fn doc_with_rects() -> (Document, NodeId, NodeId) { let mut d = Document::new(612.0, 792.0); let layer = d.layers[0].id; diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 74aa5f4440..da845ba739 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -52,7 +52,7 @@ pub struct TextObject { /// the object, so the runs (and their styles) stay the text itself. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ruby: Vec<RubySpan>, - #[serde(default)] + #[serde(default = "ParaStyle::omitted")] pub para: ParaStyle, /// Per-paragraph attributes (see the type's docs); empty = every paragraph uses `para`. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -77,6 +77,15 @@ pub struct TextObject { /// them up round the inside. #[serde(default, rename = "pathSpacing", skip_serializing_if = "crate::skip::is_default")] pub path_spacing: f64, + /// Type › Dynamic Text. On type on a path, the layout scales the text by one factor so it + /// fills the span between its start and end brackets, and fits it again after each edit; the + /// stored sizes keep their proportions, and the layout's `fit_scale` is the factor drawn. On + /// area type it is Block: after each edit the engine sets each line as typed to the frame's + /// width by its font size and writes the sizes into the characters, with the gaps of + /// [`AreaOptions::word_gap`] and [`AreaOptions::line_gap`]. Point type does not use it. Off for + /// new type and for documents from before it, and saved only when on. + #[serde(default, rename = "dynamicText", skip_serializing_if = "crate::skip::is_default")] + pub dynamic_text: bool, /// Wrap objects above this area type, resolved by the engine after each edit (text space). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub wrap: Vec<WrapShape>, diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs index 7bb742f483..848add8f53 100644 --- a/crates/doc/src/text/area.rs +++ b/crates/doc/src/text/area.rs @@ -167,6 +167,15 @@ pub struct AreaOptions { /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). #[serde(skip_serializing_if = "crate::skip::is_default")] pub fit: AreaFit, + /// Dynamic Text's Block ([`super::TextObject::dynamic_text`] on area type): the Desired word + /// spacing the layout sets every paragraph with ([`super::TextObject::layout_justification`]), in + /// percent of a word space (100, the default, is left out when saved). + #[serde(skip_serializing_if = "AreaOptions::is_default_word_gap")] + pub word_gap: f64, + /// Dynamic Text's Block: the points added to each character's size to give its leading (0, the + /// default, is left out when saved). + #[serde(skip_serializing_if = "crate::skip::is_default")] + pub line_gap: f64, } impl Default for AreaOptions { @@ -182,6 +191,8 @@ impl Default for AreaOptions { vertical_align: VerticalAlign::Top, flow: TextFlow::Columns, fit: AreaFit::None, + word_gap: Self::DEFAULT_WORD_GAP, + line_gap: 0.0, } } } @@ -189,6 +200,21 @@ impl Default for AreaOptions { impl AreaOptions { /// The most rows, and the most columns, area type can have. pub const MAX_ROWS_COLUMNS: usize = 100; + /// Block's word gap range (percent of a word space), the Justification word spacing range. + pub const WORD_GAP: (f64, f64) = (0.0, 1000.0); + /// Block's word gap new type starts with: the font's own word space. + pub const DEFAULT_WORD_GAP: f64 = 100.0; + /// Block's line gap range in points. + pub const LINE_GAP: (f64, f64) = (-1296.0, 1296.0); + fn is_default_word_gap(v: &f64) -> bool { + *v == Self::DEFAULT_WORD_GAP + } + /// Block's gaps kept within their ranges; a gap that is not a number gives its default. + pub fn block_gaps(&self) -> (f64, f64) { + let word = if self.word_gap.is_finite() { self.word_gap.clamp(Self::WORD_GAP.0, Self::WORD_GAP.1) } else { Self::DEFAULT_WORD_GAP }; + let line = if self.line_gap.is_finite() { self.line_gap.clamp(Self::LINE_GAP.0, Self::LINE_GAP.1) } else { 0.0 }; + (word, line) + } } /// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index fd828c79af..37c76c5e3a 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -28,6 +28,12 @@ pub struct CharStyle { /// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option<f64>, + /// Space before the character in 1/1000 em, as [`Self::kerning`], when it starts a line by + /// itself: the first character of the text, of a paragraph, or after a forced line break. The + /// Type tool's caret before such a character kerns with it (#5111), since there is no character + /// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect. + #[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")] + pub kerning_before: f64, /// Use glyph shapes for automatic pair spacing; false uses font metrics. #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] pub optical_kerning: bool, @@ -411,6 +417,7 @@ impl Default for CharStyle { leading: None, tracking: 0.0, kerning: None, + kerning_before: 0.0, optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index bb1fa0eb2c..d46b45b1f7 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -1,6 +1,6 @@ use super::area::{AreaOptions, PathAlign, PathEffect}; use super::char_style::CharStyle; -use super::para_style::ParaStyle; +use super::para_style::{JustificationOptions, ParaStyle}; use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end}; use super::tabs_lists::{ListCounts, ParaList}; use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2}; @@ -89,6 +89,7 @@ impl TextObject { path_effect: PathEffect::default(), path_align: PathAlign::default(), path_spacing: 0.0, + dynamic_text: false, wrap: Vec::new(), optical_margin: false, anti_alias: TypeAntiAlias::Sharp, @@ -169,6 +170,19 @@ impl TextObject { pub fn para_at(&self, i: usize) -> &ParaStyle { self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para) } + /// The Justification… options the layout sets `para` with: its own, except that with Dynamic + /// Text's Block on area type ([`Self::dynamic_text`]) the Desired word spacing is the word gap + /// ([`AreaOptions::block_gaps`]), and Minimum and Maximum move out to it when it lies outside + /// them. The paragraph keeps its own values, which apply again when Block is off. + pub fn layout_justification(&self, para: &ParaStyle) -> JustificationOptions { + let mut j = para.justification.clone(); + if self.dynamic_text && matches!(self.kind, TextKind::Area { .. }) { + let gap = self.area.block_gaps().0; + let [min, _, max] = j.word_spacing; + j.word_spacing = [min.min(gap), gap, max.max(gap)]; + } + j + } /// Every paragraph's attributes, one per paragraph. pub fn paragraph_styles(&self) -> Vec<ParaStyle> { (0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect() diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index f23de1d41f..bb3725072e 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -244,9 +244,21 @@ pub struct ParaStyle { /// Insert Kashidas (Paragraph panel): justified lines lengthen their Arabic words with /// kashidas before they widen their word spaces. pub kashida: Kashida, + /// Korean Line Break Anywhere (Paragraph panel menu): a line may break between any two Hangul + /// syllables. Off, a Korean word (the characters between spaces, when any of them is Hangul) + /// breaks only at its spaces and punctuation, or where it is wider than the line. New type and + /// imported text have it off; paragraphs saved before it existed open with it on, the line + /// breaks they were laid out with. + pub korean_line_break_anywhere: bool, } impl ParaStyle { + /// The attributes a text object saved without `para` reads with: the defaults, with Korean + /// Line Break Anywhere on, as a saved paragraph without that field reads. + pub(crate) fn omitted() -> Self { + Self { korean_line_break_anywhere: true, ..Self::default() } + } + /// Keeps the indents and the space before and after to -[`crate::MAX_COORD`] to /// [`crate::MAX_COORD`], and the tab stop positions to 0 to 100,000 pt, the range /// `text.tabs.set` takes. A value outside its range becomes the nearer end, and one that is @@ -330,6 +342,10 @@ struct ParaStyleFile { roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, + /// Written only when off: a paragraph saved without it was laid out breaking between Hangul + /// syllables. + #[serde(default = "crate::yes", skip_serializing_if = "crate::skip::is_true")] + korean_line_break_anywhere: bool, } impl From<ParaStyle> for ParaStyleFile { @@ -361,6 +377,7 @@ impl From<ParaStyle> for ParaStyleFile { kinsoku_type, roman_hanging, kashida, + korean_line_break_anywhere, .. } = p; Self { @@ -386,6 +403,7 @@ impl From<ParaStyle> for ParaStyleFile { kinsoku_type, roman_hanging, kashida, + korean_line_break_anywhere, } } } @@ -415,6 +433,7 @@ impl From<ParaStyleFile> for ParaStyle { kinsoku_type, roman_hanging, kashida, + korean_line_break_anywhere, .. } = f; Self { @@ -439,6 +458,7 @@ impl From<ParaStyleFile> for ParaStyle { kinsoku_type, roman_hanging, kashida, + korean_line_break_anywhere, } } } diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index c4ec92b70b..e213c252bb 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -28,6 +28,15 @@ pub struct TabStop { pub align_on: char, } +impl TabStop { + /// The largest stop position `text.tabs.set` and a paragraph style take, in points. + pub const MAX_POSITION: f64 = 100_000.0; + /// The most leader characters a stop repeats. + pub const MAX_LEADER: usize = 8; + /// The most stops `text.tabs.set` and a paragraph style take in one list. + pub const MAX_STOPS: usize = 256; +} + fn default_align_on() -> char { '.' } @@ -356,6 +365,7 @@ impl ParaList { position: CharPosition::Normal, tracking: 0.0, kerning: None, + kerning_before: 0.0, optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 6a997c9e57..3b3781f87c 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -1,5 +1,19 @@ use super::*; +/// Dynamic Text is off for new type and for type saved before it, and saved only when on. +#[test] +fn dynamic_text_is_saved_only_when_on() { + let t = TextObject::point(Point::ZERO, "Hi", CharStyle::default()); + assert!(!t.dynamic_text); + let off = serde_json::to_value(&t).unwrap(); + assert!(off.get("dynamicText").is_none()); + assert!(!serde_json::from_value::<TextObject>(off).unwrap().dynamic_text); + let on = TextObject { dynamic_text: true, ..t }; + let saved = serde_json::to_value(&on).unwrap(); + assert_eq!(saved["dynamicText"], true); + assert!(serde_json::from_value::<TextObject>(saved).unwrap().dynamic_text); +} + /// Character Direction is saved only when set, and styles written before it existed read as /// Default. #[test] @@ -170,6 +184,29 @@ fn justification_options_read_from_a_file_stay_in_range() { assert_eq!(same, d); } +/// Korean Line Break Anywhere is off for a new paragraph and saved only when off; a paragraph +/// saved before it existed, or a text object saved without paragraph attributes, reads with it on, +/// and both values read back as saved. +#[test] +fn korean_line_break_anywhere_is_saved_only_when_off() { + let off = ParaStyle::default(); + assert!(!off.korean_line_break_anywhere); + let saved = serde_json::to_value(&off).unwrap(); + assert_eq!(saved["korean_line_break_anywhere"], false); + assert_eq!(serde_json::from_value::<ParaStyle>(saved).unwrap(), off); + let on = ParaStyle { korean_line_break_anywhere: true, ..ParaStyle::default() }; + let saved = serde_json::to_value(&on).unwrap(); + assert!(saved.get("korean_line_break_anywhere").is_none()); + assert_eq!(serde_json::from_value::<ParaStyle>(saved).unwrap(), on); + let old: ParaStyle = serde_json::from_str(r#"{"justify":"Left"}"#).unwrap(); + assert!(old.korean_line_break_anywhere); + let mut saved = serde_json::to_value(TextObject::point(Point::ZERO, "가나", CharStyle::default())).unwrap(); + assert_eq!(saved["para"]["korean_line_break_anywhere"], false); + saved.as_object_mut().unwrap().remove("para"); + let old: TextObject = serde_json::from_value(saved).unwrap(); + assert_eq!(old.para, ParaStyle { korean_line_break_anywhere: true, ..ParaStyle::default() }); +} + /// Numbered lists: each number style writes its numbers and rolls over (letters after Z, /// roman numerals in subtractive forms, zero-padded numbers past their digits), the marker adds /// a period, and the count runs through list paragraphs, skips empty and bulleted ones and diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index be3e99522f..795fc69bdf 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -107,7 +107,8 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind { /// `n` with its geometry effects evaluated (`None` = unchanged). fn bake_node(d: &mut Document, n: &Node) -> Option<Node> { // A cancelled export leaves the rest of the document as it is: the caller drops the result. - if !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() { + // A ruler guide draws nothing and stays as it is, last in its layer. + if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() { return None; } // Colour adjustments: the object recoloured (inside it too), then baked as it is. @@ -551,6 +552,21 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { /// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to /// outline nor a geometry effect, so bending first changes nothing. pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> { + bake_appearance_as(doc, n, true) +} + +/// [`bake_appearance`] for the glyph outlines of type in an envelope with Distort Appearance: +/// geometry effects are applied as it applies them, and fills, gradients and patterns are left as +/// it leaves them, but every stroke stays a stroke on its piece instead of becoming its filled +/// outline. The envelope then bends the piece's path, and the stroke paints along the bent outline +/// at its own weight, as `.ai` files draw the strokes of type in an envelope (#6644). `None` when +/// it has no geometry effect, so bending first changes nothing. +pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> { + bake_appearance_as(doc, n, false) +} + +/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`]. +fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option<Node> { if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { return Some(m); } @@ -563,10 +579,10 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> { if crate::has_transform_art(n) && let Some(mut m) = reshape(doc, n, None) { - bake_appearance_pieces(doc, &mut m); + bake_appearance_pieces(doc, &mut m, outline_strokes); return Some(m); } - let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none()); + let outlined = |i: &AppearanceItem| outline_strokes && paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none()); let geometric = has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(item_effects(i))); if !geometric && !n.appearance.items.iter().any(outlined) { return None; @@ -584,7 +600,7 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> { let (ig, mut it) = apply_item(item, carried, &g, &ctx); clear_item_effects(&mut it); pieces.push(match &it { - AppearanceItem::Stroke(st) if st.brush.is_none() => { + AppearanceItem::Stroke(st) if outline_strokes && st.brush.is_none() => { let outline = crate::stroke::outline_region(&ig, rule, st); match st.path_gradient() { // A gradient along or across the stroke: its gradient meshes clipped to the outline. @@ -617,16 +633,16 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> { Some(m) } -/// [`bake_appearance`] every path and compound path in `n` that it changes, in place. -fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node) { +/// [`bake_appearance_as`] every path and compound path in `n` that it changes, in place. +fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes: bool) { if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { - if let Some(m) = bake_appearance(doc, n) { + if let Some(m) = bake_appearance_as(doc, n, outline_strokes) { *n = m; } return; } for c in n.children_mut().into_iter().flatten() { - bake_appearance_pieces(doc, Arc::make_mut(c)); + bake_appearance_pieces(doc, Arc::make_mut(c), outline_strokes); } } diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index 4751b137c9..2bcc026340 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -575,6 +575,27 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline assert_eq!(ch[1].opacity, 0.5); } +/// Distort Appearance on the pieces of type's glyph outlines (#6644): a stroke's geometry effect +/// still bakes into its piece, but the stroke stays a stroke at its own weight; a piece with no +/// geometry effect is left as it is, its stroke on it (Distort Appearance on a path outlines it). +#[test] +fn type_pieces_bake_their_geometry_effects_and_keep_their_strokes() { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + assert!(bake_type_appearance(None, &n).is_none(), "nothing to bake"); + assert!(bake_appearance(None, &n).is_some(), "a path's stroke is outlined"); + if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.width = 4.0; + s.effects.push(fx("path.offsetPath", json!({"offset": 5.0}))); + } + let m = bake_type_appearance(None, &n).unwrap(); + let ch = m.children().unwrap(); + assert_eq!(ch.len(), 2); + let Some(AppearanceItem::Stroke(st)) = ch[1].appearance.items.first() else { panic!("still a stroke: {:?}", ch[1].appearance) }; + assert!(st.width == 4.0 && st.effects.is_empty(), "{st:?}"); + assert!((ch[1].geometric_bounds().unwrap().width() - 110.0).abs() < 0.5, "the stroke's offset is baked into its path"); + assert!((ch[0].geometric_bounds().unwrap().width() - 100.0).abs() < 1e-6, "the fill keeps the square"); +} + /// A 100 pt square at the origin painted by `fill` and `stroke` (`width` pt), with the Transform /// effect `params`. fn transformed(fill: Paint, stroke: Paint, width: f64, params: serde_json::Value) -> Node { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index e9bbaf4bbf..84991392b2 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -1,4 +1,7 @@ -use super::{CLASSIC_EXTRUDE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap}; +use super::{ + CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, + json, trap, +}; /// Catalogue entry for one effect. #[derive(Clone, Debug, PartialEq)] @@ -81,6 +84,7 @@ fn lengths_of(id: &str) -> Lengths { "threeD.revolve" => always(&["offset"]), "threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]), "threeD.classicExtrude" => always(&["depth", "bevelHeight"]), + "threeD.classicRevolve" => always(&["offset"]), "threeD.inflate" => always(&["depth"]), "path.outlineStroke" => always(&["width"]), "stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]), @@ -112,7 +116,7 @@ fn lengths_of(id: &str) -> Lengths { } } -const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}"; +const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds, and images bend as 10 × 10 cells of two triangles unless the pieces would make the art pass 2,000,000 objects or the image's frame keeps its shape past the anchor budget), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\", version: 0|1 (the map: 1 bends each style as one Bézier patch over the bounds, which new and imported warps get; 0, or none, is VectorCraft's earlier map, which warps saved without a version keep)}"; const DT: &[&str] = &["Effect", "Distort & Transform"]; @@ -176,29 +180,29 @@ pub fn effect_catalog() -> Vec<EffectInfo> { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", - json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"cap":true,"expandVisibleOnly":true}), + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", - json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Painted with the top fill (else the top stroke).", - json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Painted with the top fill (else the top stroke).", + json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", - json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}), + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), ), g( CLASSIC_EXTRUDE, @@ -207,6 +211,20 @@ pub fn effect_catalog() -> Vec<EffectInfo> { "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}), ), + g( + CLASSIC_REVOLVE, + "Revolve (Classic)…", + &["Effect", "3D and Materials", "3D (Classic)"], + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}), + ), + g( + CLASSIC_ROTATE, + "Rotate (Classic)…", + &["Effect", "3D and Materials", "3D (Classic)"], + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}), + ), g( "convertToShape.rectangle", "Rectangle…", diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 73d7266c31..57f2fc8613 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -455,6 +455,17 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou return None; } let source: &[Arc<Node>] = group.children()?; + // A layer's ruler guides take no part in the operation: they stay above its result. + let art = Node::guide_run_start(source); + if art < source.len() { + let mut without = group.clone(); + if let Some(ch) = without.children_mut() { + ch.truncate(art); + } + let mut out = pathfinder_children(doc, &without, hook)?; + out.extend(source.iter().skip(art).cloned()); + return Some(out); + } let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() { // The group's own appearance paints the area ([`evaluate_container`]), so the art has none. match compound_shape_area(doc, group, hook) { @@ -708,6 +719,37 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)], Some(g) } +/// Whether a sublayer among the members of `n`, or among its groups' members, holds a ruler guide. +fn sublayer_guides(n: &Node) -> bool { + n.children().is_some_and(|ch| ch.iter().any(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c)))) +} + +/// Move the ruler guides of the sublayers among the members of `n`, and among its groups' +/// members, to `out`, in order. A guide taken from a hidden or locked sublayer, or from one inside +/// such a sublayer or group, is hidden or locked itself. Only containers holding one are copied. +fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, hidden: bool, locked: bool) { + let Some(ch) = n.children_mut() else { return }; + for c in ch.iter_mut().filter(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))) { + let c = Arc::make_mut(c); + let (hidden, locked) = (hidden || !c.visible, locked || c.locked); + if c.is_layer() + && let Some(lc) = c.children_mut() + { + let (taken, art): (Vec<_>, Vec<_>) = std::mem::take(lc).into_iter().partition(|g| g.is_ruler_guide()); + *lc = art; + out.extend(taken.into_iter().map(|mut g| { + if hidden || locked { + let g = Arc::make_mut(&mut g); + g.visible &= !hidden; + g.locked |= locked; + } + g + })); + } + take_sublayer_guides(c, out, hidden, locked); + } +} + /// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects /// reshaping all its members as one piece (the whole art's bounds as their reference box), and its /// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below @@ -727,9 +769,16 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> { return None; } let mut m = n.clone(); + // A layer's ruler guides take no part: they go back above the evaluated art at the end. + let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default(); + // So do its sublayers' guides, which would otherwise go with the art the effects replace or + // copy: they stay on this layer, hidden and locked as their sublayers were. + if m.is_layer() && (pathfinder || !fx.is_empty()) { + take_sublayer_guides(&mut m, &mut guides, false, false); + } if pathfinder { let hook = |c: &Node| crate::outline_object(doc, c); - let result = pathfinder_children(doc, n, Some(&hook)).unwrap_or_default(); + let result = pathfinder_children(doc, &m, Some(&hook)).unwrap_or_default(); if let Some(ch) = m.children_mut() { *ch = result; } @@ -762,6 +811,9 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> { } m.appearance.items.clear(); m.appearance.contents_index = None; + if let Some(ch) = m.children_mut() { + ch.extend(guides); + } Some(m) } diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 94456c7d57..16e893ce99 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -820,3 +820,112 @@ fn nested_compound_shapes_take_part_as_their_area() { assert!((area(&out[0]) - 50.0).abs() < 0.01); assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape"); } + +/// The ruler guides of a layer with a Pathfinder effect, a Transform effect that copies its art, or +/// fills and strokes of its own take no part: they stay last in the layer, once and unchanged. +#[test] +fn a_layers_ruler_guides_stay_last_through_its_effects() { + use vectorcraft_doc::LayerColor; + let guide = |id, pos| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: true, pos, artboard: None })); + let layer = |effect: &str, params: serde_json::Value| { + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), guide(20, 3.0), guide(21, 8.0)]; + } + l.appearance.effects.push(Effect { id: effect.into(), params, visible: true }); + l + }; + let tail = |n: &Node| { + let ch = n.children().unwrap(); + assert_eq!(ch.iter().filter(|c| c.is_ruler_guide()).count(), 2, "each guide once"); + ch.iter().rev().take(2).map(|c| c.kind.clone()).collect::<Vec<_>>() + }; + let guides = vec![guide(21, 8.0).kind.clone(), guide(20, 3.0).kind.clone()]; + + let add = layer("pathfinder.add", serde_json::json!({})); + let out = pathfinder_children(None, &add, None).unwrap(); + assert_eq!(out.len(), 3, "the united area, then the two guides"); + assert!((area(&out[0]) - 150.0).abs() < 0.01); + assert!(out[1].is_ruler_guide() && out[2].is_ruler_guide()); + assert_eq!(tail(&evaluate_container(None, &add).unwrap()), guides); + + let copies = layer("distort.transform", serde_json::json!({"moveH": 30, "copies": 2})); + let art = evaluate_container(None, &copies).unwrap(); + assert_eq!(tail(&art), guides); + assert_eq!(art.children().unwrap().len(), 5, "three groups of the art, then the two guides"); + let mut art = copies.clone(); + crate::reshape::reshape_leaves(&mut art, &copies.appearance.effects.iter().collect::<Vec<_>>(), &copies.appearance.effects, None); + assert_eq!(tail(&art), guides); + assert_eq!(art.children().unwrap().len(), 5, "reshaped as members too"); + + let mut painted = layer("distort.transform", serde_json::json!({"moveH": 30})); + painted.appearance.items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items; + assert_eq!(tail(&evaluate_container(None, &painted).unwrap()), guides); +} + +/// The ruler guides of a sublayer in a layer with a Pathfinder effect, or a Transform effect that +/// copies its art, stay on a layer of the evaluated art, once, hidden and locked as the sublayer is. +#[test] +fn a_sublayers_ruler_guides_survive_its_layers_effects() { + use vectorcraft_doc::LayerColor; + let layer = |effect: &str, params: serde_json::Value, shown: bool| { + let mut sub = Node::layer(NodeId(11), "Sub", LayerColor::Preset(1)); + (sub.visible, sub.locked) = (shown, !shown); + if let Some(ch) = sub.children_mut() { + *ch = vec![ + sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), + Arc::new(Node::new(NodeId(20), NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None })), + ]; + } + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(sub)]; + } + l.appearance.effects.push(Effect { id: effect.into(), params, visible: true }); + l + }; + // The guides found where ruler guides are looked for: directly in a layer or sublayer. + fn listed(n: &Node, out: &mut Vec<(NodeId, bool, bool)>) { + for c in n.children().into_iter().flatten() { + if c.is_ruler_guide() { + out.push((c.id, c.visible, c.locked)); + } else if c.is_layer() { + listed(c, out); + } + } + } + for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] { + for shown in [true, false] { + let art = evaluate_container(None, &layer(effect, params.clone(), shown)).unwrap(); + let mut found = vec![]; + listed(&art, &mut found); + assert_eq!(found, [(NodeId(20), shown, !shown)], "{effect}: the sublayer's guide, once, on a layer"); + } + } +} + +/// A sublayer's ruler guide inside a hidden or locked group stays hidden or locked when its layer's +/// Pathfinder effect moves it onto the layer, as the group made it. +#[test] +fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked() { + use vectorcraft_doc::LayerColor; + for (hidden, locked) in [(true, false), (false, true), (false, false)] { + let mut sub = Node::layer(NodeId(11), "Sub", LayerColor::Preset(1)); + if let Some(ch) = sub.children_mut() { + *ch = vec![ + sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), + Arc::new(Node::new(NodeId(20), NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None })), + ]; + } + let mut group = Node::group(NodeId(12), vec![Arc::new(sub)]); + (group.visible, group.locked) = (!hidden, locked); + let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(group)]; + } + l.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true }); + let art = evaluate_container(None, &l).unwrap(); + let guides: Vec<_> = art.children().into_iter().flatten().filter(|c| c.is_ruler_guide()).map(|c| (c.id, c.visible, c.locked)).collect(); + assert_eq!(guides, [(NodeId(20), !hidden, locked)], "hidden {hidden}, locked {locked}"); + } +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index ae8b7d9e90..8591bbab2c 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -68,7 +68,7 @@ pub use adjust::{ ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment, is_channel, }; -pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake}; +pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake}; pub use clip::clip_outline; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, @@ -83,18 +83,20 @@ pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, 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_art_in, revolve_options, validate_revolve, validate_revolve_in}; +pub use revolve::{ + CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, +}; pub use solids::{ - CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, - classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in, - three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, - validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, + classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in, + three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, + validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; pub use vectorcraft_three_d::Mesh; -pub use warp::{WarpStyle, warp_point}; +pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version}; mod catalog; mod geometry; diff --git a/crates/effects/src/live.rs b/crates/effects/src/live.rs index 03b335f010..2c02f886c0 100644 --- a/crates/effects/src/live.rs +++ b/crates/effects/src/live.rs @@ -2,8 +2,9 @@ //! every exporter, with what the pure evaluation in [`vectorcraft_doc::live`] can't do itself //! ([`Hooks`]): type inside an envelope distorts as its glyph outlines, run by run //! ([`outline_text`]); symbol instances as their symbol's art; with Distort Appearance strokes and -//! geometry effects bend with the art ([`bake_appearance`]); with Distort Pattern Fills the pattern -//! tiles do. +//! geometry effects bend with the art ([`bake_appearance`]), except type's strokes, which paint +//! along its bent outlines at their own weight ([`bake_type_appearance`], #6644); with Distort +//! Pattern Fills the pattern tiles do. use std::sync::Arc; @@ -11,7 +12,7 @@ use vectorcraft_doc::live::{self, Hooks, Outliner}; use vectorcraft_doc::{Document, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect}; -use crate::{bake_appearance, outline_text}; +use crate::{bake_appearance, bake_type_appearance, outline_text}; /// The text outliner live evaluation uses: type as its glyph outlines, one path per run in the /// run's paint ([`outline_text`]). @@ -44,7 +45,8 @@ fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R { let outline = |n: &Node| outline_object(doc, n); let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region)); let appearance = |n: &Node| bake_appearance(doc, n); - f(Hooks { outline: Some(&outline), appearance: Some(&appearance), pattern: Some(&tiles), symbols: doc }) + let type_appearance = |n: &Node| bake_type_appearance(doc, n); + f(Hooks { outline: Some(&outline), appearance: Some(&appearance), type_appearance: Some(&type_appearance), pattern: Some(&tiles), symbols: doc }) } /// One level of evaluation of live object `n` ([`live::expand_live_hooks`]). diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 7785aff335..1e3c8c1d31 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -31,7 +31,8 @@ pub fn merged_params(id: &str, params: &Value) -> Value { /// (`lightRotation`, `lightHeight`, `lightBehind`). Scribble took one `variation` before its /// separate `overlapVariation` and `spacingVariation`. Earlier values (from a file or a script of /// then) become the current ones that show exactly the same, unless those are given too, which win. -/// Scribble's angle is also stored above -180° and up to 180° (270° becomes -90°). +/// Scribble's angle is also stored above -180° and up to 180° (270° becomes -90°), and a Warp's +/// map `version` given as a whole float is stored as an integer. pub fn upgrade_params(id: &str, params: &Value) -> Value { match params { Value::Object(m) => { @@ -39,6 +40,7 @@ pub fn upgrade_params(id: &str, params: &Value) -> Value { upgrade_perspective(id, &mut m); upgrade_light(id, &mut m); upgrade_scribble(id, &mut m); + upgrade_warp_version(id, &mut m); Value::Object(m) } other => other.clone(), @@ -71,6 +73,19 @@ fn upgrade_perspective(id: &str, m: &mut Map<String, Value>) { } } +/// A Warp's map `version` given as a whole float (`1.0`) is stored as the integer. +fn upgrade_warp_version(id: &str, m: &mut Map<String, Value>) { + if !id.starts_with("warp.") { + return; + } + if let Some(v) = m.get_mut("version") + && !v.is_u64() + && let Some(n) = crate::warp::warp_version(v) + { + *v = json!(n); + } +} + fn upgrade_scribble(id: &str, m: &mut Map<String, Value>) { if id != "stylize.scribble" { return; @@ -91,7 +106,15 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> { if !catalog_index().contains_key(id) { vectorcraft_plugins::effect::installed(id)?; } - Some(Effect { id: id.to_string(), params: merged_params(id, params), visible: true }) + let mut params = merged_params(id, params); + // A new Warp takes its style's Bézier net unless a map is given; the catalog's defaults carry + // no version, so warps saved without one keep the earlier map. + if id.starts_with("warp.") + && let Value::Object(m) = &mut params + { + m.entry("version").or_insert(json!(crate::warp::WARP_NET)); + } + Some(Effect { id: id.to_string(), params, visible: true }) } /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 0bdc134625..9d93f82a79 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -4,19 +4,22 @@ //! Geometry effects reach them through outlines: [`outline_art`] turns the object into plain paths //! (glyph outlines, the evaluated live object, the symbol's art) and [`reshape`] runs each effect //! over all of them as one piece, with the whole art's bounds as the effect's reference box, so a -//! warp bends a line of type as a whole. An image is clipped by its reshaped frame. Raster effects -//! (shadows, glows, blur, feather) stay on the result for the renderer and exporters. Type without +//! warp bends a line of type as a whole. An image is clipped by its reshaped frame, and a Warp +//! effect bends its pixels with the frame ([`cut_warped_images`]). Raster effects (shadows, glows, blur, +//! feather) stay on the result for the renderer and exporters. Type without //! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those //! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and //! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives //! them ([`image_rows`]). use std::collections::HashSet; +use std::rc::Rc; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use vectorcraft_doc::live::Hooks; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, shapes}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes}; use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params}; @@ -548,7 +551,14 @@ fn as_art_opts( let mut art = match &n.kind { NodeKind::Image(im) => { let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); - let image = Node::new(n.id, n.kind.clone()); + let mut image = Node::new(n.id, n.kind.clone()); + // Its pixels draw as the image's do: colorized by a grayscale image's fill color, and + // smoothed or not. + { + let mut e = image.extras_mut(); + e.colorize = n.extras().colorize.clone(); + e.pixelated = n.extras().pixelated; + } let clipped = || { let mut clip = Node::path(n.id, frame.clone(), Appearance::default()); if let NodeKind::Path { clipping, .. } = &mut clip.kind { @@ -632,9 +642,9 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> { /// Apply `fx` to every path under `art` as one piece: each effect takes the whole art's bounds as /// its reference box and the art's seed (a random Transform moves the pieces together). Images and -/// symbol instances follow a Transform effect the same way ([`transform_placed`]); other geometry -/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The -/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path +/// symbol instances follow a Transform effect the same way ([`transform_placed`]), and images +/// follow a Warp effect as a raster mesh warp ([`cut_warped_images`]); other geometry effects leave them +/// as they are. The paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path /// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns /// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one /// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]). @@ -705,8 +715,9 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget let max = budget.at_least(used); // Read before the effects run: a path's own copies don't make it art of several objects. let copy_whole = copies_whole(art); + let mut warped = WarpedImages::new(); for e in fx { - let Some(bounds) = art.geometric_bounds() else { break }; + let Some(bounds) = warped.bounds(art) else { break }; let params = merged_params(&e.id, &e.params); // Where a live-effect plug-in sits, which it is listed by when it is deferred. let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); @@ -739,10 +750,21 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget } let mut groups = vec![]; if follows { - group_marks(art, &mut vec![], &HashSet::new(), &mut groups); + group_marks(art, &mut vec![], &HashSet::new(), None, &mut groups); + // The images earlier Warps bend are measured by their pieces only when a group's + // gradient needs the bounds. + if !groups.is_empty() + && let Some(images) = warped.when_cut(art) + { + groups.clear(); + group_marks(art, &mut vec![], &HashSet::new(), Some(images), &mut groups); + } } - // The ids of the paths that kept their shape (past the budget). + // The ids of the paths that kept their shape (past the budget), and their places in the + // order [`for_each_leaf`] visits the paths. let mut kept_ids = HashSet::new(); + let mut kept_leaves = HashSet::new(); + let mut leaf_at = 0usize; let transform = (e.id == "distort.transform").then(|| { let (m, copies) = crate::distort::transform_map(bounds, ¶ms, seed); let options = crate::distort::TransformOptions::of(¶ms); @@ -757,6 +779,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget continue; } for_each_leaf(art, &mut |leaf| { + let at = leaf_at; + leaf_at += 1; let Some((path, rule)) = leaf_geometry(leaf) else { return }; // What the other paths leave of the budget. let before = Budget::of(&path); @@ -789,6 +813,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None }); let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else { kept_ids.insert(leaf.id); + kept_leaves.insert(at); return; }; used = used.minus(before).plus(Budget::of(&out)); @@ -804,6 +829,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget if boxes { rebase_leaves(art, &mut leaves.into_iter()); } + // Warp bends images too: each one's pixels follow the warp's map over the same box. The + // images are cut into pieces once, after the last effect ([`cut_warped_images`]). An image + // whose clipping frame kept its shape (past the budget) keeps its pixels as they are. + if let Some(style) = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id) + && crate::warp::bends(&e.id, ¶ms) + { + let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, ¶ms)); + warped.reserve(art); + mark_warped_images(art, &f, &kept_leaves, false, &mut 0, &mut warped); + } if let Some((m, copies, options, _)) = transform && options.objects { @@ -816,14 +851,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget // follow their bounds under Free Distort and Warp (they stay when no path changed them). // Each stays when a path under it that its bounds measure kept its shape (past the budget). let mut after = vec![]; - let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, &mut after).1; + let images = if groups.is_empty() { None } else { warped.when_cut(art) }; + let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, images, &mut after).1; if !groups.is_empty() { carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, ¶ms, bounds, from, to, seed)); } if follows && !held { - whole.push(crate::Carry::of(&e.id, ¶ms, bounds, Some(bounds), art.geometric_bounds(), seed)); + whole.push(crate::Carry::of(&e.id, ¶ms, bounds, Some(bounds), warped.bounds(art), seed)); } } + cut_warped_images(art, &warped); whole } @@ -974,7 +1011,7 @@ fn effects_cost(leaf: &Node, path: &PathData) -> Budget { /// Remove the guides anywhere under `n`. fn without_guides(n: &mut Node) { let Some(children) = n.children_mut() else { return }; - children.retain(|c| !matches!(c.kind, NodeKind::Path { guide: true, .. })); + children.retain(|c| !c.is_guide()); children.iter_mut().for_each(|c| without_guides(Arc::make_mut(c))); } @@ -984,7 +1021,9 @@ fn without_guides(n: &mut Node) { /// [`crate::distort::MAX_COPY_OBJECTS`] nodes in all, the art of opacity masks counted. Returns what /// the art costs after. fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget { - let Some(members) = art.children().cloned() else { return art_cost(art) }; + let Some(mut members) = art.children().cloned() else { return art_cost(art) }; + // A layer's ruler guides are not copied: they stay above the copies, once. + let guides = members.split_off(Node::guide_run_start(&members)); let original = Node::group(art.id, members); let mut made = copy_cost(&original); let mut drawn = original.clone(); @@ -1014,6 +1053,7 @@ fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc:: // The last copy is the lowest. placements.reverse(); placements.push(Arc::new(original)); + placements.extend(guides); if let Some(children) = art.children_mut() { *children = placements; } @@ -1442,17 +1482,25 @@ type GroupMark = (Vec<usize>, Option<Rect>, bool); /// The geometric bounds of `n` (as [`Node::geometric_bounds`] gives them) and whether a path or /// compound path below it that those bounds measure is in `kept`, measured in one walk. Each group below `n` that -/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`. -fn group_marks(n: &Node, at: &mut Vec<usize>, kept: &HashSet<NodeId>, out: &mut Vec<GroupMark>) -> (Option<Rect>, bool) { +/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`. An image that `images` +/// lists is measured by the pieces it will be cut into ([`WarpedImages::image_bounds`]). +fn group_marks( + n: &Node, + at: &mut Vec<usize>, + kept: &HashSet<NodeId>, + images: Option<&WarpedImages>, + out: &mut Vec<GroupMark>, +) -> (Option<Rect>, bool) { match &n.kind { NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => (n.geometric_bounds(), kept.contains(&n.id)), + NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { at.push(i); - let (b, h) = group_marks(c, at, kept, out); + let (b, h) = group_marks(c, at, kept, images, out); if is_member_group(c) && (c.appearance.has_positioned_gradient() || c.appearance.has_unplaced_gradient()) { out.push((at.clone(), b, h)); } @@ -1587,6 +1635,225 @@ pub(crate) fn transform_placed_within(n: &mut Node, m: Affine, copies: usize, ma copy_placed(n, m, copies, &mut room); } +/// Rows and columns of the pieces a Warp effect cuts an image into (VectorCraft's own number). +pub(crate) const WARP_IMAGE_CELLS: usize = 10; + +/// A Warp effect's point map, shared by the images it bends. +pub(crate) type WarpMap = Rc<dyn Fn(Point) -> Point>; + +/// One image a Warp effect bent: the image's own key, and each warp it took with the placement +/// the image had when it took it, in order. +type WarpedImage = (String, Vec<(WarpMap, Affine)>); + +/// The images Warp effects bend while [`reshape_leaves_apart`] runs the effects. Each such image's +/// key is replaced by a key of this table ([`WarpedImages::add`]), which a copy a later Transform +/// effect makes keeps. The images are cut into pieces once, after the last effect +/// ([`cut_warped_images`]): the effects after a Warp reshape the image's frame, not each piece, +/// and a later Warp or Transform moves the one set of pieces. +pub(crate) struct WarpedImages { + /// What this table's keys start with: no image key in the art starts with it + /// ([`WarpedImages::reserve`]). + prefix: String, + /// The prefix was checked against the art's image keys. + reserved: bool, + images: Vec<WarpedImage>, +} + +impl WarpedImages { + pub(crate) fn new() -> Self { + static TABLES: AtomicUsize = AtomicUsize::new(0); + Self { prefix: format!("\0warp{}:", TABLES.fetch_add(1, Ordering::Relaxed)), reserved: false, images: vec![] } + } + + /// Before the first image of `art` is marked: lengthen the prefix until no image key in `art` + /// starts with it, so no key from the document is read as one of this table's. + pub(crate) fn reserve(&mut self, art: &Node) { + if self.reserved { + return; + } + self.reserved = true; + let mut keys = vec![]; + art.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + keys.push(im.key.clone()); + } + }); + while keys.iter().any(|k| k.starts_with(self.prefix.as_str())) { + self.prefix.push(':'); + } + } + + /// What this table's keys start with. + #[cfg(test)] + pub(crate) fn prefix(&self) -> &str { + &self.prefix + } + + /// The image that `key`, a key of this table, stands for. + fn get(&self, key: &str) -> Option<&WarpedImage> { + self.images.get(key.strip_prefix(self.prefix.as_str())?.parse::<usize>().ok()?) + } + + /// Record that the image with key `key`, placed by `xf`, takes warp `f`; returns the image's + /// new key. + fn add(&mut self, key: &str, xf: Affine, f: &WarpMap) -> String { + let (own, mut warps) = self.get(key).cloned().unwrap_or_else(|| (key.to_string(), vec![])); + warps.push((f.clone(), xf)); + self.images.push((own, warps)); + format!("{}{}", self.prefix, self.images.len() - 1) + } + + /// Does the art `n` have room, within `max` nodes, for the pieces of every image under it that + /// this table lists? + fn fits(&self, n: &Node, max: usize) -> bool { + let mut count = 0usize; + n.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind + && self.get(&im.key).is_some() + { + count += 1; + } + }); + vectorcraft_doc::live::mesh_warp_cost(WARP_IMAGE_CELLS).saturating_mul(count) <= max.saturating_sub(n.count()) + } + + /// The geometric bounds of `art` as it draws after the effects so far: each image this table + /// lists measured by the pieces the warps and moves it took would cut it into, when the art + /// has room for them ([`cut_warped_images`]). + pub(crate) fn bounds(&self, art: &Node) -> Option<Rect> { + if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { + return art.geometric_bounds(); + } + // The pieces the images would be cut into now: each group of pieces is shown or hidden as + // its image is, and hidden objects are left out of a layer's bounds. + let mut probe = art.clone(); + restore_warped_images(&mut probe, self, true); + probe.geometric_bounds() + } + + /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the + /// warps and moves it took would cut it into. + fn image_bounds(&self, n: &Node) -> Option<Rect> { + let NodeKind::Image(im) = &n.kind else { return n.geometric_bounds() }; + if self.get(&im.key).is_none() { + return n.geometric_bounds(); + } + let mut probe = Node::group(n.id, vec![Arc::new(n.clone())]); + restore_warped_images(&mut probe, self, true); + probe.geometric_bounds() + } + + /// This table when the art `art` has room for the pieces of the images it lists, so that a + /// measure of the art takes them bent ([`WarpedImages::bounds`]); `None` otherwise. + fn when_cut(&self, art: &Node) -> Option<&Self> { + (!self.images.is_empty() && self.fits(art, crate::distort::MAX_COPY_OBJECTS)).then_some(self) + } +} + +/// Record in `warped` that each image under `n` takes warp `f`, walking the groups and layers +/// [`for_each_leaf`] walks and counting the paths it passes in `at`. `kept` holds the places of +/// the paths that kept their shape (past the budget), in the order [`for_each_leaf`] visits the +/// paths of the art: an image in a clip group whose clipping art holds one (`held`) does not take +/// the warp. +pub(crate) fn mark_warped_images(n: &mut Node, f: &WarpMap, kept: &HashSet<usize>, held: bool, at: &mut usize, warped: &mut WarpedImages) { + let (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }) = &mut n.kind else { return }; + let mut held = held; + // A clip group's first member is its clipping art: when a path in it kept its shape, it and + // the members it clips keep theirs. + if *clip && let Some(first) = children.first() { + let start = *at; + held |= (start..start + leaf_count(first)).any(|p| kept.contains(&p)); + } + for c in children.iter_mut() { + match &c.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => *at += 1, + NodeKind::Group { .. } | NodeKind::Layer { .. } => mark_warped_images(Arc::make_mut(c), f, kept, held, at, warped), + NodeKind::Image(_) if !held => { + if let NodeKind::Image(im) = &mut Arc::make_mut(c).kind { + im.key = warped.add(&im.key, im.xf, f); + } + } + _ => {} + } + } +} + +/// Give each image under `n` that `warped` lists its own key back, and cut it into the pieces of +/// a raster mesh warp ([`vectorcraft_doc::live::mesh_warp_image`], each piece drawn as the image +/// is, smoothed or not) through the warps it took and the moves between and after them +/// ([`warped_map`]). The art keeps to [`crate::distort::MAX_COPY_OBJECTS`] nodes: when the pieces +/// would pass it, no image is cut. An image whose placement has no inverse is not cut either. +fn cut_warped_images(n: &mut Node, warped: &WarpedImages) { + cut_warped_images_within(n, warped, crate::distort::MAX_COPY_OBJECTS); +} + +/// [`cut_warped_images`] with the art keeping to `max` nodes. +pub(crate) fn cut_warped_images_within(n: &mut Node, warped: &WarpedImages, max: usize) { + if warped.images.is_empty() { + return; + } + let cut = warped.fits(n, max); + restore_warped_images(n, warped, cut); +} + +/// The walk of [`cut_warped_images`]: each listed image gets its key back, and with `cut` is cut +/// into pieces. +fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) { + let Some(children) = n.children_mut() else { return }; + for c in children.iter_mut() { + let NodeKind::Image(im) = &c.kind else { + if c.children().is_some() { + restore_warped_images(Arc::make_mut(c), warped, cut); + } + continue; + }; + let Some((key, warps)) = warped.get(&im.key) else { continue }; + let mut image = (**c).clone(); + let NodeKind::Image(own) = &mut image.kind else { continue }; + own.key = key.clone(); + // The pieces start from the image as it was placed when it took its first warp. + let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() }); + let map = warped_map(warps, own.xf); + *c = Arc::new(match (first, map) { + (Some(first), Some(map)) if cut => { + let pixelated = image.extras().pixelated; + vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false) + } + _ => image, + }); + } +} + +/// The map that takes a point of an image placed by the first of `warps`' placements to where the +/// warps and the moves between them take it, for an image now placed by `placed`: each warp in +/// turn, then the move from the placement the image had when it took that warp to the one it had +/// at the next, or to `placed` after the last. `None` when a placement has no inverse. +fn warped_map(warps: &[(WarpMap, Affine)], placed: Affine) -> Option<Box<dyn Fn(Point) -> Point>> { + let mut steps: Vec<(WarpMap, Affine)> = Vec::with_capacity(warps.len()); + for (i, (f, at)) in warps.iter().enumerate() { + let det = at.determinant(); + if !det.is_finite() || det == 0.0 { + return None; + } + let next = warps.get(i + 1).map_or(placed, |(_, at)| *at); + let m = next * at.inverse(); + if !m.is_finite() { + return None; + } + steps.push((f.clone(), m)); + } + Some(Box::new(move |p| steps.iter().fold(p, |q, (f, m)| *m * f(q)))) +} + +/// How many paths [`for_each_leaf`] visits in `n`. +fn leaf_count(n: &Node) -> usize { + match &n.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => 1, + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().map(|c| leaf_count(c)).sum(), + _ => 0, + } +} + /// An object that a Transform effect places through its transform rather than reshapes: an image /// (pixel space to document) or a symbol instance (the symbol's art to document). fn is_placed(n: &Node) -> bool { diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 43b339ccf4..c73d76e2c8 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -1,4 +1,5 @@ -//! Revolve as live, shaded vector art, shared by the canvas and every exporter. +//! Revolve and Revolve (Classic) as live, shaded vector art, shared by the canvas and every +//! exporter. use std::sync::Arc; use serde_json::Value; @@ -13,6 +14,14 @@ use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; pub const REVOLVE: &str = "threeD.revolve"; +mod classic; +pub use classic::CLASSIC_REVOLVE; + +/// Is `id` Revolve or Revolve (Classic), the effects this module draws? +pub fn is_revolve(id: &str) -> bool { + id == REVOLVE || id == CLASSIC_REVOLVE +} + /// Most bytes the copies of the object's paint in the faces may take together. Each face and the /// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of /// thousands of faces took gigabytes; past this the source path is drawn. @@ -55,7 +64,7 @@ pub(crate) fn paint_copies_add(used: &mut usize, copies: usize, paint: &Paint) - } fn visible(fx: &[Effect]) -> bool { - fx.iter().any(|e| e.visible && e.id == REVOLVE) + fx.iter().any(|e| e.visible && is_revolve(&e.id)) } pub fn has_revolve(n: &Node) -> bool { @@ -88,6 +97,17 @@ pub fn revolve_options(p: &Value) -> Revolve { } } +/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with +/// parameters `p` sweeps its surface with. +fn options_of(id: &str, p: &Value) -> Revolve { + if id == CLASSIC_REVOLVE { classic::options(p) } else { revolve_options(p) } +} + +/// The options effect `fx`, a Revolve or a Revolve (Classic), sweeps its surface with. +fn fx_options(fx: &Effect) -> Revolve { + options_of(&fx.id, &merged_params(&fx.id, &fx.params)) +} + /// Validate before a command mutates the document. Loading external files is still bounded /// by the evaluator; unsupported source kinds remain unchanged when rendered. pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { @@ -97,11 +117,16 @@ pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { /// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group /// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now. pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> { - validate_revolve_params(p)?; + validate_in(doc, n, REVOLVE, p) +} + +/// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`. +pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_params_of(id, p)?; let n = &*resolve_for(doc, n, "Revolve", false)?; let effects = &n.appearance.effects; // The profile is measured before the object's one Revolve, hidden or shown. - let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects); + let before = effects.iter().position(|e| is_revolve(&e.id)).and_then(|i| effects.get(..i)).unwrap_or(effects); if is_container(n) { const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors"; let mut shapes = members(n, "Revolve")?; @@ -110,9 +135,11 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul } reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or(EMPTY)?; - let options = shared_options(&shapes, revolve_options(p))?; + let options = shared_options(&shapes, options_of(id, p))?; let mut copies = 0; - return shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies)); + shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?; + let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0)); + return check_shadow(p, casting.map(|s| &s.path), b, options); } let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -121,18 +148,36 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul let path = geometry(&path, before, &GeomContext::of(n)); let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let paints = solid_paints(n); - check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0) + check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?; + check_shadow(p, [&path], b, options_of(id, p)) +} + +/// With the shadow of Revolve parameters `p` on, an error when the surfaces of `paths` it is cast +/// from, about the axis of `b`, are past the limits together. +fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, options: Revolve) -> Result<(), String> { + if crate::solids::shadow::options(p).is_none() { + return Ok(()); + } + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ())) } /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of -/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve, -/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level -/// Revolve draws in place of those surfaces. +/// appearance item `target` of `n` ([`validate_item_of`]). +#[cfg(test)] pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { + validate_item_of(n, REVOLVE, p, target, index) +} + +/// [`validate_revolve`] for a Revolve or Revolve (Classic), `id`, with parameters `p` at index +/// `index` of the effects of appearance item `target` of `n`. The surfaces of every fill and stroke +/// that carries one, `target`'s included, share one budget of paint copies, as in [`art`]. A visible +/// object-level Revolve draws in place of those surfaces. +pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> { if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() { - return validate_revolve(n, p); + return validate_in(None, n, id, p); } - validate_revolve_params(p)?; + validate_params_of(id, p)?; const EMPTY: &str = "Revolve requires a shape with at least two anchors"; let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -143,15 +188,17 @@ pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: u let mut copies = 0; for (i, item) in n.appearance.items.iter().enumerate() { let effects = item.effects(); - let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) }; - let options = match at.and_then(|at| effects.get(at)) { - _ if i == target => revolve_options(p), - Some(fx) if crate::paints(item) => revolve_options(&merged_params(REVOLVE, &fx.params)), + let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && is_revolve(&e.id)) }; + let (kind, params) = match at.and_then(|at| effects.get(at)) { + _ if i == target => (id, p.clone()), + Some(fx) if crate::paints(item) => (fx.id.as_str(), merged_params(&fx.id, &fx.params)), _ => continue, }; + let options = options_of(kind, ¶ms); let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); let b = path.bounds().ok_or(EMPTY)?; check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + check_shadow(¶ms, [&path], b, options)?; } Ok(()) } @@ -189,9 +236,10 @@ fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> { items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last()) } -/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`. +/// Check Revolve's parameter values `p` alone: its lights, shadow, `edge` and `cap`. pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { crate::lighting::validate(p)?; + crate::solids::shadow::validate(p)?; if p.get("edge").is_some_and(|v| v.as_str() != Some("left") && v.as_str() != Some("right")) { return Err("Revolve edge must be left or right".into()); } @@ -201,12 +249,60 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { Ok(()) } +/// [`validate_revolve_params`] for Revolve or Revolve (Classic), `id`; Revolve (Classic) also takes +/// only its own parameters, each in its range. +pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> { + validate_revolve_params(p)?; + if id == CLASSIC_REVOLVE { + classic::validate(p)?; + } + Ok(()) +} + fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { apply_geometry_with(fx, path, path.bounds().unwrap_or(Rect::ZERO), ctx) } +/// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of +/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with +/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when +/// the surface it is cast from is past the limits. +fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> { + let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) }; + let (_, opacity, blend) = paint_of(item); + if opacity <= 0.0 { + return Ok(None); + } + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?; + Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend })) +} + +/// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one, +/// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque, +/// in its paint's blending mode, and its opacity mask and blending mode apply to that part +/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the +/// limits. +fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> { + let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) }; + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let mut cast = vec![]; + for s in shapes { + let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue }; + // A member whose surface is fully transparent casts nothing. + let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; + if ink.opacity <= 0.0 { + continue; + } + let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?; + cast.push((s.scopes.as_slice(), ink, faces)); + } + Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) +} + /// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts -/// the bytes of the paint copies of every surface of the object. +/// the bytes of the paint copies of every surface of the object. Revolve (Classic) draws every face +/// with its classic surface, as Extrude & Bevel (Classic) does. #[allow(clippy::too_many_arguments)] fn surface( n: &Node, @@ -222,6 +318,16 @@ fn surface( ) -> Option<(Vec<f64>, Node)> { // A loaded file or a profile edited past the limits keeps drawing its source path instead // of crashing the frame. Commands validate the same evaluator and report its errors. + if fx.id == CLASSIC_REVOLVE { + let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?; + *copies = copies.saturating_add(paint_copies(facets.len(), &paint)); + if *copies > MAX_PAINT_COPIES { + return None; + } + let depths = facets.iter().map(|f| f.depth).collect(); + let p = merged_params(&fx.id, &fx.params); + return Some((depths, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p))); + } let colored = options.light_color != [1.0; 3] || options.lights.is_some(); let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; *copies = copies.saturating_add(paint_copies(faces.len(), &paint)); @@ -318,8 +424,7 @@ fn surface( fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); - let options = revolve_options(&merged_params(REVOLVE, &fx.params)); - surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) + surface(n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) } fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint { @@ -376,10 +481,10 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> { let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); - let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) }) }; - if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let path = geometry(&path, before, &ctx); @@ -392,7 +497,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let path = geometry(&path, &n.appearance.effects, &ctx); let mut out = vec![]; for item in n.appearance.items.iter().filter(|i| crate::paints(i)) { - if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) + if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) && let Some(fx) = item.effects().get(index) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); @@ -408,13 +513,13 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate:: .appearance .effects .iter() - .position(|e| e.visible && e.id == REVOLVE) + .position(|e| e.visible && is_revolve(&e.id)) .ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?; let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let mut shapes = members(n, "Revolve")?; reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; - let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let options = shared_options(&shapes, fx_options(fx))?; let mut out = vec![]; for s in &shapes { let Some(item) = surface_item(&s.items) else { continue }; @@ -438,38 +543,53 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> { let mut children = vec![]; let mut copies = 0; let mut remaining = n.appearance.effects.clone(); - if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = n.appearance.effects.get(index)?; let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); // An object's surface uses its top visible fill, falling back to its stroke. let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - children.push(Arc::new(object_surface(n, &path, fx, item, expand, &mut copies)?)); + let surface = object_surface(n, &path, fx, item, expand, &mut copies)?; + if let Some(b) = path.bounds() + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()? + { + children.push(Arc::new(shadow)); + } + children.push(Arc::new(surface)); // Later geometry acts on the projected art as a whole through container evaluation. remaining = n .appearance .effects .iter() .enumerate() - .filter(|(i, e)| e.id != REVOLVE && (!is_geometry(&e.id) || *i > index)) + .filter(|(i, e)| !is_revolve(&e.id) && (!is_geometry(&e.id) || *i > index)) .map(|(_, e)| e.clone()) .collect(); } else { let path = geometry(&path, &n.appearance.effects, &ctx); remaining.retain(|e| !is_geometry(&e.id)); + // Every item's shadow goes behind every item's art. + let mut shadows = vec![]; for item in n.appearance.items.iter().filter(|i| crate::paints(i)) { - if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) { + if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?; - art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect(); + art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); + if let Some(b) = p.bounds() + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()? + { + shadow.appearance.effects = art.appearance.effects.clone(); + shadows.push(Arc::new(shadow)); + } children.push(Arc::new(art)); } else { children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() }))); } } + children.splice(0..0, shadows); } let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -598,12 +718,12 @@ fn overlaps(a: Rect, b: Rect) -> bool { /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. fn group_art(n: &Node, expand: bool) -> Option<Node> { - let index = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE)?; + let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); let b = union_bounds(&shapes)?; - let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?; + let options = shared_options(&shapes, fx_options(fx)).ok()?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let mut copies = 0; let mut surfaces = vec![]; @@ -622,6 +742,10 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> { return None; } let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); + // A classic surface whose gradient has transparent stops carries an opacity mask: its faces go + // in runs, as a transparent member's do, and each run carries the mask. + let masks: Vec<Option<Box<vectorcraft_doc::OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect(); + let opaque = opaque && masks.iter().all(Option::is_none); let children = if !plain { scoped(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect(), 0) } else { @@ -663,7 +787,8 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> { runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); continue; }; - if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() { + let masked = masks.get(member).is_some_and(Option::is_some); + if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked { runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); continue; } @@ -699,11 +824,17 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> { let mut group = Node::group(n.id, r.faces); group.opacity = r.opacity; group.blend = r.blend; + if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() { + group.extras_mut().mask = Some(mask); + } Some((r.scopes, Arc::new(group))) }); scoped(n.id, runs.collect(), 0) } }; + // One shadow for every member's surface, behind them all. + let mut children = children; + children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?); let remaining = n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect(); let mut art = n.clone(); diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs new file mode 100644 index 0000000000..1881381567 --- /dev/null +++ b/crates/effects/src/revolve/classic.rs @@ -0,0 +1,220 @@ +//! Revolve (Classic): the surface Revolve sweeps from a path, drawn with the classic surfaces of +//! Extrude & Bevel (Classic) (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend +//! steps and shading color. +use serde_json::Value; +use vectorcraft_three_d::Revolve; + +pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve"; + +/// The numeric parameters: (key, lowest, highest, whole numbers only). +const RANGES: [(&str, f64, f64, bool); 13] = [ + ("angle", 0.0, 360.0, false), + ("offset", 0.0, 1000.0, false), + ("rotationX", -180.0, 180.0, false), + ("rotationY", -180.0, 180.0, false), + ("rotationZ", -180.0, 180.0, false), + ("perspectiveAngle", 0.0, 160.0, false), + ("lightRotation", -180.0, 180.0, false), + ("lightHeight", 0.0, 90.0, false), + ("lightIntensity", 0.0, 100.0, false), + ("ambient", 0.0, 100.0, false), + ("highlightIntensity", 0.0, 100.0, false), + ("highlightSize", 0.0, 100.0, false), + ("blendSteps", 1.0, 256.0, true), +]; + +const FLAGS: [&str; 2] = ["cap", "lightBehind"]; + +/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge, +/// rotation and perspective, built unshaded, since the classic surfaces light its faces. +pub(crate) fn options(p: &Value) -> Revolve { + Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) } +} + +/// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares +/// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false, +/// and the surface and shading color are named. +pub(crate) fn validate(p: &Value) -> Result<(), String> { + crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::color::{Color, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId}; + use vectorcraft_geom::{BezPath, PathData}; + + use super::*; + + const BLUE: Color = Color::Rgb { r: 0.2, g: 0.4, b: 0.8 }; + + /// Half a vase's profile, open, filled blue. + fn profile() -> Node { + let mut b = BezPath::new(); + b.move_to((100.0, 40.0)); + b.line_to((130.0, 60.0)); + b.line_to((130.0, 140.0)); + b.line_to((100.0, 160.0)); + Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0)) + } + + fn revolved(params: Value) -> Node { + let mut n = profile(); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, ¶ms).unwrap()); + crate::revolve_art(&n).unwrap() + } + + /// The faces of the surface of `art`, back to front. + fn faces(art: &Node) -> Vec<&Node> { + art.children().unwrap().iter().flat_map(|s| s.children().unwrap().iter().map(|f| &**f)).collect() + } + + fn fill(face: &Node) -> Option<Color> { + face.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color(), + AppearanceItem::Stroke(_) => None, + }) + } + + fn facets(params: &Value) -> usize { + let n = profile(); + let path = n.path_data().unwrap(); + let p = crate::merged_params(CLASSIC_REVOLVE, params); + vectorcraft_three_d::revolve_facets(path, path.bounds().unwrap(), options(&p)).unwrap().len() + } + + #[test] + fn plastic_shades_every_face_of_the_swept_surface_in_the_fill() { + let art = revolved(json!({})); + let drawn = faces(&art); + assert_eq!(drawn.len(), facets(&json!({})), "one face for each facet of the surface"); + let colors: Vec<[f32; 3]> = drawn.iter().map(|f| fill(f).unwrap().to_rgb()).collect(); + // Lit from one side, the faces take more than one tone, and none is another hue: a face is + // the blue darkened toward black, lightened toward white, or both. + let distinct = colors.iter().filter(|c| colors.iter().any(|d| (c[0] - d[0]).abs() > 0.02)).count(); + assert!(distinct > 0, "{colors:?}"); + // Diffuse has no highlight, so every face is the blue darkened toward black. + let art = revolved(json!({"surface": "diffuse"})); + for face in faces(&art) { + let [r, g, b] = fill(face).unwrap().to_rgb(); + assert!(b <= 0.8 + 1e-6 && (g * 2.0 - b).abs() < 1e-4 && (r * 4.0 - b).abs() < 1e-4, "{r} {g} {b}"); + } + } + + #[test] + fn wireframe_strokes_the_edges_of_every_face_and_no_shading_keeps_the_paint() { + let art = revolved(json!({"surface": "wireframe"})); + let faces_drawn = faces(&art); + assert_eq!(faces_drawn.len(), facets(&json!({"surface": "wireframe"}))); + for face in faces_drawn { + match face.appearance.items.as_slice() { + [AppearanceItem::Stroke(s)] => assert_eq!((s.paint.color(), s.width), (Some(BLUE), 0.5)), + items => panic!("a wireframe face is one stroke: {items:?}"), + } + } + for face in faces(&revolved(json!({"surface": "none"}))) { + assert_eq!(fill(face), Some(BLUE)); + } + } + + #[test] + fn angle_offset_edge_and_cap_shape_the_surface() { + let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); + // Seen from the front, the full turn is twice the profile's width across, about its left edge. + assert!((full.width() - 60.0).abs() < 2.0, "{full:?}"); + let ring = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "offset": 20})).visual_bounds().unwrap(); + assert!((ring.width() - 100.0).abs() < 2.0, "{ring:?}"); + // About its right edge the axis is at x 130, so the surface reaches x 160. + let right = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "edge": "right"})).visual_bounds().unwrap(); + assert!((right.x1 - 160.0).abs() < 2.0, "{right:?}"); + assert!(facets(&json!({"angle": 90})) < facets(&json!({}))); + // The profile's ends lie on the axis, so they close nothing until an offset moves them off it. + assert!(facets(&json!({"cap": false, "offset": 10})) < facets(&json!({"offset": 10})), "hollow leaves out the end caps"); + } + + #[test] + fn a_group_revolves_its_members_about_one_shared_axis() { + let mut b = BezPath::new(); + b.move_to((150.0, 60.0)); + b.line_to((170.0, 60.0)); + b.line_to((170.0, 140.0)); + let outer = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let mut g = Node::group(NodeId(3), vec![std::sync::Arc::new(profile()), std::sync::Arc::new(outer)]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).unwrap()); + let art = crate::revolve_art(&g).unwrap(); + // The axis is at the left edge of both members together, x 100, so the outer one reaches 70 + // out on either side of it. + let bounds = art.visual_bounds().unwrap(); + assert!((bounds.x0 - 30.0).abs() < 2.0 && (bounds.x1 - 170.0).abs() < 2.0, "{bounds:?}"); + let mut colors = vec![]; + art.walk(&mut |n| colors.extend(fill(n).map(|c| c.to_rgb()))); + assert!(colors.iter().any(|c| c[2] > c[0]) && colors.iter().any(|c| c[0] == c[2]), "both members' paints are drawn"); + } + + /// A group member in a gradient with transparent stops keeps the shared back-to-front order of + /// every member's faces: its faces go in runs that carry its opacity mask, and the other + /// member's faces are drawn between them where they are in front of some and behind others. + #[test] + fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let art = |end_opacity: f32| { + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = end_opacity; + let gradient = + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, BLUE), end])))); + let mut b = BezPath::new(); + b.move_to((150.0, 60.0)); + b.line_to((170.0, 60.0)); + b.line_to((170.0, 140.0)); + let outer = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(gradient, Paint::None, 0.0)); + let mut g = Node::group(NodeId(3), vec![std::sync::Arc::new(outer), std::sync::Arc::new(profile())]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap()); + crate::revolve_art(&g).unwrap() + }; + // The drawing order: `M` for a group with an opacity mask, `F` for a face outside one. + fn visit(n: &Node, order: &mut String) { + if n.extras().mask.is_some() { + order.push('M'); + return; + } + if n.path_data().is_some() { + order.push('F'); + } + for c in n.children().into_iter().flatten() { + visit(c, order); + } + } + let order = |art: &Node| { + let mut order = String::new(); + visit(art, &mut order); + order + }; + assert!(!order(&art(1.0)).contains('M'), "an opaque gradient needs no mask"); + let masked = order(&art(0.5)); + let (first, last) = (masked.find('M').unwrap(), masked.rfind('M').unwrap()); + assert!(masked.get(first..last).is_some_and(|between| between.contains('F')), "faces between the member's runs: {masked}"); + } + + #[test] + fn bad_parameters_are_refused() { + let check = |p: Value| crate::validate_three_d(&profile(), CLASSIC_REVOLVE, &crate::merged_params(CLASSIC_REVOLVE, &p)); + assert_eq!(check(json!({})), Ok(())); + for (p, error) in [ + (json!({"segments": 32}), "unknown parameter `segments`"), + (json!({"angle": 400}), "`angle` must be between 0 and 360"), + (json!({"offset": 1001}), "`offset` must be between 0 and 1000"), + (json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"), + (json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"), + (json!({"lightBehind": 1}), "`lightBehind` must be true or false"), + (json!({"surface": "glossy"}), "`surface` must be one of"), + (json!({"shadingColor": "white"}), "`shadingColor` must be one of"), + (json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"), + (json!({"edge": "middle"}), "Revolve edge must be left or right"), + (json!({"cap": "yes"}), "Revolve cap must be a boolean"), + ] { + let e = check(p.clone()).unwrap_err(); + assert!(e.contains(error), "{p}: {e}"); + } + } +} diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 95ef265cc9..8d9ff9eea8 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1,4 +1,4 @@ -//! Extrude & Bevel, Inflate, Rotate and Extrude & Bevel (Classic) as live, shaded vector art, +//! Extrude & Bevel, Inflate, Rotate, Extrude & Bevel (Classic) and Rotate (Classic) as live, shaded vector art, //! shared by the canvas and every exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces. use std::sync::Arc; @@ -14,21 +14,34 @@ use vectorcraft_doc::color::Color; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry}; -mod classic; -pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading}; +pub(crate) mod classic; +pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLORS, classic_extrude_options, classic_shading}; mod source; pub(crate) use source::{resolve, resolve_for}; +pub(crate) mod shadow; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; /// The 3D effects this module draws (Revolve has its own). -pub const SOLIDS: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE]; +pub const SOLIDS: [&str; 5] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE, CLASSIC_ROTATE]; -/// Is `id` one of the 3D and Materials effects (Revolve included)? +/// Is `id` one of the 3D and Materials effects (Revolve and Revolve (Classic) included)? pub fn is_three_d(id: &str) -> bool { - id == crate::REVOLVE || SOLIDS.contains(&id) + crate::revolve::is_revolve(id) || SOLIDS.contains(&id) +} + +/// Is `id` one of the 3D (Classic) effects: Extrude & Bevel (Classic), Revolve (Classic) or Rotate +/// (Classic)? +pub fn is_classic_three_d(id: &str) -> bool { + id == CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE || id == CLASSIC_ROTATE +} + +/// Does 3D effect `id` turn the art as a flat plane: Rotate or Rotate (Classic)? +fn is_plane(id: &str) -> bool { + id == ROTATE || id == CLASSIC_ROTATE } /// The 3D and Materials panel's object types and the effect that draws each: (type, effect id). @@ -191,7 +204,11 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { if id == CLASSIC_EXTRUDE { classic::validate(p)?; } + if id == CLASSIC_ROTATE { + classic::validate_rotate(p)?; + } crate::lighting::validate(p)?; + shadow::validate(p)?; if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some()) { @@ -214,17 +231,31 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group /// build from the art they show ([`resolve`]). pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_solid_for(doc, n, id, p, None) +} + +/// [`validate_solid_in`] for the effect on the object (`item` `None`) or on its appearance item +/// `item`, whose shadow is cast by that item's solid alone. +fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option<usize>) -> Result<(), String> { validate_solid_params(id, p)?; let label = label_of(id); - let n = &*source::resolve_for(doc, n, label, id == ROTATE)?; + let n = &*source::resolve_for(doc, n, label, is_plane(id))?; if is_container(n) { let shapes = members(n, label)?; let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; - return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())); + shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))?; + return cast_shadow(id, p, &shapes).map(|_| ()); } let (path, rule) = object_profile(n, label)?; let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; - facets(id, &path, rule, b, p).map(|_| ()) + facets(id, &path, rule, b, p)?; + // With its shadow on, the shadow of the object's solids (or of the item's) must fit too. + let items = match item.and_then(|i| n.appearance.items.get(i)) { + Some(item) => vec![item.clone()], + None => solid_paints(n), + }; + let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; + cast_shadow(id, p, &shapes).map(|_| ()) } /// [`profile`], or the error a command reports for object `n`: type with no outlines to build from @@ -297,7 +328,7 @@ fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> { } /// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal? -fn has_masks(shapes: &[Profile]) -> bool { +pub(crate) fn has_masks(shapes: &[Profile]) -> bool { shapes.iter().any(|s| s.scopes.iter().any(composites)) } @@ -348,7 +379,7 @@ pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> { fn walk(n: &Node, opacity: f32, scopes: &[Scope], w: &mut Walk) -> Result<(), String> { let label = w.label; for c in n.children().into_iter().flatten() { - if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + if !c.visible || c.is_guide() { continue; } let opacity = opacity * c.opacity; @@ -400,7 +431,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]). pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { - if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) } + if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) } } /// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of @@ -419,8 +450,9 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va Some(_) if is_container(n) || source::resolves(n) => { Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) } - Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index), - _ => validate_three_d_in(doc, n, id, p), + Some((item, index)) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(n, id, p, item, index), + Some((item, _)) => validate_solid_for(doc, n, id, p, Some(item)), + None => validate_three_d_in(doc, n, id, p), } } @@ -428,7 +460,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va /// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does /// not need to fit. pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { - if id == crate::REVOLVE { crate::revolve::validate_revolve_params(p) } else { validate_solid_params(id, p) } + if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) } } /// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and @@ -516,8 +548,8 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, } /// One part of [`solid_parts`]: a fill or stroke, its shape's opacity, the region it paints and its -/// fill rule, and its shape's scopes. -type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope]); +/// fill rule, its shape's scopes and the index of its shape. +type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize); /// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes, /// a group's members from the back up, each with its shape's opacity, the region it paints and its @@ -526,18 +558,128 @@ type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope]); fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) { let parts: Vec<Part> = shapes .iter() - .flat_map(|s| { + .enumerate() + .flat_map(|(member, s)| { let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); - s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| { + s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| { let (area, rule) = region(&s.path, s.rule, i); - (i, s.opacity, area, rule, s.scopes.as_slice()) + (i, s.opacity, area, rule, s.scopes.as_slice(), member) }) }) .collect(); - let bounds = parts.iter().filter_map(|(_, _, area, _, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback); + let bounds = parts.iter().filter_map(|(_, _, area, _, _, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback); (parts, bounds) } +/// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's +/// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of +/// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its +/// strokes that covers the fill's whole edge. +struct Placed { + depth: f64, + side: bool, + away: bool, + bounds: Rect, + member: usize, + paints: Paints, +} + +/// The part of its shape a face's solid is built from ([`Placed`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Paints { + Fill, + /// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without + /// dashes, a width profile or a brush, painted with a solid color or a gradient without + /// transparent stops, on a shape whose subpaths are all closed. + Stroke, + Other, +} + +impl Paints { + /// What `item` of a shape is, the shape's subpaths all closed when `closed`. + fn of(item: &AppearanceItem, closed: bool) -> Self { + match item { + AppearanceItem::Fill(_) => Paints::Fill, + AppearanceItem::Stroke(s) + if closed + && s.width > 0.0 + && s.width.is_finite() + && s.dash.is_none() + && s.profile.is_none() + && s.brush.is_none() + && match &s.paint { + Paint::Solid { .. } => true, + Paint::Gradient(_) => crate::lighting::opaque_paint(&s.paint).1.is_none(), + _ => false, + } => + { + Paints::Stroke + } + AppearanceItem::Stroke(_) => Paints::Other, + } + } +} + +impl Placed { + /// The face of `f`, of shape `member`'s part `paints`. + fn of(f: &Facet, member: usize, paints: Paints) -> Self { + let mut points = f.contours.iter().flatten(); + let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q))); + Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints } + } +} + +/// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep +/// their depths. +const MAX_OVERLAP_CHECKS: usize = 4_000_000; + +/// The order faces `faces` are drawn in, back to front, as indices into `faces`: by depth (faces +/// at the same depth in the order given), except that with `sealed` (solids with caps) a side face +/// of a shape's fill turned toward the viewer is drawn before each face of the same shape's +/// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own. +/// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under +/// any other face. +fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> { + // Each face's depth to sort by, and whether it was moved before a stroke face at that depth. + let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect(); + if sealed { + // The stroke faces turned toward the viewer of each shape, nearest last. + let mut strokes: Vec<Vec<&Placed>> = vec![]; + for f in faces.iter().filter(|f| f.paints == Paints::Stroke && !f.away) { + if strokes.len() <= f.member { + strokes.resize_with(f.member + 1, Vec::new); + } + strokes[f.member].push(f); + } + for list in &mut strokes { + list.sort_by(|a, b| a.depth.total_cmp(&b.depth)); + } + let overlap = |a: &Rect, b: &Rect| a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + let mut checks = 0usize; + for (f, key) in faces.iter().zip(&mut keys) { + if f.paints != Paints::Fill || !f.side || f.away { + continue; + } + let Some(list) = strokes.get(f.member).filter(|l| !l.is_empty()) else { continue }; + for s in list.iter().take_while(|s| s.depth <= f.depth) { + if checks >= MAX_OVERLAP_CHECKS { + break; + } + checks += 1; + if overlap(&s.bounds, &f.bounds) { + *key = (s.depth, true); + break; + } + } + } + } + let mut order: Vec<usize> = (0..faces.len()).collect(); + // A stable sort: faces at the same depth keep the order of the appearance, and a fill's side + // face moved to a stroke face's depth goes before it. + order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1))); + order +} + /// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before` /// its 3D effect, about the bounds of all of them. pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { @@ -551,24 +693,108 @@ pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile } } +/// A 3D effect's shadow and its surfaces ([`art_for`]). +type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>); + /// The 3D art of one effect `fx` on `path` (already through the effects before it). /// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a /// solid from the path for the top visible fill and one from the outline of each visible stroke, /// each in its own paint. When every one is opaque with normal blending and no colored light makes /// a surface one composite or masks it, their faces are drawn in one back-to-front order (where -/// depths tie, as for the caps turned toward the viewer, in the order of the appearance); +/// depths tie, as for the caps turned toward the viewer, in the order of the appearance, and with +/// caps, a shape's fill walls before the faces of its covering strokes that overlap them: +/// [`draw_order`]); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds -/// ([`masked`]). -fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> { +/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it +/// off), to be drawn behind every surface of the object, and the surfaces. +fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> { + let art = surfaces_for(n, fx, shapes)?; + // A shadow past the limits draws the source path, as a solid past them does; commands report + // the error ([`validate_solid_in`]). + let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? { + Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)), + None => vec![], + }; + Some((shadow, art)) +} + +/// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on +/// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the +/// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow +/// off, for Extrude & Bevel (Classic) and Rotate (Classic) or with no shapes. A stroke's solid that is not built (past +/// the limits) casts nothing, as it draws nothing; any other solid that is not built is an error. +/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to +/// the part of the shadow they cast too ([`shadow::scoped_art`]). +fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> { + if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { + return Ok(None); + } + let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let view = view_options(p); + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + // The faces each solid of visible art added, with its member's scopes and its ink (opacity + // and blending mode), in order. A fully transparent fill or stroke (or member) casts nothing + // and does not place the plane. + let mut cast: Vec<shadow::Cast> = vec![]; + let ink = |item: &AppearanceItem, member: f32| { + let (_, opacity, blend) = paint_of(item, member); + shadow::Ink { opacity, blend } + }; + if id == ROTATE { + for s in shapes { + for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) { + let (area, rule) = region(&s.path, s.rule, item); + let faces = caster.plane(&area, rule, b, view)?; + cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces)); + } + } + } else { + let (parts, bounds) = solid_parts(shapes, b); + let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect(); + // Inflate's eye is placed for every shape together, as the solids are. + let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE { + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); + let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect(); + caster.inflate(&shapes, &casts, bounds, inflate_options(p), view) + } else { + let mut added = vec![]; + for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) { + added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); + } + added + }; + for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) { + if ink.opacity <= 0.0 { + continue; + } + // A stroke whose own solid is past the limits is left out; past the shadow's limit for + // all the solids together, the shadow is refused. + let faces = match faces { + Ok(faces) => faces, + Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue, + Err(e) => return Err(e), + }; + cast.push((*scopes, ink, faces)); + } + } + Ok(Some((caster, settings, cast))) +} + +/// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with +/// its member's scopes and ink ([`cast_shadow`]). +type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>); + +/// [`art_for`] without the shadow: the solids' surfaces. +fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); - let classic = fx.id == CLASSIC_EXTRUDE; + let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; let colored = !classic && view_options(&p).has_colored_lights(); let masks = has_masks(shapes); // The paint copies of every solid together: past the allowance the source path is drawn. let mut paint_bytes = 0usize; - if fx.id == ROTATE { + if is_plane(&fx.id) { // Every part turns about the centre of the object's own bounds (a group's members about // the centre of theirs), so they stay together. let mut out = vec![]; @@ -580,7 +806,8 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) { return None; } - out.push((s.scopes.as_slice(), Arc::new(surface(n, f, &paint, opacity, blend, colored)))); + let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; + out.push((s.scopes.as_slice(), Arc::new(art))); } } return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); @@ -588,17 +815,17 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> let (parts, bounds) = solid_parts(shapes, b); let built = if fx.id == INFLATE { // One eye for every puff, as far away as the highest needs. - let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect(); + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p)) } else { - parts.iter().map(|(_, _, area, rule, _)| facets(&fx.id, area, *rule, bounds, &p)).collect() + parts.iter().map(|(_, _, area, rule, _, _)| facets(&fx.id, area, *rule, bounds, &p)).collect() }; let mut solids = vec![]; - for ((item, opacity, _, _, scopes), f) in parts.iter().zip(built) { + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built) { let item: &AppearanceItem = item; match f { Ok(f) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => return None, - Ok(f) => solids.push((item, *opacity, *scopes, f)), + Ok(f) => solids.push((item, *opacity, *scopes, f, *member)), // A stroke's outline past the limits is left out; the fill's solid still draws. Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} // A loaded file or a shape edited past the limits keeps drawing its source path @@ -610,14 +837,16 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> if solids.is_empty() { return None; } - let opaque = solids.iter().all(|(item, member, _, _)| { + let opaque = solids.iter().all(|(item, member, _, _, _)| { let (_, opacity, blend) = paint_of(item, *member); opacity >= 1.0 && blend == BlendMode::Normal }); - let surfaces: Vec<(Vec<f64>, Node, &[Scope])> = solids + let surfaces: Vec<(Vec<Placed>, Node, &[Scope])> = solids .into_iter() - .map(|(item, member, scopes, f)| { - let depths: Vec<f64> = f.iter().map(|f| f.depth).collect(); + .map(|(item, member, scopes, f, shape)| { + let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed)); + let paints = Paints::of(item, closed); + let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let (paint, opacity, blend) = paint_of(item, member); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; (depths, art, scopes) @@ -635,15 +864,20 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> if !opaque || !plain { return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect()); } - let mut faces = vec![]; + let (mut placed, mut faces) = (vec![], vec![]); for (depths, s, _) in surfaces { if let NodeKind::Group { children, .. } = s.kind { - faces.extend(depths.into_iter().zip(children)); + placed.extend(depths); + faces.extend(children.into_iter().map(Some)); } } - // A stable sort: faces at the same depth keep the order of the appearance. - faces.sort_by(|a, b| a.0.total_cmp(&b.0)); - Some(vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(_, face)| face).collect()))]) + let sealed = match fx.id.as_str() { + INFLATE => inflate_options(&p).cap, + CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, + _ => extrude_options(&p).cap, + }; + let order = draw_order(&placed, sealed); + Some(vec![Arc::new(Node::group(n.id, order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect()))]) } fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { @@ -676,7 +910,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> { let remaining: Vec<Effect>; if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?); + let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; + children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = n .appearance @@ -689,18 +924,24 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> { } else { let path = geometry(&path, &n.appearance.effects, &ctx); remaining = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect(); + // Every item's shadow goes behind every item's art. + let mut shadows = vec![]; for item in &paints { if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); - for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])? { - Arc::make_mut(&mut art).appearance.effects = - item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); - children.push(art); - } + let (shadow, surfaces) = art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); + let with_later = |mut art: Arc<Node>| { + Arc::make_mut(&mut art).appearance.effects = later.clone(); + art + }; + shadows.extend(shadow.into_iter().map(with_later)); + children.extend(surfaces.into_iter().map(with_later)); } else { children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() }))); } } + children.splice(0..0, shadows); } let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -716,7 +957,8 @@ fn group_solid_art(n: &Node) -> Option<Node> { let (index, fx) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let children = art_for(n, fx, &shapes)?; + let (shadow, surfaces) = art_for(n, fx, &shapes)?; + let children = shadow.into_iter().chain(surfaces).collect(); let remaining = n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect(); let mut art = n.clone(); @@ -774,7 +1016,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let view = view_options(&p); let mut out = vec![]; let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit); - if fx.id == ROTATE { + if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); @@ -788,11 +1030,11 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) // Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel // solid and its mesh are built as the loop reaches them. let mut inflated = (fx.id == INFLATE).then(|| { - let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect(); + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view) }); let extrude = extrude_options(&p); - for (item, member, area, rule, _) in &parts { + for (item, member, area, rule, _, _) in &parts { let item: &AppearanceItem = item; let mesh = match inflated.as_mut() { Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())), @@ -906,3 +1148,6 @@ mod tests_mesh; #[cfg(test)] mod tests_sources; + +#[cfg(test)] +mod tests_shadow; diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 730fb8e53b..919de831ce 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -1,6 +1,6 @@ //! Extrude & Bevel (Classic): the solid Extrude & Bevel builds from a path, drawn with the classic //! surfaces (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend steps and shading -//! color. +//! color. Rotate (Classic): the plane Rotate turns, drawn with the No Shading and Diffuse surfaces. use std::sync::Arc; use serde_json::Value; @@ -12,6 +12,10 @@ use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Ext use crate::util::{flag, num, text}; pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude"; +pub const CLASSIC_ROTATE: &str = "threeD.classicRotate"; + +/// The surfaces Rotate (Classic) takes: No Shading and Diffuse. +pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; @@ -104,8 +108,39 @@ const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces" /// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and /// `shadingCustom` name a surface, a shading color and a #rrggbb color. pub fn validate(p: &Value) -> Result<(), String> { + validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS) +} + +/// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only). +const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [ + ("rotationX", -180.0, 180.0, false), + ("rotationY", -180.0, 180.0, false), + ("rotationZ", -180.0, 180.0, false), + ("perspectiveAngle", 0.0, 160.0, false), + ("lightRotation", -180.0, 180.0, false), + ("lightHeight", 0.0, 90.0, false), + ("lightIntensity", 0.0, 100.0, false), + ("ambient", 0.0, 100.0, false), + ("blendSteps", 1.0, 256.0, true), +]; + +/// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude & +/// Bevel (Classic)'s, with `surface` No Shading or Diffuse only. +pub fn validate_rotate(p: &Value) -> Result<(), String> { + validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?; + if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) { + return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", "))); + } + Ok(()) +} + +/// Check the parameters `p` of classic 3D effect `id` (its defaults filled in): every key is one of +/// its parameters, the numbers `ranges` lists, as (key, lowest, highest, whole numbers only), are in +/// range, the `flags` are true or false, and `surface`, `shadingColor` and `shadingCustom` name a +/// surface, a shading color and a #rrggbb color. +pub(crate) fn validate_classic(id: &str, p: &Value, ranges: &[(&str, f64, f64, bool)], flags: &[&str]) -> Result<(), String> { let Some(map) = p.as_object() else { return Ok(()) }; - let defaults = crate::default_params(CLASSIC_EXTRUDE).unwrap_or(Value::Null); + let defaults = crate::default_params(id).unwrap_or(Value::Null); let known: Vec<&str> = defaults.as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default(); for key in map.keys() { if !known.contains(&key.as_str()) { @@ -113,7 +148,7 @@ pub fn validate(p: &Value) -> Result<(), String> { return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); } } - for (key, min, max, whole) in RANGES { + for &(key, min, max, whole) in ranges { let Some(v) = map.get(key) else { continue }; let Some(x) = v.as_f64() else { return Err(format!("`{key}` must be a number")) }; if whole && (x.fract() != 0.0 || !(min..=max).contains(&x)) { @@ -123,7 +158,7 @@ pub fn validate(p: &Value) -> Result<(), String> { return Err(format!("`{key}` must be between {min} and {max} (got {x})")); } } - for key in FLAGS { + for &key in flags { if map.get(key).is_some_and(|v| !v.is_boolean()) { return Err(format!("`{key}` must be true or false")); } @@ -161,7 +196,7 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color { /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by /// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by /// its own transparency, so the shading follows the gradient's coverage. -pub(super) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { +pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); diff --git a/crates/effects/src/solids/shadow.rs b/crates/effects/src/solids/shadow.rs new file mode 100644 index 0000000000..3906ac2d3c --- /dev/null +++ b/crates/effects/src/solids/shadow.rs @@ -0,0 +1,101 @@ +//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the +//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it +//! draws behind the solids. +use std::ops::Range; +use std::sync::Arc; + +use serde_json::Value; +use vectorcraft_doc::color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId}; +use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition}; + +use super::Scope; +use crate::util::{flag, num, text}; + +/// The shadow's paint: black at this opacity. VectorCraft's own values. +const SHADOW_OPACITY: f32 = 0.5; + +/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing +/// (Shading is off or its intensity is 0), so that no shadow is built. +pub(crate) fn options(p: &Value) -> Option<Shadow> { + let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0)); + let lit = flag(p, "shade", true) && intensity > 0.0; + (lit && flag(p, "shadow", false)).then(|| Shadow { + position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(), + distance: num(p, "shadowDistance", 0.0) / 100.0, + bounds: num(p, "shadowBounds", 100.0) / 100.0, + }) +} + +/// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind. +pub(crate) fn validate(p: &Value) -> Result<(), String> { + if p.get("shadow").is_some_and(|v| !v.is_boolean()) { + return Err("shadow must be true or false".into()); + } + if p.get("shadowPosition").is_some_and(|v| v.as_str().and_then(ShadowPosition::parse).is_none()) { + return Err("shadowPosition must be behind or below".into()); + } + for (key, min, max) in [("shadowDistance", 0.0, 100.0), ("shadowBounds", 10.0, 400.0)] { + if p.get(key).is_some_and(|v| !v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n))) { + return Err(format!("{key} must be a number from {min} to {max}")); + } + } + Ok(()) +} + +/// The opacity and blending mode of the fill or stroke (and member) that casts part of a shadow. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Ink { + pub(crate) opacity: f32, + pub(crate) blend: BlendMode, +} + +/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled +/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule; +/// `None` when it casts nothing. +pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> { + let all = 0..caster.len(); + let all = std::slice::from_ref(&all); + piece(id, caster, &caster.shadow_plane(shadow, all)?, all, ink) +} + +/// [`art`] of the faces in the ranges `faces` of `caster` only, on `plane`. +fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<usize>], ink: Ink) -> Option<Node> { + let path = caster.path_on(plane, faces)?; + let mut fill = FillLayer::new(Paint::solid(Color::BLACK)); + fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0); + fill.blend = ink.blend; + Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() })) +} + +/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies). +fn same_scopes(a: &[Scope], b: &[Scope]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.key == b.key) +} + +/// The faces one solid added to a caster, with the scopes of its member and the ink of its art. +pub(crate) type Cast<'a> = (&'a [Scope], Ink, Range<usize>); + +/// The faces of the solids that cast one piece of a shadow, with their scopes and ink. +type Run<'a> = (&'a [Scope], Ink, Vec<Range<usize>>); + +/// The shadow `cast` casts on one plane: the faces of `caster` that the solids of visible art +/// added, each range with the scopes of the member that cast it and the ink of the art, in order. +/// Each run of solids in the same ink casts a piece in that ink ([`art`]); with `masks` (a member's +/// opacity mask or blending mode applies to its solids) the solids of a run also share their scopes, +/// and each piece is drawn in their opacity masks and blending modes ([`super::masked`]). +pub(crate) fn scoped_art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, cast: Vec<Cast<'_>>, masks: bool) -> Vec<Arc<Node>> { + let placing: Vec<Range<usize>> = cast.iter().map(|(.., faces)| faces.clone()).collect(); + let Some(plane) = caster.shadow_plane(shadow, &placing) else { return vec![] }; + // Consecutive solids in the same ink (and with masks, the same scopes) share a piece; the pieces + // keep the solids' order. + let mut runs: Vec<Run> = vec![]; + for (scopes, ink, faces) in cast { + match runs.last_mut() { + Some(run) if run.1 == ink && (!masks || same_scopes(run.0, scopes)) => run.2.push(faces), + _ => runs.push((scopes, ink, vec![faces])), + } + } + let pieces = runs.into_iter().filter_map(|(scopes, ink, faces)| Some((scopes, Arc::new(piece(id, caster, &plane, &faces, ink)?)))); + if masks { super::masked(id, pieces.collect()) } else { pieces.map(|(_, piece)| piece).collect() } +} diff --git a/crates/effects/src/solids/source.rs b/crates/effects/src/solids/source.rs index ad9495cf08..585f23bd6b 100644 --- a/crates/effects/src/solids/source.rs +++ b/crates/effects/src/solids/source.rs @@ -55,7 +55,7 @@ fn needs(n: &Node) -> bool { /// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut /// for the solid effect `n` carries ([`resolve_for`]). pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result<Cow<'a, Node>, String> { - let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE); + let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| super::is_plane(&fx.id)); resolve_for(doc, n, label, every_fill) } @@ -191,7 +191,7 @@ impl Resolver<'_> { let mut changed = false; for c in children { self.spend(1)?; - if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + if !c.visible || c.is_guide() { continue; } if matches!(c.kind, NodeKind::Image(_)) { @@ -279,7 +279,7 @@ impl Resolver<'_> { kids = nest(n, cut, 0); } else { for c in n.children().into_iter().flatten() { - if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + if !c.visible || c.is_guide() { continue; } if let Some(c) = self.clipped(c, clip, depth + 1)? { diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 7273a44b22..c960bbe671 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -180,6 +180,137 @@ fn the_front_caps_are_drawn_last_in_the_order_of_the_appearance() { } } +/// A C, open to the right: two concave corners where its walls meet the walls of the notch. +fn letter_c() -> BezPath { + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((200.0, 100.0)); + b.line_to((200.0, 130.0)); + b.line_to((130.0, 130.0)); + b.line_to((130.0, 170.0)); + b.line_to((200.0, 170.0)); + b.line_to((200.0, 200.0)); + b.line_to((100.0, 200.0)); + b.close_path(); + b +} + +/// The pairs (blue, red) of `walls`, by index, where the blue face is drawn first and the two +/// faces' bounds overlap. +fn red_after_blue(walls: &[&Node]) -> Vec<(usize, usize)> { + let bounds: Vec<Rect> = walls.iter().map(|f| f.path_data().and_then(PathData::bounds).unwrap()).collect(); + let overlap = |a: &Rect, b: &Rect| a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + let mut out = vec![]; + for (i, a) in walls.iter().enumerate() { + for (j, b) in walls.iter().enumerate().skip(i + 1) { + if blue(a) && !blue(b) && overlap(&bounds[i], &bounds[j]) { + out.push((i, j)); + } + } + } + out +} + +/// An opaque stroke's solid holds the fill's edge, so the fill's walls are drawn before every +/// face of the stroke they overlap, and the stroke's walls cover them at the concave corners of a +/// turned C, in Extrude & Bevel and Extrude & Bevel (Classic). The front caps stay last, the +/// fill's below the stroke's. +#[test] +fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() { + let views = [json!({}), json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}), json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10})]; + for id in [EXTRUDE, CLASSIC_EXTRUDE] { + for view in &views { + let mut params = view.clone(); + params["depth"] = json!(60); + let mut n = stroked(&letter_c()); + n.appearance.effects.push(fx(id, params)); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + let [walls @ .., fill_cap, stroke_cap] = faces.as_slice() else { panic!("{id} {view}: the caps") }; + assert!(!blue(fill_cap) && blue(stroke_cap), "{id} {view}: the caps last"); + assert!(walls.iter().any(|f| !blue(f)) && walls.iter().any(|f| blue(f)), "{id} {view}: walls of both"); + let wrong = red_after_blue(walls); + assert!(wrong.is_empty(), "{id} {view}: fill walls after the stroke faces over them: {wrong:?} of {}", walls.len()); + } + } + // Strokes aligned inside or outside keep the fill's walls, in that order. A dashed stroke + // leaves the fill's walls in the gaps between its dashes, and they keep their depths. + use vectorcraft_doc::StrokeAlign; + for (dash, align) in [(true, StrokeAlign::Center), (false, StrokeAlign::Inside), (false, StrokeAlign::Outside)] { + let mut n = stroked(&letter_c()); + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.dash = dash.then(|| vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + s.align = align; + } + n.appearance.effects.push(fx(EXTRUDE, views[1].clone())); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + let [walls @ .., _, _] = faces.as_slice() else { panic!("{align:?}: the caps") }; + assert!(walls.iter().any(|f| !blue(f)), "{align:?}: the fill's walls"); + if !dash { + assert!(red_after_blue(walls).is_empty(), "{align:?}"); + } + } +} + +/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a +/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A +/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an +/// effect without caps keep the order of the depths. +#[test] +fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() { + let at = |depth: f64, x: f64, member: usize, paints: Paints, side: bool, away: bool| Placed { + depth, + side, + away, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member, + paints, + }; + // 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke + // wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a + // fill wall at the stroke wall's depth. + let faces = [ + at(5.0, 0.0, 0, Paints::Fill, true, false), + at(3.0, 5.0, 0, Paints::Stroke, true, false), + at(2.0, 5.0, 1, Paints::Stroke, true, false), + at(1.0, 50.0, 0, Paints::Stroke, true, false), + at(0.0, 0.0, 0, Paints::Stroke, true, true), + at(4.0, 0.0, 0, Paints::Fill, false, false), + at(6.0, 0.0, 0, Paints::Stroke, false, false), + at(3.0, 0.0, 0, Paints::Fill, true, false), + ]; + assert_eq!(draw_order(&faces, true), [4, 3, 2, 0, 7, 1, 5, 6]); + assert_eq!(draw_order(&faces, false), [4, 3, 2, 1, 7, 5, 0, 6]); + // A shape with no stroke, and a stroke without a width, move nothing. + // Only a stroke whose solid hides the fill's whole edge counts: an opaque, plain stroke with a + // width on a closed shape. + let stroke = |f: &dyn Fn(&mut StrokeLayer)| { + let mut s = StrokeLayer::new(Paint::solid(BLUE), 6.0); + f(&mut s); + AppearanceItem::Stroke(s) + }; + assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke); + assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape"); + assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width"); + let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false }; + assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes"); + assert!(Paints::of(&stroke(&|s| s.brush = Some("brush".into())), true) == Paints::Other); + assert!(Paints::of(&stroke(&|s| s.paint = Paint::None), true) == Paints::Other); + assert!(Paints::of(&stroke(&|s| s.paint = Paint::Pattern { pattern: "p".into(), xf: Affine::IDENTITY }), true) == Paints::Other, "a pattern"); + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |opacity: f32| { + let mut end = GradientStop::new(1.0, RED); + end.opacity = opacity; + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, BLUE), end])))) + }; + assert!(Paints::of(&stroke(&|s| s.paint = gradient(1.0)), true) == Paints::Stroke, "an opaque gradient"); + assert!(Paints::of(&stroke(&|s| s.paint = gradient(0.5)), true) == Paints::Other, "a gradient with a transparent stop"); + let other = |p: Paints| if p == Paints::Stroke { Paints::Other } else { p }; + let unstroked: Vec<Placed> = faces.iter().map(|f| at(f.depth, f.bounds.x0, f.member, other(f.paints), f.side, f.away)).collect(); + assert_eq!(draw_order(&unstroked, true), draw_order(&faces, false)); +} + /// A stroked open path builds a ribbon, the stroke's outline, not the area the path would enclose /// if it were closed: for an L of two 100 pt legs, a 6 pt band with butt ends and a mitered corner. #[test] @@ -758,3 +889,80 @@ fn classic_parameters_are_checked() { assert!(err.starts_with(says), "{p}: {err}"); } } + +/// The red square, stroked black, with Rotate (Classic) and `params`: its surfaces, the fill's +/// plane first, then the stroke's outline. +fn classic_rotate(params: Value) -> Vec<Node> { + let mut n = square_node(); + n.appearance.effects.push(fx(CLASSIC_ROTATE, params)); + solid_art(&n).unwrap().children().unwrap().iter().map(|s| (**s).clone()).collect() +} + +#[test] +fn classic_rotate_turns_every_fill_and_stroke_as_one_plane() { + let front = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0}); + let surfaces = classic_rotate(front.clone()); + assert_eq!(surfaces.len(), 2, "the fill's plane and the stroke's outline"); + assert!(surfaces.iter().all(|s| s.children().unwrap().len() == 1), "each is one flat face"); + let fill = surfaces[0].visual_bounds().unwrap(); + assert!((fill.width() - 100.0).abs() < 1.0 && (fill.height() - 100.0).abs() < 1.0, "{fill:?}"); + // Turned 60° about the vertical axis, the square shows half its width and all its height, + // about the center of its bounds. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 60, "rotationZ": 0}))[0].visual_bounds().unwrap(); + assert!((turned.width() - 50.0).abs() < 1.0 && (turned.height() - 100.0).abs() < 1.0, "{turned:?}"); + assert!((turned.center().x - 150.0).abs() < 1.0, "{turned:?}"); + // Turned past 90°, the back of the plane is drawn. + let back = classic_rotate(json!({"rotationX": 0, "rotationY": 150, "rotationZ": 0})); + assert!(back[0].visual_bounds().is_some_and(|b| (b.width() - 100.0 * 30f64.to_radians().cos()).abs() < 1.0)); +} + +#[test] +fn classic_rotate_shades_with_no_shading_or_diffuse() { + let rgb = |p: Value| fill_rgb(&classic_rotate(p)[0].children().unwrap()[0]); + // No Shading keeps the paint, the color itself kept. + let mut n = square_node(); + n.appearance.effects.push(fx(CLASSIC_ROTATE, json!({"surface": "none"}))); + let art = solid_art(&n).unwrap(); + let AppearanceItem::Fill(f) = &faces(&art)[0].appearance.items[0] else { panic!("a fill first") }; + assert_eq!(f.paint, Paint::solid(RED)); + // Diffuse: straight on with the light in front, the face is fully lit; turned away from the + // light, it is the red darkened toward black. + let lit = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90}); + assert!(close3(rgb(lit), RED.to_rgb())); + let [r, g, b] = rgb(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90})); + assert!(r < 0.8 - 0.05 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4, "{r} {g} {b}"); + // No light: the ambient share of the red. A custom shading color darkens toward that color; + // None keeps the paint. + let dark = rgb(json!({"lightIntensity": 0, "ambient": 20, "blendSteps": 256})); + assert!((dark[0] - 0.8 * 0.2).abs() < 0.01, "{dark:?}"); + let blue = rgb(json!({"lightIntensity": 0, "ambient": 20, "shadingColor": "custom", "shadingCustom": "#0000ff"})); + assert!(blue[2] > blue[0] / 8.0 + 0.01, "{blue:?}"); + assert!(close3(rgb(json!({"lightIntensity": 0, "shadingColor": "none"})), RED.to_rgb())); +} + +#[test] +fn classic_rotate_parameters_are_checked() { + let n = square_node(); + let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); + assert!(check(json!({})).is_ok()); + assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + for (p, says) in [ + (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), + (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), + (json!({"surface": 2}), "`surface` must be one of"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), + (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), + (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), + (json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"), + (json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"), + (json!({"lightBehind": 1}), "`lightBehind` must be true or false"), + (json!({"highlightSize": 50}), "unknown parameter `highlightSize`"), + (json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"), + (json!({"shadow": true}), "unknown parameter `shadow`"), + (json!({"lights": []}), "lights must contain one to ten lights"), + ] { + let err = check(p.clone()).unwrap_err(); + assert!(err.starts_with(says), "{p}: {err}"); + } +} diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs new file mode 100644 index 0000000000..4400555d2b --- /dev/null +++ b/crates/effects/src/solids/tests_shadow.rs @@ -0,0 +1,225 @@ +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_geom::{Affine, BezPath}; + +use super::*; + +const RED: Color = Color::Rgb { r: 0.8, g: 0.2, b: 0.1 }; + +/// The 3D and Materials effects that cast shadows. +const CASTING: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, crate::REVOLVE]; + +fn square_node(id: u64, dx: f64) -> Node { + let mut b = BezPath::new(); + b.move_to((100.0 + dx, 100.0)); + b.line_to((200.0 + dx, 100.0)); + b.line_to((200.0 + dx, 200.0)); + b.line_to((100.0 + dx, 200.0)); + b.close_path(); + Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) +} + +fn art(n: &Node, id: &str) -> Option<Node> { + if id == crate::REVOLVE { crate::revolve_art(n) } else { solid_art(n) } +} + +/// The opacity of shadow `n`: a path filled black and nothing else; `None` for any other node. +fn shadow_opacity(n: &Node) -> Option<f32> { + let [AppearanceItem::Fill(fill)] = n.appearance.items.as_slice() else { return None }; + (matches!(n.kind, NodeKind::Path { .. }) && fill.paint.color() == Some(Color::BLACK)).then_some(fill.opacity) +} + +/// Whether `n` is the shadow of opaque art: a path filled black at 50 %, nothing else. +fn is_shadow(n: &Node) -> bool { + shadow_opacity(n) == Some(0.5) +} + +fn shadows(n: &Node) -> usize { + let mut count = 0; + n.walk(&mut |c| count += usize::from(is_shadow(c))); + count +} + +#[test] +fn each_3d_effect_draws_its_shadow_behind_its_solid_when_shadows_are_on() { + for id in CASTING { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, &json!({})).unwrap()); + let plain = art(&n, id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&plain), 0, "{id}: off by default"); + n.appearance.effects[0].params = json!({"shadow": true, "shadowDistance": 50}); + let lit = art(&n, id).unwrap_or_else(|| panic!("{id}")); + let children = lit.children().unwrap(); + assert!(is_shadow(&children[0]), "{id}: the shadow is drawn first"); + assert_eq!(shadows(&lit), 1, "{id}"); + // The default light is up and to the left: the shadow on a plane away from the object + // reaches past the solid down and right. + let shadow = children[0].visual_bounds().unwrap(); + let solid = children[1..].iter().filter_map(|c| c.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(shadow.x1 > solid.x1 && shadow.y1 > solid.y1, "{id}: {shadow:?} {solid:?}"); + // The art's bounds take the shadow in. + assert!(lit.visual_bounds().unwrap().contains_rect(shadow), "{id}"); + } +} + +#[test] +fn the_shadow_moves_with_its_settings() { + for id in CASTING { + let bounds = |params: Value| { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + let lit = art(&n, id).unwrap(); + let shadow = &lit.children().unwrap()[0]; + assert!(is_shadow(shadow), "{id} {params}"); + shadow.visual_bounds().unwrap() + }; + let near = bounds(json!({"shadow": true})); + let far = bounds(json!({"shadow": true, "shadowDistance": 100})); + assert!(far.x1 > near.x1 + 1.0, "{id}: {near:?} {far:?}"); + // With the light straight in front, the outline falls about the plane's center; at 10 % + // the plane cuts it to a square 0.4 times the object's size across. + let tight = bounds(json!({"shadow": true, "shadowBounds": 10, "lightHeight": 90})); + let wide = bounds(json!({"shadow": true, "shadowBounds": 400, "lightHeight": 90})); + assert!(wide.width() > tight.width() * 2.0, "{id}: {tight:?} {wide:?}"); + let below = bounds(json!({"shadow": true, "shadowPosition": "below", "rotationX": -30})); + assert_ne!(below, near, "{id}"); + } +} + +#[test] +fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() { + for id in CASTING { + for (params, error) in [ + (json!({"shadow": "yes"}), "shadow must be true or false"), + (json!({"shadowPosition": "under"}), "shadowPosition must be behind or below"), + (json!({"shadowPosition": 1}), "shadowPosition must be behind or below"), + (json!({"shadowDistance": 101}), "shadowDistance must be a number from 0 to 100"), + (json!({"shadowDistance": -1}), "shadowDistance must be a number from 0 to 100"), + (json!({"shadowBounds": 5}), "shadowBounds must be a number from 10 to 400"), + (json!({"shadowBounds": "wide"}), "shadowBounds must be a number from 10 to 400"), + ] { + let err = validate_three_d_params(id, ¶ms).unwrap_err(); + assert!(err.contains(error), "{id} {params}: {err}"); + } + let ok = json!({"shadow": true, "shadowPosition": "below", "shadowDistance": 100, "shadowBounds": 10}); + assert!(validate_three_d_params(id, &ok).is_ok(), "{id}"); + } +} + +#[test] +fn a_group_casts_one_shadow_for_all_its_members() { + for id in CASTING { + let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(square_node(2, 200.0))]); + g.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true, "lightHeight": 90})).unwrap()); + let lit = art(&g, id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&lit), 1, "{id}"); + let shadow = lit.children().unwrap()[0].clone(); + assert!(is_shadow(&shadow), "{id}"); + // With the light straight in front, the shadow behind spans both members. + let b = shadow.visual_bounds().unwrap(); + assert!(b.x0 < 200.0 && b.x1 > 300.0, "{id}: {b:?}"); + } +} + +/// A member's opacity mask applies to the part of the shadow it casts, as to its solid: that part +/// is drawn in the mask, the other member's outside it, both on one plane. +#[test] +fn a_masked_member_casts_its_part_of_the_shadow_in_its_mask() { + for id in CASTING { + let mut masked = square_node(2, 200.0); + let mut cover = square_node(3, 200.0); + cover.appearance.items = Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0).items; + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(cover, true))); + let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(masked)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let lit = art(&g, id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&lit), 2, "{id}: one piece for each member"); + let mut in_mask = 0; + lit.walk(&mut |c| { + if c.extras().mask.is_some() { + c.walk(&mut |s| in_mask += usize::from(is_shadow(s))); + } + }); + assert_eq!(in_mask, 1, "{id}"); + } +} + +#[test] +fn transparent_art_and_a_light_that_lights_nothing_cast_no_shadow() { + for id in CASTING { + let mut n = square_node(1, 0.0); + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true, "shade": false})).unwrap()); + assert_eq!(shadows(&art(&n, id).unwrap()), 0, "{id}: Shading off"); + n.appearance.effects[0].params = json!({"shadow": true, "lightIntensity": 0}); + assert_eq!(shadows(&art(&n, id).unwrap()), 0, "{id}: no intensity"); + // A member at 0 % opacity casts nothing; the other member still casts its shadow. + let mut clear = square_node(2, 200.0); + clear.opacity = 0.0; + let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(clear)]); + g.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true, "lightHeight": 90})).unwrap()); + let lit = art(&g, id).unwrap_or_else(|| panic!("{id}")); + let shadow = lit.children().unwrap()[0].clone(); + assert!(is_shadow(&shadow), "{id}"); + let b = shadow.visual_bounds().unwrap(); + assert!(b.x1 < 300.0, "{id}: only the visible member casts: {b:?}"); + // Art at 50 % casts a shadow half as dark. + let mut half = square_node(1, 0.0); + for item in &mut half.appearance.items { + if let AppearanceItem::Fill(fill) = item { + fill.opacity = 0.5; + } + } + half.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let lit = art(&half, id).unwrap(); + assert_eq!(shadow_opacity(&lit.children().unwrap()[0]), Some(0.25), "{id}"); + // Art in a blending mode casts its shadow in that mode. + for item in &mut half.appearance.items { + if let AppearanceItem::Fill(fill) = item { + fill.blend = BlendMode::Screen; + } + } + let lit = art(&half, id).unwrap(); + let AppearanceItem::Fill(fill) = &lit.children().unwrap()[0].appearance.items[0] else { panic!("{id}: a fill") }; + assert_eq!(fill.blend, BlendMode::Screen, "{id}"); + } +} + +/// With a 3D effect on each of two fills, both fills' shadows are drawn behind both fills' solids. +#[test] +fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() { + for id in CASTING { + let mut n = square_node(1, 0.0); + let fill = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap().clone(); + n.appearance.items = vec![fill.clone(), fill]; + for item in &mut n.appearance.items { + item.effects_mut().push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + } + let lit = art(&n, id).unwrap_or_else(|| panic!("{id}")); + let children = lit.children().unwrap(); + assert!(children.len() >= 4, "{id}"); + assert!(is_shadow(&children[0]) && is_shadow(&children[1]), "{id}: both shadows first"); + assert!(children[2..].iter().all(|c| !is_shadow(c)), "{id}"); + } +} + +#[test] +fn expand_appearance_keeps_the_shadow_as_a_path() { + for id in CASTING { + let mut d = Document::new(400.0, 400.0); + let mut n = square_node(1, 0.0); + n.id = d.alloc_id(); + n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap()); + let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None; + let expanded = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap_or_else(|| panic!("{id}")); + assert_eq!(shadows(&expanded), 1, "{id}"); + let mut effects = 0; + expanded.walk(&mut |c| effects += c.appearance.effects.len()); + assert_eq!(effects, 0, "{id}"); + // It moves with the object, as the solid does. + let before = art(&n, id).unwrap().children().unwrap()[0].visual_bounds().unwrap(); + n.transform(Affine::translate((40.0, 0.0)), false); + let after = art(&n, id).unwrap().children().unwrap()[0].visual_bounds().unwrap(); + assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}"); + } +} diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index c96dcb477c..acb980204c 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -173,6 +173,18 @@ fn bar(hw: f64) -> f64 { /// Where the notch of the (open) arrow sits, as a fraction of the length. const NOTCH: f64 = 0.7; +/// How far [`super::stroke_pieces`] trims the line under each end's head: the head's inset from +/// the tip, along the path. Both are 0 without a head at that end, and in [`ArrowAlign::Extend`], +/// where the stroke keeps its full length. +pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) { + if st.arrow_align != ArrowAlign::Tip { + return (0.0, 0.0); + } + let cap = cap_extent(st.cap, st.width); + let inset_of = |kind: Option<Arrowhead>, end: bool| kind.map_or(0.0, |k| inset(k, st.arrow_weight(end), cap)); + (inset_of(st.start_arrow, false), inset_of(st.end_arrow, true)) +} + /// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 { let l = len(hw); diff --git a/crates/effects/src/stroke/gradient.rs b/crates/effects/src/stroke/gradient.rs index 1cb79e9c72..4bddf80b0a 100644 --- a/crates/effects/src/stroke/gradient.rs +++ b/crates/effects/src/stroke/gradient.rs @@ -18,11 +18,11 @@ use std::collections::VecDeque; use kurbo::{BezPath, Point, Shape, Vec2}; use vectorcraft_doc::color::{Gradient, GradientGeom, GradientPaint, Paint}; use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP}; -use vectorcraft_doc::{GradientMesh, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; +use vectorcraft_doc::{GradientMesh, LineCap, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; use vectorcraft_geom::FillRule; use super::width::{flatten, left, length, split_at}; -use super::{aligned_width, cap_extent, is_closed, segments, subpaths, unit}; +use super::{aligned_width, arrow, cap_extent, is_closed, segments, subpaths, unit}; /// Largest stretch of a rib on a turn's bisector (1 / cos of half the turn, about 74°) before the /// corner gets a fan of ribs round its outside. @@ -97,7 +97,10 @@ impl Lay<'_> { /// How far a rib at fraction `t` reaches either side of the path to cover the stroke there. fn cover(&self, t: f64) -> f64 { - self.half(t) + self.margin + // A square cap's corners stand √2 of the half-width out from where the dash ends, and a + // dash can end just past a corner: reach that far, or they paint outside every slice. + let diag = if self.st.dash.is_some() && self.st.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 }; + self.half(t) * diag + self.margin } /// The across band at fraction `t` of a subpath whose visible side is `side` (`Some(true)`: @@ -162,6 +165,9 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, return vec![]; } let heads = (st.head_reach(false), st.head_reach(true)); + // With a tip-aligned arrowhead the stroke's line, and with it the width profile, stops at the + // head's inset from the tip (`stroke_pieces`). + let trims = arrow::trims(st); let mut lay = Lay { st, hw, margin, ext: (0.0, 0.0) }; // Caps reach as far past the ends as the stroke is wide there. let cap = |t: f64| cap_extent(st.cap, 2.0 * lay.half(t)); @@ -170,27 +176,34 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, let count = subs.len(); let mut out = vec![]; for (k, (range, closed)) in subs.into_iter().enumerate() { - let (pts, corner) = flatten(&segments(&bp.elements()[range]), closed, tol.max(1e-4)); - let side = - (st.align != StrokeAlign::Center && closed_path && closed).then(|| band_on_left(bp, rule, &pts, st.align, (4.0 * tol).min(hw / 2.0))); + let segs = segments(&bp.elements()[range]); + let flat = flatten(&segs, closed, tol.max(1e-4)); + let side = (st.align != StrokeAlign::Center && closed_path && closed) + .then(|| band_on_left(bp, rule, &flat.pts, st.align, (4.0 * tol).min(hw / 2.0))); // Arrowheads sit on the start of the first subpath and the end of the last one. let heads = (if k == 0 { heads.0 } else { 0.0 }, if k + 1 == count { heads.1 } else { 0.0 }); - let ribs = match pts.len() { + let trims = (if k == 0 { trims.0 } else { 0.0 }, if k + 1 == count { trims.1 } else { 0.0 }); + let ribs = match flat.pts.len() { 0 => continue, // A subpath of no length: a dot (round and projecting caps paint it). 1 => { let (d, b, e) = (Vec2::new(1.0, 0.0), lay.band(0.0, side), lay.ext.0.max(lay.ext.1)); let r = lay.cover(0.0); - vec![Rib::square(pts[0] - d * e, d, r, 0.0, b), Rib::square(pts[0] + d * e, d, r, 0.0, b)] + vec![Rib::square(flat.pts[0] - d * e, d, r, 0.0, b), Rib::square(flat.pts[0] + d * e, d, r, 0.0, b)] } _ => { - let total = length(&pts, closed); + let total = length(&flat.pts, closed); if total <= 1e-12 { continue; } let steps = if max_dt < 1.0 { (1.0 / max_dt).ceil() as usize } else { 1 }; let profile = st.profile.iter().flat_map(|p| p.points.iter().map(|q| q.0)); let heads = if closed { (0.0, 0.0) } else { heads }; + // A tip-aligned arrowhead shortens the line it sits on, and the stroke's outline + // reads the width profile along the shortened line (`stroke_pieces`); the ribs + // must read it there too, or on a profile that changes fast they cover a narrower + // band than the stroke paints. + let span = if closed { (0.0, total) } else { (trims.0.min(total), (total - trims.1).max(trims.0)) }; // Where an arrowhead's reach ends gets a rib of its own, so the ribs that reach // across a head run all the way there instead of narrowing towards the next corner // from the head's tip, which leaves the corners of its base outside (#5964). @@ -200,11 +213,11 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, .copied() .chain(profile) .chain((1..steps).map(|i| i as f64 / steps as f64)) - .map(|t| t * total) + .map(|t| span.0 + (span.1 - span.0) * t) .chain(head_ends) .collect(); - let (pts, _) = split_at(&pts, &corner, closed, &at); - strip(&lay, &pts, closed, total, side, heads) + let (pts, _, _) = split_at(&flat, closed, &at, &segs); + strip(&lay, &pts, closed, total, side, heads, span) } }; out.push(ribs); @@ -226,8 +239,9 @@ fn band_on_left(bp: &BezPath, rule: FillRule, pts: &[Point], align: StrokeAlign, } /// The ribs along one flattened subpath `pts` of length `total` (`heads`: how far arrowheads -/// reach from its start and end). -fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, heads: (f64, f64)) -> Vec<Rib> { +/// reach from its start and end). `span` is the stretch of the subpath the width profile is laid +/// along: the whole of it, or what is left between tip-aligned arrowheads. +fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, heads: (f64, f64), span: (f64, f64)) -> Vec<Rib> { let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -249,7 +263,9 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, // stroke is wide anywhere: where a stroke crosses or runs close by itself, a narrow part // reaching that far would paint over a wide part beside it (#5960). The start of a closed // subpath is also its end. Ribs near an arrowhead reach across it. - let cover: Vec<f64> = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(along[i] / total) }).collect(); + // The fraction of the profile at how far `s` is along the subpath: the profile spans `span`. + let t_at = |s: f64| if span.1 > span.0 { ((s - span.0) / (span.1 - span.0)).clamp(0.0, 1.0) } else { 0.0 }; + let cover: Vec<f64> = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(t_at(along[i])) }).collect(); let window = match lay.st.dash { Some(_) if lay.st.profile.is_some() => cap_extent(lay.st.cap, 2.0 * lay.hw * lay.st.profile_max()), _ => 0.0, @@ -279,7 +295,7 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, let (first, last) = if closed { (0, n) } else { (1, n - 1) }; for i in first..last { let v = i % n; - let t = along[v] / total; + let t = t_at(along[v]); let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(v), t, lay.band(t, side)); // A closed subpath starts after the fan of its first corner and ends with it. let skip = if closed && i == 0 { ribs.len() - 1 } else { 0 }; diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 46969ff639..fc3f2eee48 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -232,16 +232,14 @@ fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() { let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3); assert!(near(plain.area().abs(), 1000.0, 1e-6)); let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3); - // The lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714). - assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05)); - // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens - // rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers - // its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192. + // The lens is a parabola between its ends: 2/3 of the full-width band. + assert!(near(lens.area().abs(), 2000.0 / 3.0, 0.1)); + // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). let st = stroke(10.0, |s| { s.profile = Some(WidthProfile::lens()); s.dash = Some(dashed(&[25.0, 25.0], 0.0)); }); - assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05)); + assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 1000.0 / 3.0, 0.1)); assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty()); } diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index b427fdbce7..b389cab853 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -155,9 +155,10 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![10.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip. + // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip, + // where the smooth profile is thinner than a straight ramp (a parabola's first tenth). assert!(o.contains(Point::new(45.0, 4.0)) && o.contains(Point::new(45.0, -4.0)), "middle dash is wide"); - assert!(!o.contains(Point::new(5.0, 2.0)) && o.contains(Point::new(5.0, 0.3)), "first dash is thin"); + assert!(o.contains(Point::new(5.0, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin"); assert!(!o.contains(Point::new(15.0, 0.0)), "gaps stay empty"); // Dots too: a round dot near the middle is bigger than one near an end. let st = stroke(10.0, |s| { @@ -166,7 +167,7 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - assert!(o.contains(Point::new(50.0, 4.5)) && !o.contains(Point::new(10.0, 1.5)) && o.contains(Point::new(10.0, 0.5))); + assert!(o.contains(Point::new(50.0, 4.5)) && o.contains(Point::new(10.0, 1.4)) && !o.contains(Point::new(10.0, 2.0))); } /// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0). diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index a0056d6b32..ea966ea076 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -138,9 +138,8 @@ fn across_runs_from_the_left_edge_to_the_right() { let mut lens = st.clone(); lens.profile = Some(WidthProfile::lens()); let sl = slices(&line, &lens); - // A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is - // 3.125 up. - assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05); + // A quarter of the way along, the lens is three quarters as wide: its top edge is 3.75 up. + assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05); assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02); } diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 4a9dc26784..0b307cc6b5 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -3,17 +3,18 @@ //! A stroke with a [`WidthProfile`] is drawn as a filled outline: each subpath is flattened, and //! at every sample the left and right offsets `width/2 · factor(t)` (t = fraction of the //! subpath's length) are placed along the normal. Corners of the path take the stroke's miter, -//! round or bevel join on their outer side (smooth points bend round), open subpaths get butt, -//! round or projecting caps (the round cap blends the two side widths), and closed subpaths become -//! two loops of opposite orientation filled with the non-zero rule. Dashes are pieces of a longer -//! subpath and read the profile where they sit along it ([`outline_spans`]). +//! round or bevel join on their outer side (smooth points offset along the curve's normal), open +//! subpaths get butt, round or projecting caps (the round cap blends the two side widths), and +//! closed subpaths become two loops of opposite orientation filled with the non-zero rule. Dashes +//! are pieces of a longer subpath and read the profile where they sit along it ([`outline_spans`]). use std::f64::consts::PI; -use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Rect, Vec2}; +use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Vec2}; use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile}; +use vectorcraft_pathops::fit_cubics_through; -use super::{kink, segments, subpaths, unit}; +use super::{kink, segments, subpaths, tangent, unit}; /// Filled outline of `bp` stroked with `width` scaled by `profile`, with the caps, joins and miter /// limit of `st`, flattened to `tol`. @@ -24,15 +25,16 @@ pub fn width_outline(bp: &BezPath, width: f64, profile: &WidthProfile, st: &Stro /// Outline only flattened segments near `near`, retaining each run's original fractions of its /// whole subpath for the width profile. `None` means no segments could be omitted. pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64, near: Rect) -> Option<BezPath> { - let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) }; + let ctx = Ctx::new(width, profile, st, tol); 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(); + let segs = segments(&bp.elements()[r]); + let flat = flatten(&segs, closed, ctx.tol); + let n = flat.pts.len(); if n < 2 { continue; } @@ -41,7 +43,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil 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 (a, b) = (flat.pts[i], flat.pts[i + 1]); let len = a.distance(b); if !len.is_finite() { return None; @@ -51,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil 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)); + ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64); continue; } cut = true; @@ -59,27 +61,31 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil continue; } let mut walked = 0.0; - let mut run = Vec::new(); - let mut run_corner = Vec::new(); + let mut run: Option<Flat> = None; let mut from = 0.0; for i in 0..count { if kept[i] { - if run.is_empty() { + if run.is_none() { from = walked / total; - run.push(pts[i]); - run_corner.push(corner[i]); + run = Some(Flat { pts: vec![flat.pts[i]], corner: vec![flat.corner[i]], seg_of: vec![], param: vec![] }); } - 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(); + if let Some(part) = run.as_mut() { + part.pts.push(flat.pts[i + 1]); + part.corner.push(flat.corner[i + 1]); + part.seg_of.push(flat.seg_of[i]); + part.param.push(flat.param[i]); + } + } else if let Some(part) = run.take() + && part.pts.len() > 1 + { + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); } walked += lengths[i]; } - if run.len() > 1 { - ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total)); + if let Some(part) = run + && part.pts.len() > 1 + { + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); } } cut.then_some(out) @@ -89,12 +95,15 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil /// `spans[i]` of the subpath it was cut from (see [`Dashed::spans`](super::Dashed::spans)); /// subpaths without a span are whole. pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64) -> BezPath { - let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) }; + let ctx = Ctx::new(width, profile, st, tol); let mut out = BezPath::new(); for (i, (r, closed)) in subpaths(bp).into_iter().enumerate() { - let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol); - if pts.len() > 1 { - ctx.subpath(&mut out, &pts, &corner, closed, spans.get(i).copied().unwrap_or((0.0, 1.0))); + let segs = segments(&bp.elements()[r]); + let flat = flatten(&segs, closed, ctx.tol); + if flat.pts.len() > 1 { + let span = spans.get(i).copied().unwrap_or((0.0, 1.0)); + let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1); + ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0)); } } out @@ -105,19 +114,34 @@ pub(super) fn left(t: Vec2) -> Vec2 { Vec2::new(t.y, -t.x) } +/// A flattened subpath: its points, which of them are corners, and the source segment and +/// parameter range that drew each flattened piece (so a sample added between two points can read +/// that piece's tangent instead of the chord's direction). +pub(super) struct Flat { + pub(super) pts: Vec<Point>, + pub(super) corner: Vec<bool>, + pub(super) seg_of: Vec<usize>, + /// The source segment's parameter range for each flattened piece. Restricting the tangent + /// search to this range keeps a sample on the branch that drew it when a cubic loops back + /// near itself. + pub(super) param: Vec<(f64, f64)>, +} + /// The flattened points of one subpath (consecutive duplicates removed; a closed one doesn't /// repeat its start), each marked when it is a corner of the path. -pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, Vec<bool>) { - let Some(s0) = segs.first() else { return (vec![], vec![]) }; - let (mut pts, mut corner) = (vec![s0.start()], vec![false]); - // The first and the last segment that drew something. - let (mut first, mut prev): (Option<&PathSeg>, Option<&PathSeg>) = (None, None); - for seg in segs { - let at = pts.len() - 1; +pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat { + let Some(s0) = segs.first() else { return Flat { pts: vec![], corner: vec![], seg_of: vec![], param: vec![] } }; + let mut flat = Flat { pts: vec![s0.start()], corner: vec![false], seg_of: vec![], param: vec![] }; + // The last segment that drew something, and the last parameter it reached. + let mut prev: Option<&PathSeg> = None; + let mut last_added: Option<(usize, f64)> = None; + for (si, seg) in segs.iter().enumerate() { + let at = flat.pts.len() - 1; + let before = flat.pts.len(); let mut push = |p: Point| { - if pts.last().is_none_or(|l| l.distance(p) > 1e-9) { - pts.push(p); - corner.push(false); + if flat.pts.last().is_none_or(|l| l.distance(p) > 1e-9) { + flat.pts.push(p); + flat.corner.push(false); } }; match seg { @@ -130,77 +154,151 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, } }), } - if pts.len() > at + 1 { - match prev { - Some(p) => corner[at] = kink(p, seg), - None => first = Some(seg), + if flat.pts.len() > before { + let end = flat.pts.len() - 1; + flat.seg_of.resize(end, si); + for slot in flat.seg_of.iter_mut().take(end).skip(at) { + *slot = si; + } + // Find each new point's source parameter, never going backwards. A point is on the + // curve, so its nearest parameter is exact except at a self-intersection, where the + // monotone search picks the branch that continues this flattened piece. + let mut ts = Vec::with_capacity(end - at + 1); + ts.push(0.0); + let mut t = 0.0; + for p in &flat.pts[at + 1..=end] { + if t >= 1.0 - 1e-12 { + t = 1.0; + } else { + let sub = seg.subsegment(t..1.0); + let nr = sub.nearest(*p, 1e-9); + t = (t + (1.0 - t) * nr.t).clamp(0.0, 1.0); + } + ts.push(t); + } + flat.param.extend(ts.windows(2).map(|w| (w[0], w[1]))); + last_added = ts.last().map(|t| (si, *t)); + if let Some(p) = prev { + flat.corner[at] = kink(p, seg); } prev = Some(seg); } } if closed { - if pts.len() > 1 && pts[0].distance(pts[pts.len() - 1]) <= 1e-9 { - pts.pop(); - corner.pop(); + if flat.pts.len() > 1 && flat.pts[0].distance(flat.pts[flat.pts.len() - 1]) <= 1e-9 { + flat.pts.pop(); + flat.corner.pop(); } - if let (Some(a), Some(b)) = (prev, first) { - corner[0] = kink(a, b); + if let (Some(a), Some(b)) = (segs.last(), segs.first()) { + flat.corner[0] = kink(a, b); + } + // The closing piece comes from the last source segment even when its endpoint is the + // already-present start point and did not add a flattened point. Keep a tangent (and its + // whole parameter range) for it. + flat.seg_of.truncate(flat.pts.len()); + flat.param.truncate(flat.pts.len()); + if flat.seg_of.len() < flat.pts.len() { + let last = segs.len().saturating_sub(1); + // A closing curve with interior flattened points has already reached a parameter + // before its end (the duplicated start point was not added); the missing piece starts + // where it left off, not at 0. + let start = match last_added { + Some((si, t)) if si == last => t, + _ => 0.0, + }; + flat.seg_of.resize(flat.pts.len(), last); + flat.param.resize(flat.pts.len(), (start, 1.0)); } } - (pts, corner) + flat } -/// The most samples added between two width points. -const MAX_SPAN_SAMPLES: usize = 64; -/// The most samples [`densify`] adds between width points along one piece of a subpath. -const MAX_CURVE_SAMPLES: usize = 4096; - -/// Insert samples where the profile has width points (the two points of a discontinuous point -/// share one sample), and between them where the profile's curve ([`WidthProfile::at`]) bends, so -/// that a straight run follows it to within `tol` with a stroke of half width `half`. `span` maps -/// the subpath onto the profile (see [`outline_spans`]). -fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64), half: f64, tol: f64) -> (Vec<Point>, Vec<bool>) { - let total = length(pts, closed); +/// Insert samples where the profile has width points and between them, so its smooth curve is +/// drawn as a smooth outline along straight runs too (the two points of a discontinuous point +/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]). +fn densify( + flat: &Flat, + segs: &[PathSeg], + closed: bool, + profile: &WidthProfile, + span: (f64, f64), + density: f64, +) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) { + // Two samples per profile segment: the segment end plus its midpoint. The outline is fitted + // with cubics through these points, so a smooth width curve needs far fewer samples than it + // did when every pair of samples became a separate cubic. A profile with a strong bend gets + // one more subdivision; a flat profile draws the same straight pieces as before. + const SAMPLES: usize = 2; + const MAX_SAMPLES: usize = 8; + // The gap (in width factor) the straight line between two samples may leave: small enough + // that a sharp peak like the lens' needs one more piece, large enough that a long taper's + // gentle bend does not. + const BEND: f64 = 0.05; + let total = length(&flat.pts, closed); let range = span.1 - span.0; if total <= 1e-12 || range <= 1e-12 { - return (pts.to_vec(), corner.to_vec()); + return split_at(flat, closed, &[], segs); } - let along = |t: f64| (t - span.0) / range * total; // Where the profile's points fall along this piece (a span past 1 wraps round a closed path). - let mut marks: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(along).collect(); - let mut added = 0; - for shift in [0.0, 1.0] { - for w in profile.points.windows(2) { - let (a, b) = (&w[0], &w[1]); - let (t0, t1) = (a.0 + shift, b.0 + shift); - if t1 - t0 <= 1e-7 || t1 <= span.0 || t0 >= span.1 { - continue; - } - // A span whose curve is the straight line between its points (a two-point taper, - // points on one line) needs nothing between them. A cubic off the line is off it at a - // quarter or three quarters of the way. - let off_line = |u: f64| { - let (l, r) = profile.at(a.0 + (b.0 - a.0) * u); - half * (l - (a.1 + (b.1 - a.1) * u)).abs().max((r - (a.2 + (b.2 - a.2) * u)).abs()) - }; - if off_line(0.25) <= tol * 1e-3 && off_line(0.75) <= tol * 1e-3 { - continue; - } - // A monotone cubic span bends by at most 12 times its change in width over the span - // squared, so the chords of `n` equal parts stray at most 1.5 · change / n² from it. - let change = half * (b.1 - a.1).abs().max((b.2 - a.2).abs()); - let n = (1.5 * change / tol).sqrt().ceil(); - let n = if n.is_finite() { n.clamp(1.0, MAX_SPAN_SAMPLES as f64) as usize } else { MAX_SPAN_SAMPLES }; - for k in 1..n { - if added >= MAX_CURVE_SAMPLES { - break; - } - marks.push(along(t0 + (t1 - t0) * k as f64 / n as f64)); - added += 1; - } + let mut ts: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).collect(); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); + // A flat profile draws the same straight pieces as before: sample only its points. + let constant = profile.points.first().is_some_and(|f| profile.points.iter().all(|p| (p.1 - f.1).abs() <= 1e-12 && (p.2 - f.2).abs() <= 1e-12)); + let cap = (4096 / ts.len().max(1)).max(1); + // A curved path's flattened points already sample the width along the subpath. On a dense + // piece the profile's own points are enough; a straight run has only its ends, so it needs + // the extra samples. This keeps curved, profiled art close to a uniform stroke's size. + let mut marks = Vec::with_capacity(ts.len() * SAMPLES); + for w in ts.windows(2) { + let (a, b) = (w[0], w[1]); + let samples = if constant { + 1 + } else { + // `ts` has the profile both at t and t + 1 for a dash crossing a closed seam; the + // shifted copy has the same shape, so measure its bend on the unshifted segment. + let start = a.rem_euclid(1.0); + let end = start + (b - a); + let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, BEND).min(cap); + // How many of the flattened path's points already fall in this profile segment. + // `density` is measured on the whole subpath, not on this piece, so outlining only + // the piece near the view picks the same samples as outlining the whole subpath. + let existing = (b - a) * density; + if existing >= want as f64 { 1 } else { want } + }; + for k in 0..samples { + marks.push(a + (b - a) * k as f64 / samples as f64); } } - split_at(pts, corner, closed, &marks) + if let Some(&last) = ts.last() { + marks.push(last); + } + let marks: Vec<f64> = marks.into_iter().map(|t| (t - span.0) / range * total).collect(); + split_at(flat, closed, &marks, segs) +} + +/// How many pieces one profile segment needs so a cubic fit through their ends keeps the width +/// curve. A straight taper is already straight; a visible bend gets progressively more samples. +fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize { + let mut samples = base.max(1); + while samples < max { + // One probe in the middle of each piece: how far the curve leaves the straight line + // between the piece's ends. The more pieces, the closer the line follows the curve, so + // the loop only stops when the pieces it has are fine enough (or at `max`). + let mut dev = 0.0_f64; + for k in 0..samples { + let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64); + let (la, ra) = profile.at(t0 + (t1 - t0) * a); + let (lb, rb) = profile.at(t0 + (t1 - t0) * b); + let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0); + dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs()); + } + if dev <= bend { + break; + } + samples *= 2; + } + samples } /// Length of a flattened subpath (see [`flatten`]). @@ -212,31 +310,70 @@ pub(super) fn length(pts: &[Point], closed: bool) -> f64 { /// A flattened subpath (see [`flatten`]) with points added `marks` along it (distances from its /// start; those on a point or off the subpath are ignored). -pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f64]) -> (Vec<Point>, Vec<bool>) { +pub(super) fn split_at(flat: &Flat, closed: bool, marks: &[f64], segs: &[PathSeg]) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) { + let Flat { pts, corner, seg_of, param } = flat; let n = pts.len(); let seg_count = if closed { n } else { n.saturating_sub(1) }; - let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); + // The source's direction at a source parameter. The chord direction is the secant, not the + // tangent: using it for points added inside a chord jogs the normal at every flatten vertex. + let source_at = |si: usize, t: f64| -> Vec2 { segs.get(si).map_or(Vec2::new(1.0, 0.0), |seg| tangent(seg, t)) }; + // A point added inside a flattened piece searches only that piece's source parameter range: + // a looping cubic can pass near itself, and a full-segment nearest would take the other + // branch's tangent. + let source_near = |p: Point, i: usize| -> Vec2 { + let Some(si) = seg_of.get(i).copied() else { return Vec2::new(1.0, 0.0) }; + let Some(seg) = segs.get(si) else { return Vec2::new(1.0, 0.0) }; + let (t0, t1) = param.get(i).copied().unwrap_or((0.0, 1.0)); + if t1 - t0 > 1e-12 { + let sub = seg.subsegment(t0..t1); + tangent(seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t) + } else { + tangent(seg, t0) + } + }; + // At a shared point, average the arriving and leaving directions unless it is a corner. + let dir_at = |i: usize| -> Vec2 { + let incoming = if i == 0 { + if closed { seg_of.last().copied().zip(param.last().copied()) } else { None } + } else { + seg_of.get(i - 1).copied().zip(param.get(i - 1).copied()) + }; + let outgoing = seg_of.get(i).copied().zip(param.get(i).copied()); + let a = incoming.map(|(si, (_, t))| source_at(si, t)); + let b = outgoing.map(|(si, (t, _))| source_at(si, t)); + match (a, b) { + (Some(a), Some(b)) if !corner[i] => { + let sum = a + b; + if sum.hypot() > 1e-9 { unit(sum) } else { b } + } + (_, Some(b)) => b, + (Some(a), None) => a, + (None, None) => Vec2::new(1.0, 0.0), + } + }; + let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); let mut acc = 0.0; - // Sorted once, so each segment finds its marks by search, not by a pass over all of them. - let mut marks = marks.to_vec(); - marks.sort_by(f64::total_cmp); for i in 0..seg_count { let (a, b) = (pts[i], pts[(i + 1) % n]); let len = a.distance(b); out.0.push(a); out.1.push(corner[i]); - let from = marks.partition_point(|d| *d <= acc + 1e-9); - let mut inner: Vec<f64> = marks.iter().skip(from).copied().take_while(|d| *d < acc + len - 1e-9).collect(); + out.2.push(dir_at(i)); + let mut inner: Vec<f64> = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect(); + inner.sort_by(f64::total_cmp); inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); for d in inner { - out.0.push(a.lerp(b, (d - acc) / len)); + let p = a.lerp(b, (d - acc) / len); + out.0.push(p); out.1.push(false); + out.2.push(source_near(p, i)); } acc += len; } if !closed && n > 0 { out.0.push(pts[n - 1]); out.1.push(corner[n - 1]); + out.2.push(dir_at(n - 1)); } out } @@ -249,6 +386,8 @@ struct Ctx<'a> { join: LineJoin, miter_limit: f64, tol: f64, + /// The profile has one (left, right) width everywhere. + uniform: bool, } /// A vertex of a flattened subpath: where it is, the directions in and out, the lengths of the @@ -257,14 +396,31 @@ struct Vertex { p: Point, a: Vec2, b: Vec2, + /// The smooth tangent: the source curve's direction at this sample, or the average of its + /// arriving and leaving directions at a smooth join. A smooth point offsets along this + /// normal, not the chord bisector; otherwise the chord normal inside each flattened piece and + /// the bisector at each flatten vertex alternate and the edge is scalloped. + n: Vec2, la: f64, lb: f64, corner: bool, } -impl Ctx<'_> { - fn subpath(&self, out: &mut BezPath, pts: &[Point], corner: &[bool], closed: bool, span: (f64, f64)) { - let (pts, corner) = densify(pts, corner, closed, self.profile, span, self.half, self.tol); +impl<'a> Ctx<'a> { + fn new(width: f64, profile: &'a WidthProfile, st: &StrokeLayer, tol: f64) -> Self { + Self { + half: width / 2.0, + profile, + cap: st.cap, + join: st.join, + miter_limit: st.miter_limit, + tol: tol.max(1e-4), + uniform: profile.points.first().is_some_and(|f| profile.points.iter().all(|p| p.1 == f.1 && p.2 == f.2)), + } + } + + fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) { + let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density); let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let seg_dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -280,117 +436,398 @@ impl Ctx<'_> { // at a discontinuous point). let width_at = |d: f64| { let t = span.0 + (span.1 - span.0) * d / total; - let (b, a) = self.profile.around(if t > 1.0 { t - 1.0 } else { t }); + // A closed path joins its own start and end: a profile with different widths there + // is a step, not a stretch across the seam. + let (b, a) = if closed && span == (0.0, 1.0) && d <= 1e-12 { + (self.profile.around(1.0).0, self.profile.around(0.0).1) + } else { + self.profile.around(if t > 1.0 { t - 1.0 } else { t }) + }; let side = |(l, r): (f64, f64)| (self.half * l.max(0.0), self.half * r.max(0.0)); (side(b), side(a)) }; - let mut lpts = Vec::with_capacity(n); - let mut rpts = Vec::with_capacity(n); + let mut lpts: Vec<(Point, bool)> = Vec::with_capacity(n); + let mut rpts: Vec<(Point, bool)> = Vec::with_capacity(n); + // Only a butt cap makes the side end at a corner; square and round caps stay tangent to it. + let end_sharp = matches!(self.cap, LineCap::Butt); for (i, &p) in pts.iter().enumerate() { - let (before, after) = width_at(cum[i]); + let ((wl_b, wr_b), (wl_a, wr_a)) = width_at(cum[i]); if !closed && (i == 0 || i == n - 1) { - let nm = left(seg_dir[i.min(seg_count - 1)]); - let (wl, wr) = if i == 0 { after } else { before }; - lpts.push(p + nm * wl); - rpts.push(p - nm * wr); + let nm = left(dirs[i]); + let (wl, wr) = if i == 0 { (wl_a, wr_a) } else { (wl_b, wr_b) }; + lpts.push((p + nm * wl, end_sharp)); + rpts.push((p - nm * wr, end_sharp)); continue; } let ip = if i == 0 { seg_count - 1 } else { i - 1 }; - let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; + let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], n: dirs[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; // A step: the side goes straight out (or in) from the width before to the one after. - for (k, (wl, wr)) in [before, after].into_iter().enumerate() { - if k == 0 || (wl, wr) != before { - self.join(&mut lpts, &v, wl, 1.0); - self.join(&mut rpts, &v, wr, -1.0); - } + // Both ends of that straight piece are corners: the run before it must not round + // into the step. + let (step_l, step_r) = (wl_a != wl_b, wr_a != wr_b); + self.join(&mut lpts, &v, wl_b, 1.0, step_l); + self.join(&mut rpts, &v, wr_b, -1.0, step_r); + if step_l { + self.join(&mut lpts, &v, wl_a, 1.0, true); + } + if step_r { + self.join(&mut rpts, &v, wr_a, -1.0, true); } } if closed { - polygon(out, lpts.into_iter()); - polygon(out, rpts.into_iter().rev()); + polygon(out, lpts.into_iter(), self.tol); + polygon(out, rpts.into_iter().rev(), self.tol); return; } - let (t0, t1) = (seg_dir[0], seg_dir[seg_count - 1]); + let (t0, t1) = (dirs[0], dirs[n - 1]); let ((wl0, wr0), (wl1, wr1)) = (width_at(0.0).1, width_at(total).0); let mut ring = lpts; // End cap: from the left side around the end to the right side. - cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap); + cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap, self.tol); ring.extend(rpts.into_iter().rev()); // Start cap: from the right side around the start back to the left side. - cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap); - polygon(out, ring.into_iter()); + cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap, self.tol); + polygon(out, ring.into_iter(), self.tol); } - /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path: the - /// join on the outer side of a turn, the inner miter point (or a detour through the vertex - /// when that would overshoot a segment) on the inner side. - fn join(&self, pts: &mut Vec<Point>, v: &Vertex, w: f64, side: f64) { + /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path. A + /// smooth point follows the vertex normal, the offset of the curve itself; a corner takes the + /// join on its outer side and the inner miter point (or a detour through the vertex when that + /// would overshoot a segment) on its inner side. + /// + /// Each point says whether the outline is sharp there: a path corner, a miter tip, a width + /// step or a butt cap end. Only those break the smooth fitting; a rapid width change makes + /// the offset turn sharply, but it is not a corner and must not be fitted as one. + fn join(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, w: f64, side: f64, step: bool) { let (na, nb) = (left(v.a) * side, left(v.b) * side); let mid = na + nb; // Cosine of half the turn; the miter point is `w / c` out along `mid`. let c = mid.hypot() / 2.0; - let miter = |pts: &mut Vec<Point>| pts.push(v.p + mid * (w / (2.0 * c * c))); if w <= 0.0 { - pts.push(v.p); - } else if v.b.dot(na) <= 0.0 { + pts.push((v.p, true)); + return; + } + let miter = if c > 1e-9 { Some(v.p + mid * (w / (2.0 * c * c))) } else { None }; + // The offset of the smooth path itself is at `w` along the path normal. The polyline + // miter (`w / c`) is the offset of the flattened segments, not of the curve: at a tight + // curve it spiked every sample outward and left a scalloped edge. The source curve's + // tangent is the smooth normal; a corner still uses its two chords for the join. + let smooth = v.p + left(v.n) * (w * side); + if v.b.dot(na) <= 0.0 { // Outer side: the path turns away from it. - let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY }; - match self.join { - _ if excess <= self.tol => miter(pts), - LineJoin::Miter if v.corner && 1.0 / c <= self.miter_limit => miter(pts), - LineJoin::Miter | LineJoin::Bevel if v.corner => pts.extend([v.p + na * w, v.p + nb * w]), - _ => self.arc(pts, v, na, nb, w), + if !v.corner { + // A smooth point has no join: its offset is along the path normal. + pts.push((smooth, step)); + } else { + let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY }; + match self.join { + _ if excess <= self.tol => pts.push((miter.unwrap_or(v.p), true)), + LineJoin::Miter if c > 1e-9 && 1.0 / c <= self.miter_limit => pts.push((miter.unwrap_or(v.p), true)), + LineJoin::Miter | LineJoin::Bevel => pts.extend([(v.p + na * w, true), (v.p + nb * w, true)]), + _ => self.arc(pts, v, na, nb, w, step), + } } - } else if c > 1e-9 && w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) { - miter(pts); + } else if c <= 1e-9 { + // A reversal has no inner miter; go through the vertex. That is a notch in the + // outline, so it stays sharp: fitting a curve through it would loop. + pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); + } else if !v.corner { + // A smooth point's inner offset follows its normal too. With a constant profile, once + // the half-width reaches the local radius of curvature the offset crosses the centre of + // curvature and comes back as a reversed contour, which the non-zero fill rules into a + // hole. The stroke covers that centre, so cut through it instead: the cut is inside the + // painted region and does not show. (With varying widths the crossing usually marks a + // real caustic; a cut there would show as a slit, so leave it to the offset.) + let turn = 2.0 * c.clamp(-1.0, 1.0).acos(); + let radius = if turn > 1e-9 { 0.5 * (v.la + v.lb) / turn } else { f64::INFINITY }; + if self.uniform && w >= radius { + pts.push((smooth, true)); + pts.push((v.p, true)); + pts.push((smooth, true)); + } else { + pts.push((smooth, step)); + } + } else if w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) { + // A corner's inner offset is its miter while that stays inside both segments. + pts.push((miter.unwrap_or(v.p), true)); } else { - pts.extend([v.p + na * w, v.p, v.p + nb * w]); + // The inner offset of a corner cuts through the vertex; keep that notch sharp. + pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); } } /// A round join from `na` to `nb` (unit normals) at radius `w` around `v`; a full reversal - /// rounds through the direction of travel. - fn arc(&self, pts: &mut Vec<Point>, v: &Vertex, na: Vec2, nb: Vec2, w: f64) { + /// rounds through the direction of travel. `sharp` marks a step at the join's ends. + fn arc(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, na: Vec2, nb: Vec2, w: f64, sharp: bool) { let phi = if (na + nb).hypot() < 1e-9 { if Vec2::new(-na.y, na.x).dot(v.a) > 0.0 { PI } else { -PI } } else { na.cross(nb).atan2(na.dot(nb)) }; let step = 2.0 * (1.0 - (self.tol / w).min(1.0)).acos(); let steps = ((phi.abs() / step.max(1e-3)).ceil() as usize).clamp(1, 256); for k in 0..=steps { let (s, c) = (phi * k as f64 / steps as f64).sin_cos(); - pts.push(v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w); + pts.push((v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w, sharp)); } } } /// Cap points between `c + u·r0` and `c − u·r1`, bulging towards `v`. -fn cap_points(ring: &mut Vec<Point>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap) { +#[allow(clippy::too_many_arguments)] +fn cap_points(ring: &mut Vec<(Point, bool)>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap, tol: f64) { match cap { LineCap::Butt => {} LineCap::Square => { let h = (r0 + r1) / 2.0; - ring.push(c + u * r0 + v * h); - ring.push(c - u * r1 + v * h); + ring.push((c + u * r0 + v * h, true)); + ring.push((c - u * r1 + v * h, true)); } LineCap::Round => { - let steps = 16; + // Enough steps that the cap's facets stay within `tol`, as a round join does. + let r = r0.max(r1).max(1e-9); + let step = 2.0 * (1.0 - (tol / r).min(1.0)).acos(); + let steps = ((PI / step.max(1e-6)).ceil() as usize).clamp(8, 256); for k in 1..steps { - let a = std::f64::consts::PI * k as f64 / steps as f64; + let a = PI * k as f64 / steps as f64; let r = r0 + (r1 - r0) * (k as f64 / steps as f64); - ring.push(c + u * (a.cos() * r) + v * (a.sin() * r)); + ring.push((c + u * (a.cos() * r) + v * (a.sin() * r), false)); } } } } -fn polygon(out: &mut BezPath, mut pts: impl Iterator<Item = Point>) { - let Some(first) = pts.next() else { return }; - out.move_to(first); - for p in pts { - out.line_to(p); +/// Append `pts` as a closed contour (a width outline's ring or loop), through a smooth run's +/// points as cubic curves. Sampled as line segments, a curved, wide stroke shows the facets of +/// its offset whenever it is magnified; the cubics keep it smooth. A run whose points are +/// collinear stays a line, and the points marked sharp — caps, miter joins, width steps and path +/// corners — stay sharp. A rapid width change turns the offset sharply without being a corner: +/// marking corners here rather than measuring turns keeps that turn smooth. +fn polygon(out: &mut BezPath, pts: impl Iterator<Item = (Point, bool)>, tol: f64) { + let mut ring: Vec<(Point, bool)> = Vec::new(); + for (p, sharp) in pts { + if !p.x.is_finite() || !p.y.is_finite() { + return; + } + if let Some(last) = ring.last_mut() + && last.0.distance(p) <= 1e-9 + { + last.1 |= sharp; + continue; + } + ring.push((p, sharp)); + } + if ring.len() > 1 + && ring[0].0.distance(ring[ring.len() - 1].0) <= 1e-9 + && let Some(last) = ring.pop() + { + ring[0].1 |= last.1; + } + let n = ring.len(); + if n == 0 { + return; + } + if n < 3 { + out.move_to(ring[0].0); + if n == 2 { + out.line_to(ring[1].0); + } + out.close_path(); + return; + } + // Start at a sharp point when there is one, so no run has to wrap: `smooth_run` starts from + // whichever point is current, and starting anywhere else would bridge over the skipped arc. + match ring.iter().position(|&(_, sharp)| sharp) { + None => { + // A smooth closed loop: fit across the seam, so it doesn't start with a kink. + let pts: Vec<Point> = ring.iter().map(|&(p, _)| p).collect(); + out.move_to(pts[0]); + smooth_run(out, &pts, true, tol); + } + Some(first) => { + out.move_to(ring[first].0); + // From each sharp point to the next; the sharp points themselves stay sharp. + let mut i = first; + loop { + let mut j = (i + 1) % n; + while !ring[j].1 { + j = (j + 1) % n; + } + // A contour with a single sharp point comes back to it: the run is the whole + // loop, fitted non-cyclically so that point stays sharp. + let steps = if j == i { n } else { (j + n - i) % n }; + if steps == 1 { + out.line_to(ring[j].0); + } else { + let run: Vec<Point> = (0..=steps).map(|k| ring[(i + k) % n].0).collect(); + smooth_run(out, &run, false, tol); + } + if j == first { + break; + } + i = j; + } + } } out.close_path(); } +/// The derivative of the run at each point, in points per point of chord length. Each coordinate +/// is a shape-preserving cubic Hermite (Fritsch–Carlson): between two points it stays within their +/// coordinate range, so a cubic through a fast width pinch cannot bulge past the pinch and cross +/// the other side, and it has a flat slope at a local extremum. A Catmull–Rom tangent (the secant +/// across the neighbours) does neither: it overshoots a V and, with the uneven sample spacing of a +/// flattened path, leaves a scalloped edge. +fn tangents(run: &[Point], cyclic: bool) -> Vec<Vec2> { + let n = run.len(); + let segs = if cyclic { n } else { n.saturating_sub(1) }; + let mut h = vec![0.0; segs]; + for (i, hi) in h.iter_mut().enumerate() { + *hi = run[i].distance(run[(i + 1) % n]); + } + let slope = |d0: f64, d1: f64, h0: f64, h1: f64| { + if d0 * d1 <= 0.0 { + return 0.0; + } + let (w0, w1) = (2.0 * h1 + h0, h1 + 2.0 * h0); + let m = (w0 + w1) / (w0 / d0 + w1 / d1); + if m.is_finite() { m } else { 0.0 } + }; + // The one-sided slope of a run's end uses its two end secants, instead of only the last one. + // A coarse sample then still leaves the end of a profile curve with the right slope. + let end_slope = |d0: f64, d1: f64, h0: f64, h1: f64| { + if d0 * d1 <= 0.0 || h0 + h1 <= 1e-12 { + return 0.0; + } + let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); + if m.is_finite() && m * d0 > 0.0 { + let cap = 3.0 * d0.abs(); + m.clamp(-cap, cap) + } else { + 0.0 + } + }; + let delta = |i: usize| -> Vec2 { + let hi = h[i % segs]; + if hi > 1e-12 { (run[(i + 1) % n] - run[i % n]) / hi } else { Vec2::ZERO } + }; + let mut out = vec![Vec2::ZERO; n]; + for (i, m) in out.iter_mut().enumerate() { + let (d0, d1) = (delta((i + n - 1) % n), delta(i % segs)); + let (h0, h1) = (h[(i + n - 1) % segs], h[i % segs]); + if h0 <= 1e-12 || h1 <= 1e-12 { + *m = if h1 > 1e-12 { d1 } else { d0 }; + } else if cyclic || (i > 0 && i + 1 < n) { + *m = Vec2::new(slope(d0.x, d1.x, h0, h1), slope(d0.y, d1.y, h0, h1)); + } else if i == 0 { + *m = if n >= 3 { + let (a, b) = (delta(0), delta(1)); + Vec2::new(end_slope(a.x, b.x, h[0], h[1]), end_slope(a.y, b.y, h[0], h[1])) + } else { + d1 + }; + } else { + *m = if n >= 3 { + let (a, b) = (delta(n - 2), delta(n - 3)); + Vec2::new(end_slope(a.x, b.x, h[n - 2], h[n - 3]), end_slope(a.y, b.y, h[n - 2], h[n - 3])) + } else { + d0 + }; + } + // A shape-preserving slope is flat in a coordinate at that coordinate's local extremum. + // Where both are extrema at one sample (a loop or a pinch in the sampled edge) the flat + // tangent would make a line and a kink; the secant across the sample keeps the curve C1 + // there, and the extremum itself is what trims the loop later. + if m.hypot() <= 1e-12 { + let prev = if cyclic || i > 0 { run[(i + n - 1) % n] } else { run[i] }; + let next = if cyclic || i + 1 < n { run[(i + 1) % n] } else { run[i] }; + let sec = next - prev; + if sec.hypot() > 1e-12 { + *m = sec.normalize(); + } + } + } + out +} + +/// Append a run of points as a fitted chain of cubics (or one line when they are collinear). +/// +/// A cubic through every flattened point, as this used to emit, keeps the outline smooth but puts +/// three coordinates per point into the file; a small, thin stroke then exports several times the +/// path data of the same stroke without a profile. Fit a chain within the outline tolerance +/// instead: the result is still G1 continuous and stays within `tol` of the sampled edge, but a +/// smooth side is a few cubics rather than one per flatten step. Profile bends that need finer +/// detail produce more cubics; straight runs stay lines. +fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) { + let n = run.len(); + if n < 2 { + return; + } + if !cyclic && is_straight(run, tol) { + out.line_to(run[n - 1]); + return; + } + let tans = tangents(run, cyclic); + let tol = tol.max(1e-6); + // A short run is one or two profile features, not flattened path detail. Fitting it loosely + // enough to save path data can let a handle cross the narrow side of a V; keep the + // shape-preserving per-point cubics there. + let segs = if cyclic { n } else { n - 1 }; + if n <= 3 { + for i in 0..segs { + let j = (i + 1) % n; + let h = run[i].distance(run[j]); + let (m0, m1) = (tans[i] * (h / 3.0), tans[j] * (h / 3.0)); + if m0.hypot() <= 1e-12 || m1.hypot() <= 1e-12 { + out.line_to(run[j]); + } else { + out.curve_to(run[i] + m0, run[j] - m1, run[j]); + } + } + return; + } + let unit_or = |v: Vec2, fallback: Vec2| { + let len = v.hypot(); + if len > 1e-12 { + v / len + } else { + let len = fallback.hypot(); + if len > 1e-12 { fallback / len } else { Vec2::new(1.0, 0.0) } + } + }; + let t0 = unit_or(tans[0], run[1] - run[0]); + let (pts, t0, t1) = if cyclic { + // Fit the seam too: the fit starts and arrives with the same tangent, so closing the + // contour adds no kink. + let mut pts = Vec::with_capacity(n + 1); + pts.extend_from_slice(run); + pts.push(run[0]); + (pts, t0, t0) + } else { + (run.to_vec(), t0, unit_or(tans[n - 1], run[n - 1] - run[n - 2])) + }; + // Fit tighter than the flattening tolerance: the fit's error is the whole outline's error, + // and a least-squares fit may sit on one side of the sampled edge, which would otherwise + // shift a profile's area visibly. The points lie on the outline's own curve, so the fit follows + // their curve between them rather than the chords through them. + let cubics = fit_cubics_through(&pts, t0, t1, tol * 0.1); + if cubics.is_empty() { + out.line_to(run[n - 1]); + return; + } + for c in cubics { + out.curve_to(c.p1, c.p2, c.p3); + } +} + +/// Are the run's points within the flattening tolerance of its chord? +fn is_straight(run: &[Point], tol: f64) -> bool { + let (a, b) = (run[0], run[run.len() - 1]); + let d = b - a; + let l = d.hypot(); + if l <= 1e-12 { + return false; + } + run.iter().all(|p| (d.cross(*p - a) / l).abs() <= tol.max(1e-6) * 0.25) +} + #[cfg(test)] mod tests { use super::*; @@ -423,13 +860,12 @@ mod tests { assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6); } - /// The Lens outline swells on its curve, and a profile with one side at zero paints only the other side. + /// The lens eases up to full width and back down (a parabolic bump averaging two thirds of + /// the width); a one-sided profile keeps its side at zero and stays on the other. #[test] - fn lens_profile_swells_smoothly_and_one_sided_profiles_stay_on_their_side() { - // Each half of the lens rises on a cubic from 0 to full width, flat at the middle: it - // covers 7/12 of the full-width band (a diamond would cover half). + fn lens_profile_is_a_smooth_bump_and_one_sided_profiles_stay_on_their_side() { let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01)); - assert!((a - 1000.0 * 7.0 / 12.0).abs() < 0.5, "{a}"); + assert!((a - 2000.0 / 3.0).abs() < 0.1, "{a}"); let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] }; let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01); assert!((area(&o) - 500.0).abs() < 1e-6); @@ -453,41 +889,103 @@ mod tests { assert!(a.is_finite() && (a - 3000.0).abs() < 150.0, "{a}"); } - /// #5714: between width points a straight run follows the profile's smooth curve, not a - /// straight line from one width to the next. #[test] - fn a_straight_run_follows_the_curve_between_width_points() { - // 5 pt either side at the ends, 15 pt at the middle: a quarter of the way along the curve - // is at 2.25 × 5 = 11.25 pt (a straight ramp would be at 10 pt). - let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 3.0), (1.0, 1.0, 1.0)] }; - let o = width_outline(&line(), 10.0, &p, &capped(LineCap::Butt), 0.01); - for y in [-11.0, 11.0] { - assert!(o.contains(kurbo::Point::new(25.0, y)), "inside at y {y}"); - } - for y in [-11.5, 11.5] { - assert!(!o.contains(kurbo::Point::new(25.0, y)), "outside at y {y}"); - } - // Round the widest point the side is flat: no corner sticks out above 15 pt. - let bb = o.bounding_box(); - assert!((bb.y0 + 15.0).abs() < 1e-6 && (bb.y1 - 15.0).abs() < 1e-6, "{bb:?}"); + fn a_closed_path_steps_where_its_profile_ends_differ() { + let mut sq = BezPath::new(); + sq.move_to((0.0, 0.0)); + sq.line_to((100.0, 0.0)); + sq.line_to((100.0, 100.0)); + sq.line_to((0.0, 100.0)); + sq.close_path(); + // 5 pt at the seam's start, 10 pt at its end: the ring must step between them, not + // stretch the last width point round the corner. + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 2.0, 2.0)] }; + let o = width_outline(&sq, 10.0, &p, &capped(LineCap::Butt), 0.01); + let at = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let step = o.elements().windows(2).any(|w| match (w[0], w[1]) { + (PathEl::MoveTo(a), PathEl::LineTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => { + at(a, -10.0, -10.0) && at(b, -5.0, -5.0) || at(a, -5.0, -5.0) && at(b, -10.0, -10.0) + } + _ => false, + }); + assert!(step, "{o:?}"); } - /// A taper is a straight ramp: its outline gets no samples between the width points. #[test] - fn a_straight_taper_gets_no_samples_between_its_points() { - let o = width_outline(&line(), 10.0, &WidthProfile::taper_end(), &capped(LineCap::Butt), 0.01); - assert_eq!(o.elements().len(), 5, "{:?}", o.elements()); + fn added_samples_follow_the_curve_not_the_flattened_chord() { + // A cubic with a tight S: its chords are far from its tangents. A sample inserted inside a + // chord must take the curve's direction there; the chord's direction is what made a wide + // profile scallop at every flatten vertex. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((0.0, 120.0), (120.0, -120.0), (120.0, 0.0)); + let segs = segments(b.elements()); + let flat = flatten(&segs, false, 2.0); + assert!(flat.pts.len() >= 3); + let mut marks = vec![]; + let mut acc = 0.0; + for i in 0..flat.pts.len() - 1 { + let len = flat.pts[i].distance(flat.pts[i + 1]); + marks.push(acc + len / 2.0); + acc += len; + } + let (all, _, dirs) = split_at(&flat, false, &marks, &segs); + assert!(all.len() > flat.pts.len()); + let seg = segs[0]; + for (p, d) in all.iter().zip(&dirs) { + let want = tangent(&seg, seg.nearest(*p, 1e-9).t); + assert!(d.dot(want) > 0.999, "{d:?} vs {want:?} at {p:?}"); + } } - /// A profile read from a file may have thousands of points and absurd widths: the samples added - /// between them stay bounded and the outline finite. #[test] - fn samples_between_width_points_are_capped() { - let points = (0..=10_000).map(|i| (i as f64 / 10_000.0, if i % 2 == 0 { 0.0 } else { 1e12 }, 1.0)).collect(); - let o = width_outline(&line(), 10.0, &WidthProfile { points }, &capped(LineCap::Butt), 0.01); - let n = o.elements().len(); - assert!(n < 2 * (2 * 10_001 + MAX_CURVE_SAMPLES) + 64, "{n}"); - assert!(o.bounding_box().area().is_finite()); + fn a_wiggly_profile_on_a_curve_fits_without_kinks() { + // A rapid width change turns the offset sharply; that is not a path corner, so the + // outline must stay tangent-continuous through it (the old turn-angle test did not). + let c = kurbo::Circle::new((0.0, 0.0), 50.0).to_path(1e-3); + let p = WidthProfile { + points: vec![(0.0, 1.0, 1.0), (0.15, 3.0, 0.4), (0.3, 0.2, 2.8), (0.5, 2.5, 0.3), (0.7, 0.4, 2.2), (0.85, 2.0, 0.5), (1.0, 1.0, 1.0)], + }; + let o = width_outline(&c, 10.0, &p, &capped(LineCap::Butt), 0.01); + let mut cursor = None; + let mut prev: Option<Vec2> = None; + let mut kinks = 0; + let mut check = |a: Vec2, b: Vec2| { + let (la, lb) = (a.hypot(), b.hypot()); + if la > 1e-9 && lb > 1e-9 && (a.dot(b) <= 0.0 || a.cross(b).abs() / (la * lb) > 1e-6) { + kinks += 1; + } + }; + for el in o.elements() { + match el { + PathEl::MoveTo(p) => { + cursor = Some(*p); + prev = None; + } + PathEl::LineTo(p) => { + if let Some(q) = cursor { + let d = *p - q; + if let Some(a) = prev { + check(a, d); + } + prev = Some(d); + } + cursor = Some(*p); + } + PathEl::CurveTo(a, b, p) => { + if let Some(q) = cursor { + let d = if a.distance(q) > 1e-9 { *a - q } else { *b - q }; + if let Some(prev) = prev { + check(prev, d); + } + prev = Some(if p.distance(*b) > 1e-9 { *p - *b } else { *p - *a }); + } + cursor = Some(*p); + } + PathEl::QuadTo(_, _) | PathEl::ClosePath => {} + } + } + assert_eq!(kinks, 0, "{o:?}"); } #[test] @@ -512,4 +1010,108 @@ mod tests { let want = 2.0 * std::f64::consts::PI * 50.0 * 10.0; assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); } + + #[test] + fn a_uniform_circle_narrower_than_its_stroke_has_no_hole() { + // Half-width 15 on a radius-5 circle: the inner offset crosses the centre. The constant + // stroke still covers the centre, so the outline must not leave a hole there. + let c = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let o = width_outline(&c, 30.0, &p, &capped(LineCap::Butt), 0.01); + assert!(o.contains(Point::new(0.0, 0.0)), "{o:?}"); + } + + #[test] + fn a_quick_width_change_does_not_overshoot_its_samples() { + // Width falls to a point and comes back, unevenly on either side: the fitted edge must not + // dip past the point (that crossed the other edge and left a scalloped neck). + let mut run = vec![Point::new(0.0, 0.0), Point::new(10.0, -1.0), Point::new(20.0, -0.3)]; + let (mut a, mut b) = (BezPath::new(), BezPath::new()); + a.move_to(run[0]); + b.move_to(run[0]); + smooth_run(&mut a, &run, false, 0.0); + // Reverse the same points: the fit must stay inside the V from either direction too. + run.reverse(); + smooth_run(&mut b, &run, false, 0.0); + for path in [a, b] { + let mut start = Point::ZERO; + for el in path.elements() { + match el { + PathEl::MoveTo(p) => start = *p, + PathEl::CurveTo(c1, c2, p) => { + for c in [c1, c2] { + assert!(c.y >= -1.0 - 1e-9, "{c:?} in {path:?}"); + assert!(c.y <= start.y.max(p.y) + 1e-9, "{c:?} in {path:?}"); + } + start = *p; + } + _ => {} + } + } + } + } + + #[test] + fn added_samples_stay_on_their_flattened_branch() { + // This cubic loops back near itself. At a coarse tolerance a chord midpoint can be closer + // to the other branch; a full-segment nearest would then take that branch's tangent and + // spike the offset. Each inserted sample must use the parameter range of its own piece. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((150.0, 100.0), (-50.0, 100.0), (100.0, 0.0)); + let segs = segments(b.elements()); + let seg = segs[0]; + let flat = flatten(&segs, false, 2.0); + let mut acc = 0.0; + let mut divergent = 0; + for i in 0..flat.pts.len() - 1 { + let len = flat.pts[i].distance(flat.pts[i + 1]); + if len <= 1e-12 { + continue; + } + let (t0, t1) = flat.param[i]; + let sub = seg.subsegment(t0..t1); + for k in 1..16 { + let (out, _, dirs) = split_at(&flat, false, &[acc + len * k as f64 / 16.0], &segs); + assert!(out.len() >= i + 2, "no sample inserted in piece {i}"); + let p = out[i + 1]; + let want = tangent(&seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t); + assert!(dirs[i + 1].dot(want) > 0.999, "piece {i}, k {k}: {:?} vs {want:?}", dirs[i + 1]); + let full = tangent(&seg, seg.nearest(p, 1e-9).t); + if full.dot(want) < 0.9 { + divergent += 1; + } + } + acc += len; + } + assert!(divergent > 0, "the fixture did not cross the other branch"); + } + + #[test] + fn a_coarse_wide_circle_keeps_its_offset() { + // A wide stroke flattened coarsely: offsetting each flattened segment by its miter + // (`w / cos(θ/2)`) scalloped the circle outward at every sample. Smooth points follow the + // curve's normal instead, so the ring is the annulus between radii 10 and 30. + let c = kurbo::Circle::new((0.0, 0.0), 20.0).to_path(0.5); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let a = area(&width_outline(&c, 20.0, &p, &capped(LineCap::Butt), 0.5)); + let want = std::f64::consts::PI * (30.0 * 30.0 - 10.0 * 10.0); + assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); + } + + #[test] + fn profiled_outlines_stay_compact() { + // A smooth profile is fitted with cubics, so it must not turn every profile sample into + // exported path data. Compare it with the same curved path's uniform outline. + let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01); + let count = |points| { + let p = WidthProfile { points }; + width_outline(&circle, 5.0, &p, &capped(LineCap::Butt), 0.01).elements().len() + }; + let uniform = count(vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]); + let lens = count(WidthProfile::lens().points); + let wave = count(vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)]); + assert!(lens <= uniform * 3 / 2, "lens {lens} vs uniform {uniform}"); + assert!(wave <= uniform * 3 / 2, "wave {wave} vs uniform {uniform}"); + } } diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 532251bd73..e63b38a462 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -209,6 +209,57 @@ fn warp_arc_bends_the_top_edge() { assert!(b.x0 < -1.0 || b.x1 > 101.0, "{b:?}"); } +/// A Warp of `version` 1 bends its bounds as its style's Bézier net; one without a version, as +/// saved before the version existed, draws as it always did. Flag at 60 % on a 200 × 100 box: the +/// net moves the top edge up to 6 × 0.6 × 100 × max u(1 - u)(1 - 2u) = 34.64 out, the earlier map +/// moves it 0.6 × 25 = 15. +#[test] +fn a_warp_draws_with_the_map_its_version_names() { + let rect = shapes::rectangle(Rect::new(10.0, 20.0, 210.0, 120.0)); + // u(1 - u)(1 - 2u) peaks at √3 / 18. + let peak = 360.0 * 3f64.sqrt() / 18.0; + for (version, out) in [(json!(1), peak), (json!(null), 15.0), (json!(0), 15.0)] { + let b = run("warp.flag", json!({"bend": 60, "version": version}), &rect).bounds().unwrap(); + assert!(close(b.y0, 20.0 - out, 0.1) && close(b.y1, 120.0 + out, 0.1), "version {version}: {b:?}"); + assert!(close(b.x0, 10.0, 1e-9) && close(b.x1, 210.0, 1e-9), "version {version}: {b:?}"); + } +} + +/// A straight line has a box with no width or no height, and the net bends it as the middle of +/// the patch along that side: under Arc a vertical line stays vertical, and under Bulge, Fisheye, +/// Inflate and Squeeze a horizontal line stays straight. +#[test] +fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() { + let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::<Vec<_>>(); + let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0)); + let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical); + assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); + let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0)); + for style in ["bulge", "fisheye", "inflate", "squeeze"] { + let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal); + assert!( + anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), + "{style}: {out:?}" + ); + } +} + +/// A new Warp takes the nets' version unless one is given, and the catalog's defaults carry none, +/// so a saved warp's params don't gain one. +#[test] +fn new_warps_take_the_nets_version() { + for (s, _) in WARP_STYLES { + let id = format!("warp.{s}"); + let Some(e) = crate::new_effect(&id, &json!({"bend": 20})) else { panic!("{id}") }; + assert_eq!(e.params["version"], json!(crate::WARP_NET), "{id}"); + let Some(e) = crate::new_effect(&id, &json!({"version": 0})) else { panic!("{id}") }; + assert_eq!(e.params["version"], json!(0), "{id}"); + assert!(crate::merged_params(&id, &json!({"bend": 20})).get("version").is_none(), "{id}"); + } + let Some(e) = crate::new_effect("distort.twist", &json!({})) else { panic!("twist") }; + assert!(e.params.get("version").is_none()); +} + #[test] fn transform_copies_and_move() { let out = run("distort.transform", json!({"moveH": 20, "copies": 3}), &square()); @@ -318,6 +369,317 @@ fn stacked_transform_copies_stay_within_the_image_budget() { assert_eq!(count(&evaluate_container(None, &g).unwrap()), 1001); } +/// A 40 × 40 px image placed at (0, 0) at one point a pixel, with id `id`. +fn warp_test_image(id: u64) -> std::sync::Arc<Node> { + use vectorcraft_doc::{ImageObject, NodeId}; + let im = ImageObject { key: "k".into(), width: 40, height: 40, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + std::sync::Arc::new(Node::new(NodeId(id), NodeKind::Image(Box::new(im)))) +} + +/// How many images `art` holds, and the keys they have. +fn warp_test_images(art: &Node) -> (usize, std::collections::BTreeSet<String>) { + let (mut n, mut keys) = (0, std::collections::BTreeSet::new()); + art.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + n += 1; + keys.insert(im.key.clone()); + } + }); + (n, keys) +} + +#[test] +fn warped_images_stay_within_the_object_budget() { + use std::rc::Rc; + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1)); + let cost = vectorcraft_doc::live::mesh_warp_cost(crate::reshape::WARP_IMAGE_CELLS); + let none = std::collections::HashSet::new(); + let k = || std::collections::BTreeSet::from(["k".to_string()]); + let warp = |art: &mut Node, warps: usize| { + let mut warped = crate::reshape::WarpedImages::new(); + for _ in 0..warps { + crate::reshape::mark_warped_images(art, &lift, &none, false, &mut 0, &mut warped); + } + warped + }; + // The art has room for one image's pieces only: neither image is cut, and each gets its own + // key back. + let mut art = Node::group(NodeId(1), vec![warp_test_image(2), warp_test_image(3)]); + let warped = warp(&mut art, 1); + let max = art.count() + cost; + crate::reshape::cut_warped_images_within(&mut art, &warped, max); + assert_eq!(warp_test_images(&art), (2, k())); + // With room for both, each is cut into 200 pieces once, however many warps it took. + let mut art = Node::group(NodeId(1), vec![warp_test_image(2), warp_test_image(3)]); + let warped = warp(&mut art, 3); + let max = art.count() + 2 * cost; + crate::reshape::cut_warped_images_within(&mut art, &warped, max); + assert_eq!(warp_test_images(&art), (400, k())); + // Images clipped by their frames: the second frame (the second path) kept its shape, so its + // image stays whole, and the first is cut. The third's frame is a group of two paths, the + // second of them kept, with an image after them, and its image sits in a group of its own: + // both stay whole too. + let frame = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Default::default())); + let clip_group = |id: u64, children: Vec<Arc<Node>>| Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: true })); + let nested = clip_group( + 4, + vec![ + Arc::new(Node::group(NodeId(4), vec![frame(4), frame(4), warp_test_image(5)])), + Arc::new(Node::group(NodeId(4), vec![warp_test_image(4)])), + ], + ); + let mut art = + Node::group(NodeId(1), vec![clip_group(2, vec![frame(2), warp_test_image(2)]), clip_group(3, vec![frame(3), warp_test_image(3)]), nested]); + let (mut at, mut warped) = (0, crate::reshape::WarpedImages::new()); + crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::from([1, 3]), false, &mut at, &mut warped); + assert_eq!(at, 4); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(warp_test_images(&art), (203, k())); +} + +/// An image key from the document that looks like a key of the table is not read as one, and a +/// hidden image stays out of the bounds the later effects take, as it does before it is warped. +#[test] +fn warped_images_keep_document_keys_and_hidden_images_apart() { + use std::rc::Rc; + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1)); + let none = std::collections::HashSet::new(); + let mut warped = crate::reshape::WarpedImages::new(); + let lookalike = format!("{}0", warped.prefix()); + let mut b = (*warp_test_image(3)).clone(); + if let NodeKind::Image(im) = &mut b.kind { + im.key = lookalike.clone(); + } + let mut art = Node::group(NodeId(1), vec![warp_test_image(2), Arc::new(b)]); + warped.reserve(&art); + crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(warp_test_images(&art), (400, std::collections::BTreeSet::from(["k".to_string(), lookalike]))); + // A layer of a 10 × 10 square and a hidden 40 × 40 image: the warped image is not measured. + let square = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default())); + let mut hidden = (*warp_test_image(5)).clone(); + hidden.visible = false; + let mut layer = Node::layer(NodeId(6), "Layer 1", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + *children = vec![square, Arc::new(hidden)]; + } + let before = layer.geometric_bounds(); + let mut warped = crate::reshape::WarpedImages::new(); + warped.reserve(&layer); + crate::reshape::mark_warped_images(&mut layer, &lift, &none, false, &mut 0, &mut warped); + assert_eq!(warped.bounds(&layer), before); + // A shown image is measured by the pieces it is cut into. + let mut art = Node::group(NodeId(1), vec![warp_test_image(2)]); + let mut warped = crate::reshape::WarpedImages::new(); + warped.reserve(&art); + crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped); + let measured = warped.bounds(&art); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(measured, art.geometric_bounds()); + assert!(measured.is_some_and(|b| b.y0 < -3.9), "{measured:?}"); + // An image placed at a tiny scale (a placement with a tiny determinant) is cut too; one placed + // with no area is not. + for (scale, pieces) in [(1e-7, 200), (0.0, 1)] { + let mut image = (*warp_test_image(2)).clone(); + if let NodeKind::Image(im) = &mut image.kind { + im.xf = Affine::scale(scale); + } + let mut art = Node::group(NodeId(1), vec![Arc::new(image)]); + let mut warped = crate::reshape::WarpedImages::new(); + crate::reshape::mark_warped_images(&mut art, &lift, &none, false, &mut 0, &mut warped); + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + assert_eq!(warp_test_images(&art).0, pieces, "{scale}"); + } +} + +/// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its +/// pixels as they are; within the budget, both bend. +#[test] +fn an_image_whose_frame_passes_the_budget_stays_whole() { + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let clipped = || { + let mut frame = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut frame.kind { + *clipping = true; + } + Node::new(NodeId(1), NodeKind::Group { children: vec![Arc::new(frame), warp_test_image(1)], clip: true }) + }; + let arc = fx("warp.arc", json!({"bend": 50, "version": 1})); + let k = || std::collections::BTreeSet::from(["k".to_string()]); + let mut art = clipped(); + crate::reshape::reshape_leaves_within(&mut art, &[&arc], Budget { anchors: 0, lines: 0 }, None); + assert_eq!(art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).map(|p| p.anchor_count()), Some(4)); + assert_eq!(warp_test_images(&art), (1, k())); + let mut art = clipped(); + crate::reshape::reshape_leaves_within(&mut art, &[&arc], Budget::EFFECTS, None); + assert!(art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).is_some_and(|p| p.anchor_count() > 4)); + assert_eq!(warp_test_images(&art), (200, k())); +} + +/// The first image under `n` (the first piece of a cut image). +fn first_image(n: &Node) -> Option<vectorcraft_doc::ImageObject> { + let mut first = None; + n.walk(&mut |c| { + if first.is_none() + && let NodeKind::Image(im) = &c.kind + { + first = Some((**im).clone()); + } + }); + first +} + +#[test] +fn effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces() { + let image = |effects: Vec<Effect>| { + let mut n = (*warp_test_image(1)).clone(); + n.appearance.effects = effects; + n + }; + // Each piece's clipping path, and the image's frame (the outer clip group's clipping path). + let clips = |art: &Node| { + let (mut pieces, mut frame) = (vec![], None); + art.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let Some(path) = children.first().and_then(|p| p.path_data()) + { + if matches!(children.get(1).map(|i| &i.kind), Some(NodeKind::Image(_))) && path.anchor_count() == 3 { + pieces.push(path.anchor_count()); + } else if frame.is_none() { + frame = Some(path.anchor_count()); + } + } + }); + (pieces, frame) + }; + let arc = fx("warp.arc", json!({"bend": 50, "version": 1})); + for after in [ + fx("distort.roughen", json!({"size": 5, "detail": 10})), + fx("stylize.roundCorners", json!({"radius": 5})), + fx("path.offsetPath", json!({"offset": -2})), + ] { + let art = crate::reshape::reshape(None, &image(vec![arc.clone(), after.clone()]), None).unwrap(); + let (pieces, frame) = clips(&art); + assert_eq!(pieces.len(), 200, "{}", after.id); + assert!(frame.is_some_and(|n| n > 4), "{}: {frame:?}", after.id); + assert_eq!(warp_test_images(&art), (200, std::collections::BTreeSet::from(["k".to_string()])), "{}", after.id); + } + // Two warps cut the image once, through both maps; a Transform after them moves the pieces. + let flag = fx("warp.flag", json!({"bend": 30, "version": 1})); + let mv = fx("distort.transform", json!({"moveH": 100, "moveV": 0})); + let art = crate::reshape::reshape(None, &image(vec![arc.clone(), flag.clone()]), None).unwrap(); + assert_eq!(warp_test_images(&art).0, 200); + let moved = crate::reshape::reshape(None, &image(vec![arc.clone(), flag.clone(), mv]), None).unwrap(); + assert_eq!(warp_test_images(&moved).0, 200); + let box1 = Rect::new(0.0, 0.0, 40.0, 40.0); + let f1 = crate::warp::warp_map(box1, crate::warp::WarpStyle::Arc, &merged_params("warp.arc", &arc.params)); + // The flag bends the box the arc leaves, which the arc's frame measures. + let box2 = crate::reshape::reshape(None, &image(vec![arc.clone()]), None).unwrap().geometric_bounds().unwrap(); + let f2 = crate::warp::warp_map(box2, crate::warp::WarpStyle::Flag, &merged_params("warp.flag", &flag.params)); + // The first piece's corners: the pixels (0, 0), (4, 0) and (4, 4). + for (art, by) in [(&art, 0.0), (&moved, 100.0)] { + let piece = first_image(art).unwrap(); + for p in [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0)] { + let want = f2(f1(p)) + vectorcraft_geom::Vec2::new(by, 0.0); + assert!((piece.xf * p).distance(want) < 1e-6, "{p:?}: {:?} {want:?}", piece.xf * p); + } + } +} + +/// A warp with no version (VectorCraft's earlier map) bends an image's pixels with that map, as it +/// bends the frame. +#[test] +fn an_images_pixels_take_the_map_their_warps_version_names() { + for version in [json!(null), json!(0), json!(1)] { + let mut params = json!({"bend": 50}); + if !version.is_null() { + params["version"] = version.clone(); + } + let mut n = (*warp_test_image(1)).clone(); + n.appearance.effects = vec![fx("warp.arc", params.clone())]; + let art = crate::reshape::reshape(None, &n, None).unwrap(); + let f = crate::warp::warp_map(Rect::new(0.0, 0.0, 40.0, 40.0), crate::warp::WarpStyle::Arc, &merged_params("warp.arc", ¶ms)); + let piece = first_image(&art).unwrap(); + for p in [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0)] { + assert!((piece.xf * p).distance(f(p)) < 1e-6, "{version}: {p:?}"); + } + // The frame has an anchor where the map takes each corner. + let frame = art.children().and_then(|c| c.first()).and_then(|c| c.path_data()).unwrap(); + for corner in [Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(40.0, 40.0), Point::new(0.0, 40.0)] { + let near = frame.subpaths.iter().flat_map(|s| &s.anchors).any(|a| a.p.distance(f(corner)) < 1e-6); + assert!(near, "{version}: {corner:?}"); + } + } +} + +/// Under a group's Warp effect, a nested group's own placed gradient follows the nested group's +/// bounds to where its image's pieces draw them. +#[test] +fn a_nested_groups_gradient_follows_its_warped_image() { + use std::sync::Arc; + + use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, NodeId}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let geom = GradientGeom { start: (5.0, 20.0).into(), end: (35.0, 20.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let mut inner = Node::group(NodeId(5), vec![warp_test_image(1)]); + inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed))); + let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(60.0, 0.0, 100.0, 40.0)), Appearance::default()); + let mut g = Node::group(NodeId(10), vec![Arc::new(inner), Arc::new(square)]); + g.appearance.effects.push(fx("warp.arc", json!({"bend": 50, "version": 1}))); + let art = crate::group::evaluate_container(None, &g).unwrap(); + assert_eq!(warp_test_images(&art).0, 200); + let (from, mut to) = (Rect::new(0.0, 0.0, 40.0, 40.0), None); + art.walk(&mut |c| { + if c.id == NodeId(5) && to.is_none() { + to = c.geometric_bounds(); + } + }); + let to = to.unwrap(); + assert!(to.y0 < from.y0 - 1.0, "the pieces draw the image bent: {to:?}"); + let follow = |p: Point| Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height()); + let mut checked = 0; + art.walk(&mut |c| { + if c.id != NodeId(5) { + return; + } + for item in &c.appearance.items { + let Paint::Gradient(gp) = item.paint() else { continue }; + let got = gp.geom.unwrap(); + assert!(got.start.distance(follow(geom.start)) < 1e-6 && got.end.distance(follow(geom.end)) < 1e-6, "{got:?} in {to:?}"); + checked += 1; + } + }); + assert!(checked > 0); +} + +/// An image under a geometry effect other than a Warp draws as the image does: colorized by +/// a grayscale image's fill color, and smoothed or not. +#[test] +fn an_image_under_a_geometry_effect_keeps_its_color_and_smoothing() { + let mut n = (*warp_test_image(1)).clone(); + n.appearance.effects = vec![fx("distort.roughen", json!({"size": 5, "detail": 10}))]; + n.extras_mut().colorize = Some(Box::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + n.extras_mut().pixelated = true; + let art = crate::reshape::reshape(None, &n, None).unwrap(); + let mut seen = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Image(_)) { + seen.push((c.extras().colorize.clone(), c.extras().pixelated)); + } + }); + assert_eq!(seen, vec![(n.extras().colorize.clone(), true)]); +} + /// What `effects` make of `path` within `budget`. fn within(effects: &[Effect], path: &PathData, budget: Budget) -> PathData { apply_geometry_within(effects, path, path.bounds().unwrap(), &GeomContext::default(), budget) diff --git a/crates/effects/src/warp.rs b/crates/effects/src/warp.rs index 84f196a8b4..4b117d4142 100644 --- a/crates/effects/src/warp.rs +++ b/crates/effects/src/warp.rs @@ -1,25 +1,49 @@ //! Warp effects: 15 envelope styles plus horizontal/vertical perspective distortion. //! -//! Each style is a map on normalised box coordinates (x, y) ∈ [-1, 1]² (y down). The path is -//! split into short pieces whose control points are mapped (see `map_nonlinear`). +//! A warp with `version` [`WARP_NET`] is its style's Bézier patch over the box ([`WarpNet`]); +//! one without (saved before the version existed) is a map on normalized box coordinates +//! (x, y) ∈ [-1, 1]² (y down), [`warp_point`]. The path is split into short pieces whose control +//! points are mapped (see `map_nonlinear`). use serde_json::Value; use vectorcraft_geom::{PathData, Point, Rect}; use crate::util::{map_nonlinear_within, num, text}; -pub use vectorcraft_doc::live::{WarpStyle, warp_point}; +pub use vectorcraft_doc::live::{WARP_NET, WarpNet, WarpStyle, uses_net, warp_point, warp_version}; + +/// The map version warp params `p` ask for: their `version`, 0 (the first map) when absent. +pub fn map_version(p: &Value) -> u32 { + let v = num(p, "version", 0.0); + if v.is_finite() && v >= 0.0 { v.min(f64::from(u32::MAX)) as u32 } else { 0 } +} /// Apply a warp to `path` using box `b`, making at most `max` anchors ([`map_nonlinear_within`]). pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -> PathData { + let piece = b.width().hypot(b.height()) / 24.0; + map_nonlinear_within(path, piece, max, warp_map(b, style, p)) +} + +/// The point map a warp of `style` with params `p` applies to box `b`: what [`warp`] moves each +/// point of a path to. +pub(crate) fn warp_map(b: Rect, style: WarpStyle, p: &Value) -> Box<dyn Fn(Point) -> Point> { let bend = num(p, "bend", 50.0).clamp(-100.0, 100.0) / 100.0; let dh = num(p, "horizontal", 0.0).clamp(-100.0, 100.0) / 100.0; let dv = num(p, "vertical", 0.0).clamp(-100.0, 100.0) / 100.0; let vertical = text(p, "orientation", "horizontal").eq_ignore_ascii_case("vertical"); + if uses_net(map_version(p)) { + let net = WarpNet::new(style, bend, dh, dv, b.width(), b.height(), vertical); + let (w, h) = (b.width(), b.height()); + // A box with no width or no height takes the middle of the patch along that side. + return Box::new(move |q: Point| { + let (u, v) = (if w > 0.0 { (q.x - b.x0) / w } else { 0.5 }, if h > 0.0 { (q.y - b.y0) / h } else { 0.5 }); + b.origin() + net.at(u, v).to_vec2() + }); + } let c = b.center(); let hw = (b.width() / 2.0).max(1e-9); let hh = (b.height() / 2.0).max(1e-9); - let f = |q: Point| { + Box::new(move |q: Point| { let (x, y) = ((q.x - c.x) / hw, (q.y - c.y) / hh); let (x2, y2) = if vertical { let (a, b2) = warp_point(style, bend, dh, dv, hw / hh, y, x); @@ -28,18 +52,17 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) - warp_point(style, bend, dh, dv, hh / hw, x, y) }; Point::new(c.x + x2 * hw, c.y + y2 * hh) - }; - let piece = b.width().hypot(b.height()) / 24.0; - map_nonlinear_within(path, piece, max, f) + }) } /// Does warp effect `id` with params `p` move any point? Every style leaves the box as it is with -/// no bend and no distortion, and Arc (`warp.arc`) takes a bend under 0.0001 % as none: the -/// threshold must match the one in [`warp_point`]'s Arc case (`warp_bends_when_the_warp_moves_the_outline` -/// tests both sides of it). +/// no bend and no distortion. With the first map, Arc (`warp.arc`) takes a bend under 0.0001 % as +/// none: the threshold must match the one in [`warp_point`]'s Arc case +/// (`warp_bends_when_the_warp_moves_the_outline` tests both sides of it). With [`WarpNet`] any +/// bend moves the outline. pub(crate) fn bends(id: &str, p: &Value) -> bool { let share = |key: &str, default: f64| num(p, key, default).clamp(-100.0, 100.0) / 100.0; let bend = share("bend", 50.0); - let bent = if id == "warp.arc" { bend.abs() >= 1e-6 } else { bend != 0.0 }; + let bent = if id == "warp.arc" && !uses_net(map_version(p)) { bend.abs() >= 1e-6 } else { bend != 0.0 }; bent || share("horizontal", 0.0) != 0.0 || share("vertical", 0.0) != 0.0 } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 836d4b7448..0fccbcdecb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -67,6 +67,11 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). +# Already in Cargo.lock (walkdir), so this adds no new crate. +[target.'cfg(windows)'.dependencies] +same-file = "1.0.6" + # The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c76492f454..465025302f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -507,6 +507,23 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt Some(v) => Ok(Some(vec![checked_id(s, v, command)?])), } } +/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form: +/// for a command that looks its objects up itself, outside the document's layers too. +pub(crate) fn given_object_ids(p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + return ids_param(p, "ids", command); + } + match p.get("id").filter(|v| !v.is_null()) { + None => Ok(None), + Some(Value::String(r)) if r.starts_with('$') => { + Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))) + } + Some(v) => { + let id = v.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {v}: expected a non-negative integer")))?; + Ok(Some(vec![id])) + } + } +} /// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list. pub(crate) fn index(v: u64) -> usize { usize::try_from(v).unwrap_or(usize::MAX) @@ -519,17 +536,23 @@ pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str } /// The objects a command acts on: `ids` when given (every one checked, and those inside another -/// given one dropped), else the selected objects. +/// given one dropped), else (`ids` left out or null) the selected objects. pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> { - if p.get("ids").is_some() { Ok(edit::outermost(&s.doc()?.doc, checked_ids_param(s, p, "ids", command)?)) } else { edit::selected_roots(s) } + if p.get("ids").is_some_and(|v| !v.is_null()) { + Ok(edit::outermost(&s.doc()?.doc, checked_ids_param(s, p, "ids", command)?)) + } else { + edit::selected_roots(s) + } } pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> { let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?; - if s.doc()?.doc.node(id).is_none() { - return Err(bad(command, format!("no such object id {value}"))); + match s.doc()?.doc.node(id) { + None => Err(bad(command, format!("no such object id {value}"))), + // The guide commands take ruler guides by index. + Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))), + Some(_) => Ok(id), } - Ok(id) } /// `v` as exactly `N` finite numbers (`[x, y]`, `[x, y, width, height]`…): `None` when it isn't an @@ -689,10 +712,11 @@ pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> { let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns)); let mut out = vec![]; for id in ids { - let Some(n) = d.node(*id) else { continue }; + // A ruler guide has no appearance to paint, given or in a layer. + let Some(n) = d.node(*id).filter(|n| !n.is_ruler_guide()) else { continue }; match &n.kind { NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| { - if !c.is_container() || owns(c) { + if (!c.is_container() && !c.is_ruler_guide()) || owns(c) { out.push(c.id) } }), @@ -742,6 +766,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< /// The most presets one presets file imports: each is looked up among the saved ones. pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; +pub(crate) use addons::DecodedImages; +pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 324d7bde58..0815404835 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -5,13 +5,17 @@ mod arrange; mod cleanup; mod color; mod contour; +mod cutting; mod document; +mod image; mod pathtools; mod pen; mod select; mod shapes; mod typetools; +pub(crate) use image::DecodedImages; + use super::CommandSpec; /// The commands of every built-in add-on. @@ -20,7 +24,9 @@ pub fn specs() -> Vec<CommandSpec> { v.extend(cleanup::specs()); v.extend(color::specs()); v.extend(contour::specs()); + v.extend(cutting::specs()); v.extend(document::specs()); + v.extend(image::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs index dfb450faed..4fd1f1ce96 100644 --- a/crates/engine/src/cmd/addons/cleanup/checks.rs +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -185,7 +185,7 @@ fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> { } fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) { - if !n.visible || n.locked || out.len() >= MAX_OBJECTS { + if !n.visible || n.locked || n.is_ruler_guide() || out.len() >= MAX_OBJECTS { return; } let inner = |clip: bool, i: usize, top: bool| Place { clips: clip && i == 0, top, in_compound: false }; @@ -216,7 +216,7 @@ fn is_generated(n: &Node) -> bool { } fn is_guide_or_clip(n: &Node) -> bool { - matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. }) + n.is_guide() || matches!(n.kind, NodeKind::Path { clipping: true, .. }) } fn is_shape(n: &Node) -> bool { @@ -484,7 +484,7 @@ fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result<Out if i < d.artboards.len() { let id = d.artboards.remove(i).id; d.retire_artboard_id(id); - d.retain_guides(sel, |_, g| g.artboard != Some(id)); + d.retain_guides(sel, |g| g.artboard != Some(id)); } } Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty }) diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 6e6abfaa48..10fd432dfc 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -806,7 +806,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> { }; // 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 editing = if p.get("ids").is_some_and(|v| !v.is_null()) { 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; // Each type object with the breaks that go from it. diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index 27d0233bb6..0af24be36a 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -125,6 +125,30 @@ fn break_area_type_into_lines_paragraphs_and_glyphs() { } } +/// Tracked area type broken into lines or paragraphs stays where it was, however it is aligned: +/// a wrap after a hyphen or at a space becomes a line break or a paragraph's end, and the line +/// leaves the tracking after its last character out of its width there as it did at the wrap. +/// (Words chosen without a kerning pair across the wrap, which the pieces don't keep.) +#[test] +fn break_tracked_area_type_keeps_its_aligned_lines_in_place() { + for justify in ["center", "right"] { + for text_of in ["Mode-Mode-Mode", "Wave Wave Wave"] { + for by in ["paragraphs", "lines"] { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 40, "text": text_of, "size": 20, "area": {"width": 90, "height": 200}})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": 200})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": justify})).unwrap(); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(&s, id)); + assert!(lay.lines.len() > 1, "{text_of}: it wraps"); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let pieces = ids(&s.execute("addon.cleanup.breakText", &json!({"by": by})).unwrap()); + assert_same_places(&was, &glyphs(&s, &pieces)); + } + } + } +} + #[test] fn break_text_refuses_what_it_cannot_break() { let mut s = session(); @@ -264,6 +288,18 @@ fn remove_breaks_in_the_characters_a_type_tool_selected() { assert_eq!(obj(&s, id).plain_text(), "a b\nc"); } +/// `ids: null` is `ids` left out: the characters the Type tool selected lose their breaks, and +/// the rest of the text keeps them. +#[test] +fn remove_breaks_with_ids_null_in_the_characters_a_type_tool_selected() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb\nc", "size": 12})); + select(&mut s, &[id]); + edit_text(&mut s, id, 0, 2); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": null})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "a b\nc"); +} + #[test] fn split_at_the_cursor_and_around_a_selection() { for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] { diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs index 7a4cfee9c4..a0dd332fec 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -107,7 +107,7 @@ impl Fixes { let white = usize::from(self.remove_white_overprint && self.unset_white(n)); let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_))); let mut counts = (white, usize::from(blacks && black.apply(n, spots))); - for c in n.children_mut().into_iter().flatten() { + for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { let (w, b) = self.overprint(Arc::make_mut(c), black, spots); counts = (counts.0 + w, counts.1 + b); } diff --git a/crates/engine/src/cmd/addons/cutting.rs b/crates/engine/src/cmd/addons/cutting.rs new file mode 100644 index 0000000000..8412af9a68 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting.rs @@ -0,0 +1,11 @@ +//! Cutting Tools (`addon.cutting.*`), a built-in add-on that prepares art for cutting. Stencil +//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together +//! ([`stencil`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialog are the UI's. + +mod stencil; + +use super::super::CommandSpec; + +pub fn specs() -> Vec<CommandSpec> { + stencil::specs() +} diff --git a/crates/engine/src/cmd/addons/cutting/stencil.rs b/crates/engine/src/cmd/addons/cutting/stencil.rs new file mode 100644 index 0000000000..a8b4cfe591 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/stencil.rs @@ -0,0 +1,167 @@ +//! Stencil Bridges (`addon.cutting.bridges`), a command of the built-in Cutting Tools add-on: it +//! cuts bridges out of the selected art so that a stencil cut from it holds together. Each island +//! of the stencil sheet (the inside of an O, a hole in a shape) stays joined to the sheet by strips +//! of a set width across the art (<https://en.wikipedia.org/wiki/Stencil> describes islands and +//! bridges). The art becomes one compound path with the gaps cut, and type is measured by its +//! glyph outlines. The original goes to a new hidden layer or is replaced. The geometry is +//! `vectorcraft_pathops::addons::stencil`. + +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_pathops::addons::stencil::{BRIDGE_WIDTH_RANGE, BridgeDirection, BridgeSpec, MAX_BRIDGES_PER_ISLAND, stencil_bridges}; + +use super::super::super::edit::selected_roots; +use super::super::super::object::choice; +use super::super::super::pathops::{length_given, node_path, pf_leaves, shape_node, style_of}; +use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// Stencil Bridges' command (the id in [`specs`]). +pub const BRIDGES: &str = "addon.cutting.bridges"; +/// The ways bridges run, as `direction` takes them. +pub const DIRECTIONS: [&str; 3] = ["vertical", "horizontal", "shortest"]; +/// A bridge's width when none is given, in points. +pub const DEFAULT_WIDTH: f64 = 2.0; +/// The name of the hidden layer the original art goes to (numbered when it is taken). +const ORIGINAL_LAYER: &str = "Stencil Original"; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "addon.cutting.bridges", + "Stencil Bridges…", + ["Object", "Plug-ins", "Cutting Tools"], + None, + "{width?: pt 0.01..1000 (2), count?: whole number 1..16 of bridges each island gets (1; fewer where it has no room and more where other islands are joined to the sheet through it), direction?: \"vertical\" | \"horizontal\" | \"shortest\" (the shortest crossing among 12 directions 15° apart) (\"vertical\"), keepOriginal?: true (the selected objects that make up the art go to a new hidden layer named \"Stencil Original\"; false: they are replaced)} cut bridges out of the selected art so that a stencil cut from it holds together: every island (an area the art encloses, such as the inside of an O or a hole in a shape) is joined to the area around the art by strips `width` wide across the art, the shortest crossings first, then spread around the island. The art is measured by the area its outlines enclose, whatever their paint (open paths closed as a fill closes them; type by its glyph outlines; groups by their members; hidden objects left out) and becomes one compound path with the gaps cut, painted as the topmost selected shape, in the place of the topmost selected object that has outlines. Selected objects with no outlines in the art stay where they are. Art with no islands, or none a bridge of the width fits, is left as it is, with a warning and no undo step; islands the cut result still encloses are counted in `unbridged`, with a warning. Art that reaches more than 10000000 pt from the origin, has more than 200000 anchors, whose combined area has more than 4000 outlines, whose outlines need more than 200000 straight segments, or that takes more work to measure than a fixed budget allows is refused. One undo step; the new path is selected → {id, islands, bridges, unbridged, original (the hidden layer's id, or null), warning?}", + has_selection, + bridges + )] +} + +fn bridges(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = BRIDGES; + let width = length_given(p, "width", C)?.unwrap_or(DEFAULT_WIDTH); + let (lo, hi) = BRIDGE_WIDTH_RANGE; + if !(lo..=hi).contains(&width) { + return Err(bad(C, format!("`width` must be from {lo} to {hi} pt"))); + } + let count = number_or(p, "count", 1.0, C)?; + if count.fract() != 0.0 || !(1.0..=MAX_BRIDGES_PER_ISLAND as f64).contains(&count) { + return Err(bad(C, format!("`count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND}"))); + } + let direction = match choice(p, C, "direction", &DIRECTIONS)?.unwrap_or("vertical") { + "horizontal" => BridgeDirection::Horizontal, + "shortest" => BridgeDirection::Shortest, + _ => BridgeDirection::Vertical, + }; + let keep = switch_or(p, "keepOriginal", true, C)?; + let selected = selected_roots(s)?; + let (bridged, style, roots) = { + let d = &s.doc()?.doc; + // The art's outlines, the selected objects they come from, and the topmost object that + // has some, whose paint the result takes. + let mut parts: Vec<(PathData, FillRule)> = vec![]; + let mut roots = vec![]; + let mut top = None; + for id in selected { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let mut leaves = vec![]; + shown_leaves(d, n, &mut leaves); + let before = parts.len(); + for leaf in leaves { + if let Some(part) = node_path(&leaf).filter(|(p, _)| !p.is_empty()) { + parts.push(part); + top = Some(leaf); + } + } + if parts.len() > before { + roots.push(id); + } + } + let Some(top) = top else { + let label = "Stencil Bridges"; + return Err(EngineError::Other(format!("{label}: select paths, compound paths, groups or text"))); + }; + let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect(); + let spec = BridgeSpec { width, count: count as usize, direction }; + let bridged = stencil_bridges(&refs, spec).map_err(|e| EngineError::Other(e.to_string()))?; + (bridged, style_of(&top), roots) + }; + let summary = |id: Option<NodeId>, original: Option<NodeId>| { + json!({ + "id": id.map(|i| i.0), "islands": bridged.islands, "bridges": bridged.bridges, "unbridged": bridged.unbridged, + "original": original.map(|i| i.0), + }) + }; + if bridged.islands == 0 { + let mut r = summary(None, None); + // The warnings are written as `EngineError::Other` so that the i18n message scan + // (`untranslated_report`) finds them. + r["warning"] = json!(EngineError::Other("The selected art has no islands to bridge".into()).to_string()); + return Ok(r); + } + if bridged.bridges == 0 { + let mut r = summary(None, None); + r["warning"] = json!(EngineError::Other("No bridge of this width fits across the selected art".into()).to_string()); + return Ok(r); + } + let path = bridged.path.clone(); + let (id, original) = s.edit("Stencil Bridges", |d, sel| { + let mut made = shape_node(d, path, None); + style.apply(&mut made); + let mut taken = vec![]; + let id = d.wrap(&roots, |nodes| { + taken = nodes; + made + })?; + let original = if keep { Some(hide_originals(d, taken)?) } else { None }; + sel.set([id]); + Ok((id, original)) + })?; + let mut r = summary(Some(id), original); + if bridged.unbridged > 0 { + r["warning"] = json!(EngineError::Other("Some islands could not be joined to the area around the art".into()).to_string()); + } + Ok(r) +} + +/// The leaf shapes of `n` as [`pf_leaves`] gives them, leaving out hidden objects and the members +/// of hidden groups. +fn shown_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } if !n.is_compound_shape() => { + for c in children { + shown_leaves(d, c, out); + } + } + _ => pf_leaves(d, n, out), + } +} + +/// Put `nodes` in a new hidden layer above the others, in their order, and return its id. +fn hide_originals(d: &mut Document, nodes: Vec<Arc<Node>>) -> Result<NodeId> { + let mut taken = std::collections::HashSet::new(); + d.walk(|n| { + if n.is_layer() { + taken.extend(n.name.clone()); + } + }); + let name = std::iter::once(ORIGINAL_LAYER.to_string()) + .chain((2..).map(|i| format!("{ORIGINAL_LAYER} {i}"))) + .find(|name| !taken.contains(name)) + .unwrap_or_else(|| ORIGINAL_LAYER.to_string()); + let layer = d.add_layer(Some(&name)); + for (i, n) in nodes.into_iter().enumerate() { + d.insert(Some(layer), i, Arc::unwrap_or_clone(n))?; + } + d.node_mut(layer).ok_or(EngineError::NoNode(layer))?.visible = false; + Ok(layer) +} diff --git a/crates/engine/src/cmd/addons/cutting/stencil/tests.rs b/crates/engine/src/cmd/addons/cutting/stencil/tests.rs new file mode 100644 index 0000000000..ad072ca13d --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/stencil/tests.rs @@ -0,0 +1,328 @@ +//! Tests for `addon.cutting.bridges`: bridges cut out of the selected art keep a stencil's islands +//! attached. + +use kurbo::Shape; +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::super::super::super::pathops::node_path; +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 select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap(); +} + +/// `outer` less each of `holes` (x, y, width, height), as one compound path, selected. +fn shape_with_holes(s: &mut Session, outer: (f64, f64, f64, f64), holes: &[(f64, f64, f64, f64)]) -> NodeId { + let mut ids = vec![rect(s, outer.0, outer.1, outer.2, outer.3)]; + for h in holes { + ids.push(rect(s, h.0, h.1, h.2, h.3)); + } + select(s, &ids); + let r = s.execute("object.pathfinder.minusFront", &json!({})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + select(s, &[id]); + id +} + +/// A square O: 100 pt across at (100, 100), with bars 20 pt thick. +fn letter_o(s: &mut Session) -> NodeId { + shape_with_holes(s, (100.0, 100.0, 100.0, 100.0), &[(120.0, 120.0, 60.0, 60.0)]) +} + +fn id_of(r: &Value) -> NodeId { + NodeId(r["id"].as_u64().unwrap()) +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +/// Is `(x, y)` inside the area object `id` fills? +fn fills(s: &Session, id: NodeId, x: f64, y: f64) -> bool { + let (path, rule) = node_path(&node(s, id)).unwrap(); + let w = path.to_bezpath().winding(kurbo::Point::new(x, y)); + match rule { + vectorcraft_geom::FillRule::EvenOdd => w % 2 != 0, + vectorcraft_geom::FillRule::NonZero => w != 0, + } +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn an_o_gets_a_bridge_and_the_original_goes_to_a_hidden_layer() { + let mut s = session(); + let o = letter_o(&mut s); + let fill = node(&s, o).appearance.fill_paint(); + let steps = undo_steps(&s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(1), json!(0))); + assert!(r.get("warning").is_none(), "{r}"); + let made = id_of(&r); + assert_eq!(s.doc().unwrap().selection.objects, vec![made]); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + // The bridge crosses the top bar in the middle; the rest of the O stays, painted as it was. + assert!(!fills(&s, made, 150.0, 110.0)); + assert!(fills(&s, made, 130.0, 110.0) && fills(&s, made, 150.0, 190.0) && fills(&s, made, 110.0, 150.0)); + assert_eq!(node(&s, made).appearance.fill_paint(), fill); + // The original, unchanged, is on a new hidden layer. + let layer = NodeId(r["original"].as_u64().unwrap()); + let l = node(&s, layer); + assert_eq!((l.name.as_deref(), l.visible), (Some("Stencil Original"), false)); + let held = s.doc().unwrap().doc.children(Some(layer)).map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()); + assert_eq!(held, Some(vec![o])); + // The island is joined to the sheet: the result has none left. + let again = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!(again["islands"], json!(0)); + assert!(again["warning"].as_str().is_some_and(|w| w.contains("no islands")), "{again}"); + assert_eq!(undo_steps(&s), steps + 1, "no islands: no undo step"); + // Undo puts the O back where it was and takes the layer away. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(layer).is_none() && d.node(made).is_none() && d.node(o).is_some_and(|n| n.visible)); +} + +#[test] +fn keep_original_off_replaces_the_art() { + let mut s = session(); + let o = letter_o(&mut s); + let layers = s.doc().unwrap().doc.layers.len(); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": false})).unwrap(); + assert_eq!(r["original"], Value::Null); + let d = &s.doc().unwrap().doc; + assert!(d.node(o).is_none() && d.node(id_of(&r)).is_some()); + assert_eq!(d.layers.len(), layers); +} + +#[test] +fn the_bridge_is_as_wide_as_asked() { + for width in [2.0, 8.0] { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": width})).unwrap(); + let made = id_of(&r); + let half = width / 2.0; + assert!(!fills(&s, made, 150.0 - half * 0.9, 110.0) && !fills(&s, made, 150.0 + half * 0.9, 110.0), "{width}"); + assert!(fills(&s, made, 150.0 - half * 1.2, 110.0) && fills(&s, made, 150.0 + half * 1.2, 110.0), "{width}"); + } +} + +#[test] +fn the_width_takes_units() { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": "2 mm"})).unwrap(); + let made = id_of(&r); + // 2 mm is about 5.67 pt. + assert!(!fills(&s, made, 152.5, 110.0) && fills(&s, made, 154.0, 110.0)); +} + +#[test] +fn the_shortest_crossing_takes_the_thinnest_bar() { + let mut s = session(); + // The left bar is 5 pt thick, the others 20. + shape_with_holes(&mut s, (100.0, 100.0, 100.0, 100.0), &[(105.0, 120.0, 75.0, 60.0)]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "direction": "shortest"})).unwrap(); + let made = id_of(&r); + assert!(!fills(&s, made, 102.5, 150.0), "the bridge crosses the thin bar"); + assert!(fills(&s, made, 150.0, 110.0) && fills(&s, made, 190.0, 150.0)); +} + +#[test] +fn horizontal_bridges_cross_the_sides() { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "direction": "horizontal"})).unwrap(); + let made = id_of(&r); + assert!(!fills(&s, made, 110.0, 150.0) || !fills(&s, made, 190.0, 150.0)); + assert!(fills(&s, made, 150.0, 110.0) && fills(&s, made, 150.0, 190.0)); +} + +#[test] +fn a_shape_with_two_holes_gets_a_bridge_for_each() { + let mut s = session(); + shape_with_holes(&mut s, (100.0, 100.0, 100.0, 50.0), &[(110.0, 110.0, 30.0, 30.0), (160.0, 110.0, 30.0, 30.0)]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 3, "count": 2})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(2), json!(4), json!(0))); + let made = id_of(&r); + for x in [125.0, 175.0] { + assert!(!fills(&s, made, x, 105.0) && !fills(&s, made, x, 145.0), "{x}: a bridge above and below each hole"); + } +} + +#[test] +fn type_is_bridged_by_its_glyph_outlines_and_stays_type() { + let mut s = session(); + let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": "O", "size": 144})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[t]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 3})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(1), json!(0)), "{r}"); + assert!(matches!(node(&s, id_of(&r)).kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); + // The type itself is not converted: it is on the hidden layer, still type. + assert!(matches!(node(&s, t).kind, NodeKind::Text(_))); + assert!(!node(&s, NodeId(r["original"].as_u64().unwrap())).visible); +} + +#[test] +fn the_result_is_painted_as_the_topmost_object_with_outlines() { + let mut s = session(); + let o = letter_o(&mut s); + // Type holding only a space draws no outlines, so it does not set the paint, though it is on top. + let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": " ", "size": 24})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[o]); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let red = node(&s, o).appearance.fill_paint(); + select(&mut s, &[o, t]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!(node(&s, id_of(&r)).appearance.fill_paint(), red); +} + +#[test] +fn hidden_members_of_a_group_are_left_out() { + let mut s = session(); + let o = letter_o(&mut s); + // A hidden square that would fill the O's hole, grouped with it. + let cover = rect(&mut s, 120.0, 120.0, 60.0, 60.0); + select(&mut s, &[o, cover]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[cover]); + s.execute("object.hide", &json!({})).unwrap(); + select(&mut s, &[g]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone()), (json!(1), json!(1)), "{r}"); +} + +#[test] +fn art_without_islands_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + select(&mut s, &[a]); + let (steps, count) = (undo_steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute("addon.cutting.bridges", &json!({})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["id"].clone()), (json!(0), json!(0), Value::Null)); + assert!(r["warning"].as_str().is_some(), "{r}"); + assert_eq!((undo_steps(&s), s.doc().unwrap().doc.node_count()), (steps, count)); +} + +#[test] +fn an_island_too_narrow_for_the_width_is_reported() { + let mut s = session(); + shape_with_holes(&mut s, (100.0, 100.0, 100.0, 100.0), &[(149.0, 120.0, 2.0, 60.0)]); + let steps = undo_steps(&s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(1), json!(0), json!(1))); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("No bridge")), "{r}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn islands_left_without_a_bridge_are_reported_beside_the_ones_bridged() { + let mut s = session(); + // A wide hole on the left and a 2 pt slot on the right. + shape_with_holes(&mut s, (100.0, 100.0, 200.0, 100.0), &[(120.0, 120.0, 60.0, 60.0), (249.0, 120.0, 2.0, 60.0)]); + let steps = undo_steps(&s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + assert_eq!((r["islands"].clone(), r["bridges"].clone(), r["unbridged"].clone()), (json!(2), json!(1), json!(1))); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("could not be joined")), "{r}"); + assert_eq!(undo_steps(&s), steps + 1); + assert!(!fills(&s, id_of(&r), 150.0, 110.0), "the wide hole is bridged"); +} + +#[test] +fn each_run_keeps_its_original_on_a_layer_of_its_own() { + let mut s = session(); + letter_o(&mut s); + let first = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + shape_with_holes(&mut s, (300.0, 100.0, 100.0, 100.0), &[(320.0, 120.0, 60.0, 60.0)]); + let second = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap(); + let name = |r: &Value| node(&s, NodeId(r["original"].as_u64().unwrap())).name; + assert_eq!((name(&first).as_deref(), name(&second).as_deref()), (Some("Stencil Original"), Some("Stencil Original 2"))); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + letter_o(&mut s); + let steps = undo_steps(&s); + for (key, p) in [ + ("width", json!({"width": 0})), + ("width", json!({"width": 5000})), + ("width", json!({"width": "wide"})), + ("count", json!({"count": 0})), + ("count", json!({"count": 1.5})), + ("count", json!({"count": 17})), + ("count", json!({"count": "two"})), + ("direction", json!({"direction": "diagonal"})), + ("direction", json!({"direction": 90})), + ("keepOriginal", json!({"keepOriginal": "yes"})), + ] { + let e = s.execute("addon.cutting.bridges", &p).unwrap_err().to_string(); + assert!(e.contains(key), "{p}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert!(s.execute("addon.cutting.bridges", &json!({"width": 4})).is_ok(), "good params run"); +} + +#[test] +fn selected_objects_without_outlines_stay_where_they_are() { + for keep in [true, false] { + let mut s = session(); + let o = letter_o(&mut s); + // Type holding only a space has no outlines. + let t = NodeId(s.execute("text.create", &json!({"x": 100, "y": 300, "text": " ", "size": 24})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session, id: NodeId| s.doc().unwrap().doc.layer_of(id); + let before = layer(&s, t); + select(&mut s, &[o, t]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": keep})).unwrap(); + assert_eq!(r["bridges"], json!(1), "{r}"); + assert!(node(&s, t).visible && layer(&s, t) == before, "keep {keep}: the type stays where it was"); + if keep { + let held = + s.doc().unwrap().doc.children(Some(NodeId(r["original"].as_u64().unwrap()))).map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()); + assert_eq!(held, Some(vec![o])); + } + } +} + +#[test] +fn the_result_takes_the_place_of_the_topmost_selected_object() { + let mut s = session(); + let o = letter_o(&mut s); + let between = rect(&mut s, 400.0, 100.0, 50.0, 50.0); + let o2 = shape_with_holes(&mut s, (500.0, 100.0, 100.0, 100.0), &[(520.0, 120.0, 60.0, 60.0)]); + let above = rect(&mut s, 400.0, 300.0, 50.0, 50.0); + select(&mut s, &[o, o2]); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "keepOriginal": false})).unwrap(); + let made = id_of(&r); + let d = &s.doc().unwrap().doc; + let order: Vec<NodeId> = d.children(d.layer_of(made)).unwrap().iter().map(|n| n.id).collect(); + let at = |id: NodeId| order.iter().position(|i| *i == id).unwrap(); + assert!(at(between) < at(made) && at(made) < at(above), "{order:?}"); +} + +#[test] +fn the_result_is_one_path_when_one_outline_is_left() { + for (count, plain) in [(1, true), (2, false)] { + let mut s = session(); + letter_o(&mut s); + let r = s.execute("addon.cutting.bridges", &json!({"width": 4, "count": count})).unwrap(); + let kind = node(&s, id_of(&r)).kind; + // One bridge leaves a C, one outline; two leave two pieces. + assert_eq!(matches!(kind, NodeKind::Path { .. }), plain, "count {count}"); + assert_eq!(matches!(kind, NodeKind::Compound { .. }), !plain, "count {count}"); + } +} diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index fafdfc07dc..654138a1dd 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -164,11 +164,11 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> { } /// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds -/// no layers). +/// no layers, and no ruler guides: a layer's are left out). fn without_layers(n: &Node) -> Node { let mut n = n.clone(); if let NodeKind::Layer { children, clip, .. } = &n.kind { - n.kind = NodeKind::Group { children: children.clone(), clip: *clip }; + n.kind = NodeKind::Group { children: children.iter().filter(|c| !c.is_ruler_guide()).cloned().collect(), clip: *clip }; } if let Some(children) = n.children_mut() { for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) { @@ -203,8 +203,10 @@ fn symbols_from_layers(s: &mut Session, p: &Value) -> Result<Value> { let (mut made, mut skipped) = (vec![], vec![]); for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) { let name = layer.display_name(); - let roots: Vec<NodeId> = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default(); - let art = match layer.children().map(Vec::as_slice).unwrap_or_default() { + // The layer's ruler guides stay where they are. + let children: Vec<Arc<Node>> = layer.children().into_iter().flatten().filter(|n| !n.is_ruler_guide()).cloned().collect(); + let roots: Vec<NodeId> = children.iter().map(|n| n.id).collect(); + let art = match children.as_slice() { [] => None, [one] => Some(without_layers(one)), many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))), diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs index 61e59fc54f..084bd5ca27 100644 --- a/crates/engine/src/cmd/addons/document/batch_trace.rs +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -113,7 +113,8 @@ pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> { for path in &files { let opened_before = s.documents().len(); let one = |s: &mut Session| -> Result<String> { - s.execute("document.open", &json!({ "path": path }))?; + // A PSD or PSB is traced as its merged image, not as the first of its layers. + s.execute("document.open", &json!({ "path": path, "layers": false }))?; s.execute("select.all", &json!({}))?; s.execute(trace, &json!({ "preset": preset }))?; let stem = fileio::file_stem(path); diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index b0fbb41422..43e86caf52 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -333,6 +333,34 @@ fn batch_trace_folder_traces_and_saves_each_image() { let _ = std::fs::remove_dir_all(&dir); } +/// A layered PSD is traced as its merged image: a white layer under a black square gives the +/// square's shape, not a trace of the white layer alone. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_traces_a_layered_psd_as_its_merged_image() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace-psd"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 24, "height": 24})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 24, "height": 24})).unwrap(); + s.execute("layer.new", &json!({"name": "Square"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 6, "y": 6, "width": 12, "height": 12})).unwrap(); + let psd = s.execute("document.export", &json!({"format": "psd"})).unwrap(); + std::fs::write(src.join("two.psd"), vectorcraft_format::base64_decode(psd["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + let r = + s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "preset": "Black and White Logo", "expand": true})).unwrap(); + assert_eq!(r["traced"].as_array().unwrap().len(), 1, "{r}"); + let svg = std::fs::read_to_string(out.join("two.svg")).unwrap(); + assert!(svg.contains("fill=\"#000000\""), "the black square is traced: {svg}"); + 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] diff --git a/crates/engine/src/cmd/addons/image.rs b/crates/engine/src/cmd/addons/image.rs new file mode 100644 index 0000000000..b2a9d74f83 --- /dev/null +++ b/crates/engine/src/cmd/addons/image.rs @@ -0,0 +1,604 @@ +//! Image Tools (`addon.image.*`), a built-in add-on. Remove Background makes the background of the +//! selected images transparent in their own pixels, as one undo step. The background is the most +//! common color along an image's edges, the average of its four corners, or colors the caller +//! picks. It is cleared where it reaches in from an edge, or wherever it is. The work is done here, +//! on the pixels; nothing is sent anywhere. It is a VectorCraft addition. Its submenu (Object › +//! Plug-ins › Image Tools) and dialog are the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::{HashMap, HashSet}; +use std::io::Cursor; +use std::sync::{Arc, Weak}; + +use image::{DynamicImage, ImageBuffer, LumaA, Rgba}; +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{ImageBlob, NodeId, NodeKind}; +use vectorcraft_geom::Affine; + +use super::super::fileio::{MAX_RASTER_ALLOC, ppi}; +use super::super::menucmds::has_image; +use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param}; + +/// Remove Background's command. +pub const REMOVE_BACKGROUND: &str = "addon.image.removeBackground"; +const C: &str = REMOVE_BACKGROUND; + +/// The most colors `colors` lists. +const MAX_COLORS: usize = 16; + +/// Bytes a pixel takes while it is worked on, beside its pixels: its level, whether the edge search +/// reached it, and its place in the search's stack (4 bytes, twice that while the stack grows). +const WORK_BYTES: u64 = 10; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "addon.image.removeBackground", + "Remove Background…", + ["Object", "Plug-ins", "Image Tools"], + None, + "{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, and a result with no pixel left are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}", + has_image, + remove_background + )] +} + +/// Where the background's colors come from. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Background { + /// The most common color along the image's edges. + Edges, + /// The average of the image's four corner pixels that are not clear. + Corners, + /// These colors. + Colors(Vec<[u8; 3]>), +} + +/// How near a color is to a background color. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Match { + /// The RGB distance, as a percentage of the largest one (black to white). + Distance, + /// The largest difference on one of red, green and blue, as a percentage of a channel's range. + Channels, +} + +/// What Remove Background clears: the background, whether only where it reaches in from an edge, +/// and how near a color must be to it (a percentage, measured as `measure` says) to be cleared, and +/// to fade out past that. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Settings { + pub background: Background, + pub contiguous: bool, + pub measure: Match, + pub tolerance: f64, + pub softness: f64, +} + +impl Settings { + /// The settings `p` gives, each checked. + fn read(p: &Value) -> Result<Self> { + let percent = |key: &str| -> Result<f64> { + let v = number_or(p, key, 10.0, C)?; + if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) } + }; + let (tolerance, softness) = (percent("tolerance")?, percent("softness")?); + let colors = match p.get("colors") { + None | Some(Value::Null) => None, + Some(v) => Some(colors(v)?), + }; + let background = match text_param(p, "background", C)? { + None | Some("edges") => Background::Edges, + Some("corners") => Background::Corners, + Some("colors") => Background::Colors(colors.ok_or_else(colors_error)?), + Some(_) => return Err(bad(C, "`background` must be edges, corners or colors")), + }; + let measure = match text_param(p, "match", C)? { + None | Some("distance") => Match::Distance, + Some("channels") => Match::Channels, + Some(_) => return Err(bad(C, "`match` must be distance or channels")), + }; + let contiguous = switch_or(p, "contiguous", true, C)?; + Ok(Self { background, contiguous, measure, tolerance, softness }) + } +} + +fn colors_error() -> crate::EngineError { + bad(C, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue") +} + +/// The colors `v` lists: an array of strings, or one string of them split by commas or spaces. +/// Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused. +fn colors(v: &Value) -> Result<Vec<[u8; 3]>> { + // One past the most is enough to tell a list that is too long. + let texts: Vec<&str> = match v { + Value::String(s) => s.split([',', ' ', '\t', '\n']).filter(|t| !t.is_empty()).take(MAX_COLORS + 1).collect(), + Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(colors_error)?, + _ => return Err(colors_error()), + }; + if texts.is_empty() || texts.len() > MAX_COLORS { + return Err(colors_error()); + } + texts.into_iter().map(|t| rgb8(t).ok_or_else(colors_error)).collect() +} + +/// The 8-bit RGB of the color `t` writes. +fn rgb8(t: &str) -> Option<[u8; 3]> { + if hex_with_alpha(t) { + return None; + } + let [r, g, b] = Color::from_hex(t)?.to_rgb_uncalibrated(); + Some([r, g, b].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) +} + +fn remove_background(s: &mut Session, p: &Value) -> Result<Value> { + let settings = Settings::read(p)?; + // A preview step keeps the pixels it decodes for the next step; other runs keep none. + let mut kept = std::mem::take(&mut s.decoded_images); + let previewing = s.previewing; + let found = changes(s, p, &settings, previewing.then_some(&mut kept)); + s.decoded_images = kept; + let changes = found?; + let ids: Vec<u64> = changes.iter().map(|(id, ..)| id.0).collect(); + let made_clear: u64 = changes.iter().map(|(_, out, _)| out.cleared).sum(); + if !changes.is_empty() { + s.edit("Remove Background", |d, _| { + for (id, out, xf) in changes { + let key = out.blob.content_key(); + d.images.entry(key.clone()).or_insert(out.blob); + if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) { + im.key = key; + (im.width, im.height, im.xf) = (out.width, out.height, xf); + im.link = None; + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids, "cleared": made_clear })) +} + +/// The images `p` names (`ids`, or the selected images) whose pixels change, each with its pixels +/// cleared as `settings` say and the transform that keeps its place and size. Decoded pixels are +/// taken from and kept in `kept` when it is given. +fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<(NodeId, Cleared, Affine)>> { + let st = s.doc()?; + let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) { + // Each image once, however often `ids` names it. + let mut given = HashSet::new(); + let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", C)?.into_iter().filter(|id| given.insert(*id)).collect(); + if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) { + return Err(bad(C, format!("object {} is not an image", id.0))); + } + ids + } else { + st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect() + }; + if ids.is_empty() { + return Err(bad(C, "select an image")); + } + // Every image is checked before any is decoded. + let mut images = vec![]; + for id in ids { + let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue }; + let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?; + // The preview stands in for a file that hasn't been read, or that is kept at its preview. + if im.link.is_some() && blob.is_proxy() { + return Err(bad(C, "the linked image shows its preview: embed or relink it first")); + } + if blob.is_cmyk() { + return Err(bad(C, "a CMYK image has no transparency to set")); + } + images.push((id, im, blob)); + } + // Each image's pixels once, however many objects show them. + let mut cleared: HashMap<&str, Option<Cleared>> = HashMap::new(); + let mut changes = vec![]; + for (id, im, blob) in images { + let out = match cleared.get(im.key.as_str()) { + Some(out) => out.clone(), + None => { + let out = clear(blob, settings, kept.as_deref_mut())?; + cleared.insert(&im.key, out.clone()); + out + } + }; + if let Some(out) = out { + // A file read at another size than the object's keeps the object's place and size. + let xf = if (out.width, out.height) == (im.width, im.height) { + im.xf + } else { + im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(out.width), f64::from(im.height) / f64::from(out.height)) + }; + changes.push((id, out, xf)); + } + } + Ok(changes) +} + +/// An image with its background cleared: its PNG, its size in pixels, and how many of its pixels +/// were made fully clear. +#[derive(Clone, Debug)] +pub(crate) struct Cleared { + pub blob: ImageBlob, + pub width: u32, + pub height: u32, + pub cleared: u64, +} + +/// An image's pixels as straight RGBA, at 8 or 16 bits a sample. +#[derive(Clone)] +enum Pixels { + Eight(image::RgbaImage), + Sixteen(ImageBuffer<Rgba<u16>, Vec<u16>>), +} + +/// The most bytes of decoded pixels and ICC profiles [`DecodedImages`] keeps (128 MiB, or 32 MiB in +/// the web app). +const KEEP_BYTES: u64 = MAX_RASTER_ALLOC / 16; + +/// The images Remove Background decoded during an interaction's preview steps, the most recently +/// used first, at most [`KEEP_BYTES`] in all. The next preview step runs the command again on the +/// same bytes and takes their pixels from here instead of decoding them again. The session holds +/// it and empties it when the interaction ends (OK or Cancel). A run that is not a preview step +/// does not read or fill it. +#[derive(Default)] +pub(crate) struct DecodedImages(Vec<Decoded>); + +/// An image decoded by [`clear`]: the bytes it was decoded from (held weakly, so they are not kept +/// alive for it, and an entry whose bytes are gone is dropped), its pixels, whether it was gray, +/// and its ICC profile. +struct Decoded { + source: Weak<Vec<u8>>, + pixels: Arc<Pixels>, + gray: bool, + icc: Option<Vec<u8>>, +} + +#[cfg(test)] +thread_local! { + /// How many times this thread decoded an image in [`clear`]. + pub(crate) static DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +impl DecodedImages { + /// Drops every image kept. + pub(crate) fn empty(&mut self) { + self.0.clear(); + } + + /// How many images are kept. + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.0.len() + } + + /// The pixels, gray flag and ICC profile kept for `bytes`, if they are kept. Images whose bytes + /// are gone are dropped first. + fn get(&mut self, bytes: &Arc<Vec<u8>>) -> Option<(Arc<Pixels>, bool, Option<Vec<u8>>)> { + self.0.retain(|d| d.source.strong_count() > 0); + let at = self.0.iter().position(|d| std::ptr::eq(d.source.as_ptr(), Arc::as_ptr(bytes)))?; + let d = self.0.remove(at); + let found = (Arc::clone(&d.pixels), d.gray, d.icc.clone()); + self.0.insert(0, d); + Some(found) + } + + /// Keeps `pixels` decoded from `bytes` first, in place of anything kept for the same bytes, and + /// drops images whose bytes are gone and the least recently used past [`KEEP_BYTES`]. + fn keep(&mut self, bytes: &Arc<Vec<u8>>, pixels: Arc<Pixels>, gray: bool, icc: Option<Vec<u8>>) { + self.0.retain(|d| d.source.strong_count() > 0 && !std::ptr::eq(d.source.as_ptr(), Arc::as_ptr(bytes))); + self.0.insert(0, Decoded { source: Arc::downgrade(bytes), pixels, gray, icc }); + let mut total = 0u64; + self.0.retain(|d| { + total = total.saturating_add(d.bytes()); + total <= KEEP_BYTES + }); + } +} + +impl Decoded { + /// How many bytes the entry keeps: its pixels and its ICC profile. + fn bytes(&self) -> u64 { + self.pixels.bytes().saturating_add(self.icc.as_ref().map_or(0, |icc| icc.len() as u64)) + } +} + +impl Pixels { + /// How many bytes the pixels take. + fn bytes(&self) -> u64 { + match self { + Self::Eight(img) => img.as_raw().len() as u64, + Self::Sixteen(img) => img.as_raw().len() as u64 * 2, + } + } + + /// The width and height in pixels. + fn dimensions(&self) -> (u32, u32) { + match self { + Self::Eight(img) => img.dimensions(), + Self::Sixteen(img) => img.dimensions(), + } + } + + /// Pixel `i` (row by row from the top left) at 16 bits a sample (an 8-bit sample `v` is + /// `v * 257`). + fn rgba16(&self, i: usize) -> [u16; 4] { + let mut out = [0u16; 4]; + match self { + Self::Eight(img) => { + for (o, v) in out.iter_mut().zip(img.as_raw().get(i * 4..i * 4 + 4).unwrap_or_default()) { + *o = u16::from(*v) * 257; + } + } + Self::Sixteen(img) => { + for (o, v) in out.iter_mut().zip(img.as_raw().get(i * 4..i * 4 + 4).unwrap_or_default()) { + *o = *v; + } + } + } + out + } +} + +/// `blob` with its background cleared as `settings` say, or `None` when no pixel changes. A CMYK +/// image, one that can't be decoded or is too large to change, and a result with no pixel left are +/// errors. The PNG keeps the source's ICC profile and resolution. The decoded pixels are taken +/// from and kept in `kept` when it is given. +pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Option<Cleared>> { + if blob.is_cmyk() { + return Err(bad(C, "a CMYK image has no transparency to set")); + } + let found = kept.as_deref_mut().and_then(|k| k.get(&blob.bytes)); + let (source, gray, icc) = match found { + Some(found) => found, + None => decode(blob, kept)?, + }; + // The pixels kept for the next run stay as they are; ones not kept are worked on in place. + let mut px = Arc::try_unwrap(source).unwrap_or_else(|kept| Pixels::clone(&kept)); + let (w, h) = px.dimensions(); + let levels = levels(w as usize, h as usize, &|i| px.rgba16(i), settings); + let Some(cleared) = apply(&mut px, &levels) else { return Ok(None) }; + let left = match &px { + Pixels::Eight(img) => img.pixels().any(|p| p.0[3] > 0), + Pixels::Sixteen(img) => img.pixels().any(|p| p.0[3] > 0), + }; + if !left { + return Err(bad(C, "every pixel matches the background: no image would be left")); + } + let out = match (px, gray) { + (Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img), + (Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img), + (Pixels::Eight(img), true) => { + DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]]))) + } + (Pixels::Sixteen(img), true) => { + DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]]))) + } + }; + let mut png = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + if let Some(icc) = icc { + use image::ImageEncoder as _; + encoder.set_icc_profile(icc).map_err(|e| bad(C, e.to_string()))?; + } + out.write_with_encoder(encoder).map_err(|e| bad(C, e.to_string()))?; + // The resolution the file declares, which sizes the image at 100% when it is replaced or relinked. + if let Some(r) = ppi::resolution(&blob.bytes) { + png = ppi::with_png_resolution(&png, r); + } + Ok(Some(Cleared { blob: ImageBlob::png(png), width: w, height: h, cleared })) +} + +/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that +/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it +/// is given, if a copy of them fits the decode allowance beside the work. +fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> { + let reader = + || image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(C, "the image's pixels can't be read")); + let mut decoder = reader()?.into_decoder().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?; + // The ICC profile the colors are in goes with them into the PNG. + let (w, h, kind, icc) = { + use image::ImageDecoder as _; + let (w, h) = decoder.dimensions(); + (w, h, decoder.color_type(), decoder.icc_profile().ok().flatten()) + }; + drop(decoder); + // The file's pixels, those worked on (as many again for the PNG made of them) and the work, + // checked from the header before anything is decoded. + let deep = kind.bytes_per_pixel() > kind.channel_count(); + let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES; + if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) { + return Err(bad(C, format!("an image of {w} × {h} pixels is too large to change"))); + } + let mut reader = reader()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_RASTER_ALLOC); + reader.limits(limits); + let img = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?; + #[cfg(test)] + DECODES.with(|c| c.set(c.get() + 1)); + let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16); + let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) }); + // A kept copy is worked on as a copy: one more set of the pixels worked on. + let with_copy = per_pixel + if deep { 8 } else { 4 }; + if let Some(kept) = kept + && u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(with_copy)).is_some_and(|n| n <= MAX_RASTER_ALLOC) + && px.bytes().saturating_add(icc.as_ref().map_or(0, |icc| icc.len() as u64)) <= KEEP_BYTES + { + kept.keep(&blob.bytes, Arc::clone(&px), gray, icc.clone()); + } + Ok((px, gray, icc)) +} + +/// Each pixel's alpha scaled by its level (255 keeps it). Returns how many pixels were made fully +/// clear, or `None` when no pixel changed. +fn apply(px: &mut Pixels, levels: &[u8]) -> Option<u64> { + let (mut changed, mut cleared) = (false, 0u64); + match px { + Pixels::Eight(img) => { + for (p, &l) in img.pixels_mut().zip(levels) { + let a = ((u32::from(p.0[3]) * u32::from(l) + 127) / 255) as u8; + changed |= a != p.0[3]; + cleared += u64::from(a == 0 && p.0[3] != 0); + p.0[3] = a; + } + } + Pixels::Sixteen(img) => { + for (p, &l) in img.pixels_mut().zip(levels) { + let a = ((u32::from(p.0[3]) * u32::from(l) + 127) / 255) as u16; + changed |= a != p.0[3]; + cleared += u64::from(a == 0 && p.0[3] != 0); + p.0[3] = a; + } + } + } + changed.then_some(cleared) +} + +/// How much of each of the `w` × `h` pixels `px` gives (row by row, straight RGBA at 16 bits a +/// sample) stays, from 0 (cleared) to 255 (kept), as `settings` say. Each pixel's distance to the +/// background is worked out once. A pixel past the first `u32::MAX` is left kept by the edge search. +pub(crate) fn levels(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4], settings: &Settings) -> Vec<u8> { + let n = w.saturating_mul(h); + let refs: Vec<[u16; 3]> = match &settings.background { + Background::Colors(refs) => refs.iter().map(|c| c.map(|v| u16::from(v) * 257)).collect(), + Background::Edges => match edge_color(w, h, px) { + Some(edge) => vec![edge], + None => return vec![255; n], + }, + Background::Corners => match corner_color(w, h, px) { + Some(corner) => vec![corner], + None => return vec![255; n], + }, + }; + let mut out: Vec<u8> = (0..n) + .map(|i| { + let [r, g, b, _] = px(i); + level([r, g, b], &refs, settings) + }) + .collect(); + if settings.contiguous { + // Out from the edges, through clear pixels and pixels that lose some alpha; the pixels it + // doesn't reach are kept. + let reaches = |out: &[u8], i: usize| out.get(i).is_some_and(|l| *l < 255) || px(i)[3] == 0; + let mut seen = vec![false; n]; + let mut stack: Vec<u32> = vec![]; + for i in border(w, h).filter(|&i| reaches(&out, i)) { + if let (Some(s), Ok(at)) = (seen.get_mut(i), u32::try_from(i)) { + *s = true; + stack.push(at); + } + } + while let Some(at) = stack.pop() { + let i = at as usize; + let (x, y) = (i % w, i / w); + let next = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]; + for j in next.into_iter().flatten() { + if let Some(s) = seen.get_mut(j) + && !*s + && reaches(&out, j) + && let Ok(at) = u32::try_from(j) + { + *s = true; + stack.push(at); + } + } + } + for (l, s) in out.iter_mut().zip(&seen) { + if !*s { + *l = 255; + } + } + } + out +} + +/// The level of a pixel of color `c`: 0 within the tolerance of the nearest of `refs`, 255 from +/// the tolerance plus the softness on, and in proportion between them. +fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 { + let Settings { tolerance, softness, measure, .. } = *settings; + let d = percent(refs.iter().map(|r| gap(c, *r, measure)).fold(f64::INFINITY, f64::min), measure); + if d <= tolerance { + 0 + } else if d >= tolerance + softness { + 255 + } else { + ((d - tolerance) / softness * 255.0).round().clamp(0.0, 255.0) as u8 + } +} + +/// How far apart `a` and `b` are, measured as `measure` says, before `percent` converts it: the +/// squared RGB distance, or the largest difference on one channel. +fn gap(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 { + match measure { + Match::Distance => a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum(), + Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)), + } +} + +/// A `gap` as a percentage: of the largest RGB distance (black to white) with distance, or of the +/// channel's range with channels. A difference of `k` 8-bit steps on one channel is exactly +/// `k / 255 × 100` with channels. +fn percent(gap: f64, measure: Match) -> f64 { + match measure { + Match::Distance => gap.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0, + Match::Channels => gap / 65_535.0 * 100.0, + } +} + +/// The pixels on the edges of a `w` × `h` image, each once. +fn border(w: usize, h: usize) -> impl Iterator<Item = usize> { + let top = (0..w).filter(move |_| h > 0); + let bottom = (0..w).filter(move |_| h > 1).map(move |x| (h - 1) * w + x); + let sides = (1..h.saturating_sub(1)).flat_map(move |y| [Some(y * w), (w > 1).then(|| y * w + w - 1)].into_iter().flatten()); + top.chain(bottom).chain(sides) +} + +/// The most common color along an image's edges: its edge pixels grouped by 16 levels a channel, +/// with the clear ones as a group of their own, as the average of the largest group. `None` when +/// the clear edge pixels are at least as many as that group: the background is already cleared. +fn edge_color(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4]) -> Option<[u16; 3]> { + let mut groups: HashMap<[u16; 3], (u64, [u64; 3])> = HashMap::new(); + let mut clear = 0u64; + for i in border(w, h) { + let [r, g, b, a] = px(i); + if a == 0 { + clear += 1; + continue; + } + let e = groups.entry([r >> 12, g >> 12, b >> 12]).or_default(); + e.0 += 1; + for (s, v) in e.1.iter_mut().zip([r, g, b]) { + *s += u64::from(v); + } + } + // Equal groups go by color, so the result doesn't depend on the map's order. + let (_, (n, sums)) = groups.into_iter().max_by(|a, b| a.1.0.cmp(&b.1.0).then(b.0.cmp(&a.0)))?; + if clear >= n { + return None; + } + Some(sums.map(|s| ((s + n / 2) / n.max(1)) as u16)) +} + +/// The average of the four corner pixels of a `w` × `h` image that are not clear (a corner of a +/// one-pixel-wide image counts twice). `None` when all four are clear: the background is already +/// cleared. +fn corner_color(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4]) -> Option<[u16; 3]> { + if w == 0 || h == 0 { + return None; + } + let corners = [0, w - 1, (h - 1) * w, (h - 1) * w + w - 1]; + let (mut n, mut sums) = (0u64, [0u64; 3]); + for [r, g, b, a] in corners.map(px) { + if a > 0 { + n += 1; + for (s, v) in sums.iter_mut().zip([r, g, b]) { + *s += u64::from(v); + } + } + } + (n > 0).then(|| sums.map(|s| ((s + n / 2) / n) as u16)) +} diff --git a/crates/engine/src/cmd/addons/image/tests.rs b/crates/engine/src/cmd/addons/image/tests.rs new file mode 100644 index 0000000000..df27180e82 --- /dev/null +++ b/crates/engine/src/cmd/addons/image/tests.rs @@ -0,0 +1,480 @@ +use std::io::Cursor; +use std::sync::Arc; + +use image::{DynamicImage, ImageBuffer, Luma, Rgb}; +use serde_json::{Value, json}; +use vectorcraft_doc::{ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind}; +use vectorcraft_geom::Affine; + +use super::{Background, Match, REMOVE_BACKGROUND as C, Settings, level, levels}; +use crate::Session; +use crate::cmd::fileio::ppi; + +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const RED: [u8; 4] = [200, 0, 0, 255]; + +/// The command's defaults with `background`. +fn settings(background: Background) -> Settings { + Settings { background, contiguous: true, measure: Match::Distance, tolerance: 10.0, softness: 10.0 } +} + +fn png(img: DynamicImage) -> Vec<u8> { + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// 12 × 10 pixels: white, with a red block from (3, 3) to (9, 7) that holds one white pixel at +/// (6, 5), which no white edge pixel reaches. +fn framed() -> image::RgbaImage { + image::RgbaImage::from_fn(12, 10, |x, y| { + let block = (3..9).contains(&x) && (3..7).contains(&y); + image::Rgba(if block && (x, y) != (6, 5) { RED } else { WHITE }) + }) +} + +/// A session with `bytes` opened as a document, its image selected. +fn open(bytes: &[u8]) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let id = s.doc().unwrap().selection.objects[0]; + (s, id) +} + +fn image_of(s: &Session, id: NodeId) -> ImageObject { + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") }; + (**im).clone() +} + +fn bytes_of(s: &Session, id: NodeId) -> Arc<Vec<u8>> { + s.doc().unwrap().doc.images[&image_of(s, id).key].bytes.clone() +} + +fn pixels(s: &Session, id: NodeId) -> DynamicImage { + image::load_from_memory(&bytes_of(s, id)).unwrap() +} + +fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 { + img.to_rgba8().get_pixel(x, y).0[3] +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn the_edge_colors_are_cleared_where_they_reach_in_from_an_edge() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let before = (image_of(&s, id), undo_len(&s)); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": 1, "ids": [id.0], "cleared": 12 * 10 - 6 * 4})); + let out = pixels(&s, id); + assert_eq!(out.color(), image::ColorType::Rgba8); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 11, 9), alpha(&out, 2, 4)), (0, 0, 0), "the white around the block"); + assert_eq!(out.to_rgba8().get_pixel(4, 4).0, RED, "the block"); + assert_eq!(alpha(&out, 6, 5), 255, "white inside the block, which no edge reaches"); + let after = image_of(&s, id); + assert_eq!((after.width, after.height, after.xf), (12, 10, before.0.xf), "the same place and size"); + assert_eq!(undo_len(&s), before.1 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(image_of(&s, id), before.0); +} + +/// Picked colors, like the other backgrounds, are cleared where they reach in from an edge, and with +/// `contiguous: false` wherever they are. +#[test] +fn picked_colors_are_cleared_from_the_edges_or_wherever_they_are() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + s.execute(C, &json!({"background": "colors", "colors": ["#fff"], "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 255, 255), "not inside the block"); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + s.execute(C, &json!({"background": "colors", "colors": ["#fff"], "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255), "inside the block too; the red stays"); +} + +/// With `contiguous: false` the edge color is cleared inside the subject too. +#[test] +fn the_edge_color_can_be_cleared_wherever_it_is() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let r = s.execute(C, &json!({"contiguous": false})).unwrap(); + assert_eq!(r["cleared"], 12 * 10 - 6 * 4 + 1); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255)); +} + +/// `colors` as one string split by commas and spaces, written as other color params take them. +#[test] +fn picked_colors_can_be_one_string_of_colors() { + for colors in ["#00ff00, ffffff", "green white", "#0f0,#FFF"] { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + s.execute(C, &json!({"background": "colors", "colors": colors, "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 6, 5), alpha(&out, 4, 4)), (0, 0, 255), "{colors}"); + } +} + +/// A subject along a whole edge stays: only the most common edge color is the background. +#[test] +fn a_subject_along_one_edge_is_not_the_background() { + let img = image::RgbaImage::from_fn(10, 10, |_, y| image::Rgba(if y >= 7 { RED } else { WHITE })); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + s.execute(C, &json!({})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 5, 0), alpha(&out, 5, 9), alpha(&out, 0, 8)), (0, 255, 255)); +} + +/// The preview steps of one interaction, as the dialog's are, decode an image once and give what a +/// run on freshly decoded pixels gives. The pixels are kept only until the interaction ends (OK or +/// Cancel), and a run that is not a preview step keeps none. +#[test] +fn preview_steps_on_the_same_pixels_decode_them_once() { + let decodes = || super::DECODES.with(std::cell::Cell::get); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let start = decodes(); + let p = json!({"background": "colors", "colors": "#c80000", "contiguous": false, "tolerance": 0, "softness": 0}); + s.begin_interaction("Remove Background").unwrap(); + s.preview(C, &json!({"tolerance": 0, "softness": 0})).unwrap(); + s.preview(C, &json!({"tolerance": 20, "softness": 0})).unwrap(); + s.preview(C, &p).unwrap(); + assert_eq!((decodes() - start, s.decoded_images.len()), (1, 1), "decoded once for three preview steps"); + s.commit_interaction().unwrap(); + assert_eq!(s.decoded_images.len(), 0, "OK lets the pixels go"); + let (mut fresh, fresh_id) = open(&png(DynamicImage::ImageRgba8(framed()))); + fresh.execute(C, &p).unwrap(); + assert_eq!((decodes() - start, fresh.decoded_images.len()), (2, 0), "a run that is not a preview step keeps nothing"); + assert_eq!(bytes_of(&s, id), bytes_of(&fresh, fresh_id), "the same result"); + assert_eq!((alpha(&pixels(&s, id), 4, 4), alpha(&pixels(&s, id), 0, 0)), (0, 255), "the red cleared, the white kept"); + s.execute("edit.undo", &json!({})).unwrap(); + s.begin_interaction("Remove Background").unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.decoded_images.len(), 1); + s.cancel_interaction().unwrap(); + assert_eq!(s.decoded_images.len(), 0, "Cancel lets the pixels go"); + s.execute(C, &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute(C, &json!({})).unwrap(); + assert_eq!(decodes() - start, 5, "each run that is not a preview step decodes"); +} + +/// Pixels a preview step takes from the step before keep what they were decoded with: a 16-bit gray +/// image with an ICC profile comes out as a run on freshly decoded pixels gives it. +#[test] +fn reused_pixels_keep_their_depth_gray_and_profile() { + use image::{ImageDecoder as _, ImageEncoder as _}; + let icc = b"a profile's bytes".to_vec(); + let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }])); + let mut bytes = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes); + encoder.set_icc_profile(icc.clone()).unwrap(); + DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap(); + let decodes = || super::DECODES.with(std::cell::Cell::get); + let (mut s, id) = open(&bytes); + let start = decodes(); + s.begin_interaction("Remove Background").unwrap(); + s.preview(C, &json!({"tolerance": 0, "softness": 0})).unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(decodes() - start, 1, "the second step took the pixels of the first"); + let (mut fresh, fresh_id) = open(&bytes); + fresh.execute(C, &json!({})).unwrap(); + assert_eq!(bytes_of(&s, id), bytes_of(&fresh, fresh_id), "the same result"); + let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") }; + assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535])); + let result = bytes_of(&s, id); + let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap(); + assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); +} + +/// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the +/// subject's color along an edge is not taken for the background. +#[test] +fn a_second_run_leaves_the_subject() { + let img = image::RgbaImage::from_fn(10, 10, |x, y| { + image::Rgba(if y >= 7 { + RED + } else if (4..6).contains(&x) && (3..5).contains(&y) { + [0, 0, 200, 255] + } else { + WHITE + }) + }); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + s.execute(C, &json!({})).unwrap(); + let (first, steps) = (image_of(&s, id), undo_len(&s)); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": 0, "ids": [], "cleared": 0})); + assert_eq!((image_of(&s, id), undo_len(&s)), (first, steps), "no change and no undo step"); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 5, 0), alpha(&out, 5, 9), alpha(&out, 4, 3)), (0, 255, 255), "the red and the blue stay"); +} + +#[test] +fn tolerance_and_softness_set_how_near_a_color_is_cleared() { + // White; 1.96 % from white; 21.6 % from white. + let px = [WHITE, [250, 250, 250, 255], [200, 200, 200, 255]]; + let at = |i: usize| px[i].map(|v| u16::from(v) * 257); + let run = |tolerance, softness| levels(3, 1, &at, &Settings { tolerance, softness, ..settings(Background::Colors(vec![[255; 3]])) }); + assert_eq!(run(0.0, 0.0), [0, 255, 255], "only white itself at 0"); + assert_eq!(run(2.0, 0.0), [0, 0, 255]); + assert_eq!(run(0.0, 10.0), [0, 50, 255], "1.96 % into a 10 % fade"); + assert_eq!(run(100.0, 0.0), [0, 0, 0], "everything at 100"); +} + +#[test] +fn a_result_with_no_pixel_left_is_refused_and_changes_nothing() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let before = (image_of(&s, id), undo_len(&s)); + let e = s.execute(C, &json!({"background": "colors", "colors": "#ffffff", "tolerance": 100})).unwrap_err(); + assert!(e.to_string().contains("every pixel matches the background"), "{e}"); + assert_eq!((image_of(&s, id), undo_len(&s)), before); +} + +#[test] +fn an_image_whose_pixels_do_not_change_is_left_with_no_undo_step() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let before = (image_of(&s, id), undo_len(&s)); + let r = s.execute(C, &json!({"background": "colors", "colors": "#00ff00", "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!(r, json!({"changed": 0, "ids": [], "cleared": 0})); + assert_eq!((image_of(&s, id), undo_len(&s)), before); + // An image whose edges and corners are already clear has no edge or corner color to clear, + // whatever color the clear pixels hold. + let ring = + image::RgbaImage::from_fn(6, 6, |x, y| image::Rgba(if (1..5).contains(&x) && (1..5).contains(&y) { WHITE } else { [255, 255, 255, 0] })); + for p in [json!({}), json!({"background": "corners", "contiguous": false})] { + let (mut s, _) = open(&png(DynamicImage::ImageRgba8(ring.clone()))); + assert_eq!(s.execute(C, &p).unwrap()["changed"], 0, "{p}"); + } +} + +/// The corners' color: 40 × 30 pixels of light gray around a red block, cleared within 5 steps on +/// each channel (`match: channels`, a tolerance of `5 / 255 × 100`, no softness), from the edges +/// or wherever it is. +#[test] +fn the_corners_color_is_cleared() { + let img = image::RgbaImage::from_fn(40, 30, |x, y| { + image::Rgba(if (10..30).contains(&x) && (8..22).contains(&y) { [200, 40, 40, 255] } else { [240, 240, 240, 255] }) + }); + for contiguous in [false, true] { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img.clone()))); + let p = json!({"background": "corners", "contiguous": contiguous, "match": "channels", "tolerance": 5.0 / 255.0 * 100.0, "softness": 0}); + let r = s.execute(C, &p).unwrap(); + assert_eq!(r["cleared"], 40 * 30 - 14 * 20, "{p}"); + let out = pixels(&s, id).to_rgba8(); + assert_eq!((out.get_pixel(0, 0).0[3], out.get_pixel(15, 15).0), (0, [200, 40, 40, 255]), "{p}"); + } + // A clear corner is left out of the average: the other three are white, and white is cleared. + let mut img = image::RgbaImage::from_pixel(8, 8, image::Rgba(WHITE)); + img.put_pixel(0, 0, image::Rgba([0; 4])); + img.put_pixel(4, 4, image::Rgba(RED)); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + let r = s.execute(C, &json!({"background": "corners", "tolerance": 0, "softness": 0})).unwrap(); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 7, 7), alpha(&out, 3, 3), alpha(&out, 4, 4)), (0, 0, 255)); + assert_eq!(r["cleared"], 8 * 8 - 2, "the pixels made clear, not the corner that was clear already"); +} + +/// One picked color matched by channel at a tolerance of 0: cleared wherever it is, and a pixel a +/// long way from it kept. +#[test] +fn one_picked_color_is_cleared_by_channel() { + let mut img = image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 20, 30, 255])); + img.put_pixel(2, 2, image::Rgba([250, 250, 250, 255])); + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(img))); + let p = json!({"background": "colors", "colors": "#0a141e", "contiguous": false, "match": "channels", "tolerance": 0, "softness": 0}); + assert_eq!(s.execute(C, &p).unwrap()["cleared"], 15); + let out = pixels(&s, id); + assert_eq!((alpha(&out, 0, 0), alpha(&out, 2, 2)), (0, 255)); +} + +/// With `match: channels`, a tolerance of `t / 255 × 100` clears a color `k` 8-bit steps from the +/// background on one channel exactly when `k ≤ t`, for every `t` and `k` from 0 to 255; with +/// `distance` the same color is nearer when the others match. +#[test] +fn channels_match_the_largest_difference_on_one_channel() { + for t in 0..=255u16 { + let s = Settings { measure: Match::Channels, tolerance: f64::from(t) / 255.0 * 100.0, softness: 0.0, ..settings(Background::Edges) }; + for k in 0..=255u16 { + for c in [[k * 257, 0, 0], [0, k * 257, 0], [0, 0, k * 257]] { + assert_eq!(level(c, &[[0; 3]], &s) == 0, k <= t, "t {t}, k {k}"); + } + } + } + let at = |measure| { + level([0, 40 * 257, 0], &[[0; 3]], &Settings { measure, tolerance: 32.0 / 255.0 * 100.0, softness: 0.0, ..settings(Background::Edges) }) + }; + assert_eq!((at(Match::Channels), at(Match::Distance)), (255, 0), "40 steps on green: past 32 on one channel; 9 % of the RGB distance"); +} + +#[test] +fn sixteen_bit_and_gray_images_keep_their_depth_and_channels() { + let deep = ImageBuffer::from_fn(8, 8, |x, y| Rgb(if (2..6).contains(&x) && (2..6).contains(&y) { [51_400, 0, 1] } else { [65_535; 3] })); + let (mut s, id) = open(&png(DynamicImage::ImageRgb16(deep))); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageRgba16(out) = pixels(&s, id) else { panic!("16-bit RGBA") }; + assert_eq!(out.get_pixel(0, 0).0[3], 0); + assert_eq!(out.get_pixel(3, 3).0, [51_400, 0, 1, 65_535], "16-bit samples kept as they were"); + // Samples one 8-bit step apart are told apart: only the background is cleared at 0. + let near = ImageBuffer::from_fn(4, 4, |x, y| Rgb(if (1..3).contains(&x) && (1..3).contains(&y) { [65_280; 3] } else { [65_535; 3] })); + let (mut s, id) = open(&png(DynamicImage::ImageRgb16(near))); + s.execute(C, &json!({"tolerance": 0, "softness": 0})).unwrap(); + let DynamicImage::ImageRgba16(out) = pixels(&s, id) else { panic!("16-bit RGBA") }; + assert_eq!((out.get_pixel(0, 0).0[3], out.get_pixel(1, 1).0[3]), (0, 65_535)); + let gray = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 30u8 } else { 240 }])); + let (mut s, id) = open(&png(DynamicImage::ImageLuma8(gray))); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") }; + assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([240, 0], [30, 255])); + let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }])); + let (mut s, id) = open(&png(DynamicImage::ImageLuma16(gray16))); + s.execute(C, &json!({})).unwrap(); + let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") }; + assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535])); +} + +/// The ICC profile the colors are in stays with them. +#[test] +fn the_color_profile_is_kept() { + use image::{ImageDecoder as _, ImageEncoder as _}; + let icc = b"a profile's bytes".to_vec(); + let mut bytes = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes); + encoder.set_icc_profile(icc.clone()).unwrap(); + DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap(); + let blob = ImageBlob::png(bytes); + let out = super::clear(&blob, &settings(Background::Edges), None).unwrap().unwrap(); + let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap(); + assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); +} + +/// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the +/// image as before. +#[test] +fn the_resolution_is_kept() { + let bytes = ppi::with_png_resolution(&png(DynamicImage::ImageRgba8(framed())), (300.0, 150.0)); + let (mut s, id) = open(&bytes); + s.execute(C, &json!({})).unwrap(); + let (x, y) = ppi::resolution(&bytes_of(&s, id)).expect("a resolution"); + assert_eq!((x.round(), y.round()), (300.0, 150.0)); +} + +#[test] +fn a_cmyk_image_is_refused() { + let inks = vectorcraft_doc::cmyk::Inks::new(4, 2, [0, 0, 0, 0].repeat(8)).unwrap(); + let tiff = ImageBlob::cmyk_tiff(&inks).unwrap(); + let (mut s, id) = open(&tiff.bytes); + let before = (image_of(&s, id), undo_len(&s)); + let e = s.execute(C, &json!({})).unwrap_err(); + assert!(e.to_string().contains("a CMYK image has no transparency to set"), "{e}"); + assert_eq!((image_of(&s, id), undo_len(&s)), before); +} + +/// A linked image of `blob`, `width` × `height` pixels as the object records it, beside the open +/// document's image. +fn place_linked(s: &mut Session, key: &str, blob: ImageBlob, (width, height): (u32, u32)) -> NodeId { + s.edit("Place", |d, sel| { + d.images.insert(key.into(), blob); + let id = d.alloc_id(); + let im = ImageObject { + key: key.into(), + width, + height, + xf: Default::default(), + link: Some(LinkInfo::new("/nowhere/art.png")), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +#[test] +fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() { + let bytes = png(DynamicImage::ImageRgba8(framed())); + let (mut s, _) = open(&bytes); + let linked = place_linked(&mut s, "linked", ImageBlob::png(bytes.clone()), (12, 10)); + let clip = vectorcraft_doc::links::PlacementOptions { clip: true, ..Default::default() }; + s.edit("Placement", |d, _| { + if let Some(NodeKind::Image(im)) = d.node_mut(linked).map(|n| &mut n.kind) { + im.placement = clip; + } + Ok(()) + }) + .unwrap(); + let r = s.execute(C, &json!({"ids": [linked.0, linked.0]})).unwrap(); + assert_eq!(r, json!({"changed": 1, "ids": [linked.0], "cleared": 12 * 10 - 6 * 4}), "an image named twice changes once"); + let im = image_of(&s, linked); + assert_eq!((im.link, alpha(&pixels(&s, linked), 0, 0)), (None, 0), "embedded, with its background cleared"); + assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them"); + // Pixels the file wasn't read for: the preview, as an image whose file is missing shows it. + let preview = Arc::new(bytes); + let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10)); + let before = (image_of(&s, missing), undo_len(&s)); + let e = s.execute(C, &json!({})).unwrap_err(); + assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}"); + assert_eq!((image_of(&s, missing), undo_len(&s)), before); +} + +/// An object whose pixels were read at another size than it records keeps its place and size. +#[test] +fn an_image_read_at_another_size_keeps_its_place_and_size() { + let bytes = png(DynamicImage::ImageRgba8(framed())); + let (mut s, _) = open(&bytes); + let id = place_linked(&mut s, "linked", ImageBlob::png(bytes), (24, 20)); + s.execute(C, &json!({"ids": [id.0]})).unwrap(); + let im = image_of(&s, id); + assert_eq!((im.width, im.height, im.xf), (12, 10, Affine::scale_non_uniform(2.0, 2.0))); +} + +#[test] +fn bad_params_are_refused_and_change_nothing() { + let (mut s, id) = open(&png(DynamicImage::ImageRgba8(framed()))); + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = (image_of(&s, id), undo_len(&s)); + // With `ids`, the command is available when one of them is an image. + let not_image = format!("object {rect} is not an image"); + let cases: [(Value, &str); 18] = [ + (json!({"background": "sky"}), "`background` must be edges, corners or colors"), + (json!({"background": 5}), "`background` must be a string"), + (json!({"match": "rgb"}), "`match` must be distance or channels"), + (json!({"match": true}), "`match` must be a string"), + (json!({"contiguous": "yes"}), "`contiguous` must be true or false"), + (json!({"contiguous": 1}), "`contiguous` must be true or false"), + (json!({"tolerance": 101}), "`tolerance` must be from 0 to 100"), + (json!({"softness": -1}), "`softness` must be from 0 to 100"), + (json!({"tolerance": "5"}), "`tolerance` must be a number"), + (json!({"background": "colors"}), "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue"), + (json!({"background": "colors", "colors": []}), "`colors` must list"), + (json!({"background": "colors", "colors": "#12"}), "`colors` must list"), + (json!({"background": "colors", "colors": "#ffffff80"}), "`colors` must list"), + (json!({"colors": ["#ffffff", 7]}), "`colors` must list"), + (json!({"background": "colors", "colors": vec!["#000"; 17]}), "`colors` must list"), + (json!({"background": "colors", "colors": "#000 ".repeat(100_000)}), "`colors` must list"), + (json!({"ids": [id.0, rect]}), ¬_image), + (json!({"ids": [rect]}), "select an image"), + ]; + for (p, msg) in cases { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } + assert_eq!((image_of(&s, id), undo_len(&s)), before); +} + +#[test] +fn an_image_too_large_to_change_is_refused_before_it_is_decoded() { + let run = |w: u32, h: u32| { + let (mut s, _) = open(&crate::tests_linkspanel::png_header(w, h)); + s.execute(C, &json!({})).unwrap_err().to_string() + }; + // As gray samples, RGBA worked on and kept for the PNG, and the work: 19 bytes a pixel. + let over = run(10_632, 10_631); + assert!(over.contains("an image of 10632 × 10631 pixels is too large to change"), "{over}"); + // Within the allowance it is decoded, and its missing rows can't be read. + let within = run(10_631, 10_631); + assert!(within.contains("the image's pixels can't be read"), "{within}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 4c1ba7e2dd..fc88442997 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?, count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", has_doc, set ), diff --git a/crates/engine/src/cmd/addons/pen/tests.rs b/crates/engine/src/cmd/addons/pen/tests.rs index 1bb9f3345e..b314b8db32 100644 --- a/crates/engine/src/cmd/addons/pen/tests.rs +++ b/crates/engine/src/cmd/addons/pen/tests.rs @@ -285,3 +285,54 @@ fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() { assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3); assert_eq!(steps(&s), n + 8); } + +/// #6634: the tool's closing drag on the first anchor sets that anchor's incoming handle to the +/// mirror of the pointer and does not give it symmetric handles: a corner keeps its outgoing +/// handle, a smooth anchor turns it to stay in line at its own length, and Alt pressed mid-drag +/// keeps it where the drag had turned it. +#[test] +fn the_tools_closing_drag_does_not_make_the_first_anchor_symmetric() { + // An open path whose first anchor, at (50, 50), has the handles `first`, drawn on from its last + // anchor; the closing gesture is then up to the caller. + let draw = |first: Value| { + let mut s = session(); + let mut a = json!({"x": 50, "y": 50}); + a.as_object_mut().unwrap().extend(first.as_object().unwrap().clone()); + let anchors = json!([a, {"x": 150, "y": 50}, {"x": 150, "y": 150}]); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + s.select_tool("smartPen", view()).unwrap(); + gesture(&mut s, &[(150.0, 150.0)], Mods::default()); + (s, id) + }; + let first = |s: &Session, id: NodeId| { + let sp = &path(s, id).subpaths[0]; + assert!(sp.closed, "{sp:?}"); + sp.anchors[0] + }; + let near = |a: Point, b: Point| a.distance(b) < 1e-6; + + // A corner: the first segment keeps its shape. + let (mut s, id) = draw(json!({"out": [80, 30]})); + gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default()); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(50.0, 0.0), Point::new(80.0, 30.0), AnchorKind::Corner), "{a:?}"); + + // A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 30. + let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]})); + assert_eq!(path(&s, id).subpaths[0].anchors[0].kind, AnchorKind::Smooth); + gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default()); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(50.0, 0.0), AnchorKind::Smooth), "{a:?}"); + assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}"); + + // Alt pressed mid-drag: a corner, its outgoing handle where the drag had turned it. + let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]})); + let alt = Mods { alt: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 50.0, 100.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 80.0, 100.0).with_mods(alt), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 100.0).with_mods(alt), view()).unwrap(); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(20.0, 0.0), AnchorKind::Corner), "{a:?}"); + assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}"); +} diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs index c401733906..87549e3694 100644 --- a/crates/engine/src/cmd/addons/shapes.rs +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + "{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top-left corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> { "Ellipse", [], None, - "{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + "{x, y, width, height, startAngle?, endAngle?: degrees (counter-clockwise from 3 o'clock, as object.setLiveShape's pieStart and pieEnd; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, ellipse ), @@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> { "Polygon", [], None, - "{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + "{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> { "Star", [], None, - "{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + "{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top point; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> { "3D Box", [], None, - "{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}", + "{x, y, width, height, angleX=30 (degrees about the level axis: positive tips the top away from you), angleY=30 (degrees about the upright axis: positive turns the right side away from you), angleZ=0 (degrees clockwise in the page), parallelX=false, parallelY=true, parallelZ=false} → {id}", has_doc, box3d ), @@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> { "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}", + "{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (as addon.shapes.rectangle, ellipse, polygon and star take them: an ellipse's counter-clockwise from 3 o'clock, the others' clockwise along the outline), arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?: degrees (as addon.shapes.box3d: positive tips the top, or turns the right side, away from you), angleZ?: degrees clockwise in the page, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}", has_selection, configure ), @@ -131,6 +131,8 @@ fn insert_custom(s: &mut Session, label: &str, live: Option<LiveShape>, cs: Cust && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) { cs.write_to_node(n); + // A shape drawn pixel-aligned (Align New Objects to Pixel Grid) snaps its stored outline. + super::super::object::snap_if_aligned(n); } Ok(val) } @@ -270,6 +272,7 @@ fn box3d(s: &mut Session, p: &Value) -> Result<Value> { && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) { cs.write_to_node(n); + super::super::object::snap_if_aligned(n); } Ok(val) } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index bc1d4e4f25..537e6bfe75 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -21,7 +21,7 @@ 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::typemenu::text_ids; +use super::super::typemenu::{bake_dynamic_text, text_ids}; use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; @@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> { "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}", + "{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; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. 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 ), @@ -230,8 +230,9 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> { /// `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. +/// object's own text space, so its transform stays). Type on a Path Options are dropped, and +/// Dynamic Text is turned off at the sizes it draws the text at. None for other type, or when it +/// can't be placed. fn released_text(t: &TextObject) -> Option<TextObject> { let TextKind::OnPath { path, .. } = &t.kind else { return None }; let db = vectorcraft_text::FontDb::global(); @@ -244,6 +245,8 @@ fn released_text(t: &TextObject) -> Option<TextObject> { (p.x.is_finite() && p.y.is_finite()).then_some(p) })?; let mut out = t.clone(); + // Point type has no brackets to fit: it keeps the sizes the path drew it at. + bake_dynamic_text(&mut out); out.kind = TextKind::Point; out.path_effect = Default::default(); out.path_align = Default::default(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 024358adfe..fb86fa7852 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -19,12 +19,12 @@ //! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the //! image as its Contents row says; new ones go right below that row. -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::appearance::SharedStack; -use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; use vectorcraft_geom::Rect; use super::edit::{outermost, roots_of, selected_roots}; @@ -32,8 +32,8 @@ use super::opacitymask::percent; use super::paint::paint_from; use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs}; use super::{ - CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, id_param, ids_param, index, leaf_targets, - ok, paint_targets, str_param, switch_or, targets, + CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, ids_param, index, leaf_targets, + object_param, ok, paint_targets, str_param, switch_or, targets, }; use crate::EngineError; @@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}", has_doc, copy_from ), @@ -726,8 +726,8 @@ fn clear(n: &mut Node) { fn transfer(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "appearance.transfer"; - let source = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; - let target = id_param(p, "target").ok_or_else(|| bad(C, "missing `target` id"))?; + let source = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?; + let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing `target` id"))?; if source == target { return Err(bad(C, "`source` and `target` are the same object")); } @@ -1189,7 +1189,7 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> { .iter() .filter_map(|id| d.node(*id)) .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) - .flat_map(|n| n.children().into_iter().flatten().filter(|c| c.visible && !c.locked).map(|c| c.id)) + .flat_map(|n| n.children().into_iter().flatten().filter(|c| c.visible && !c.locked && !c.is_ruler_guide()).map(|c| c.id)) .collect(); if ids.is_empty() { return Err(bad("appearance.targetContents", "select a group or layer with visible, unlocked members")); @@ -1198,10 +1198,10 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })) } -/// Sample enabled attributes, refusing object transparency that a text range cannot store. +/// Sample enabled attributes with transform-aware character dimensions and atomic validation. fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "appearance.copyFrom"; - let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; + let clicked = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?; let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?); let defaults_only = switch_or(p, "defaultsOnly", false, C)?; if defaults_only && (reverse || append || p.get("ids").is_some()) { @@ -1270,9 +1270,6 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?, }; let picked = Picked::of(&node); - if !reverse && !defaults_only { - s.eyedropper_sample = Some(node); - } // The highlighted characters' type objects and ranges: after Select All in threaded text, all // the text of every frame of the story, except a frame the attributes come from, in place of // the object selection. @@ -1285,6 +1282,15 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { Some((id, start, end)) if targets.contains(&id) => vec![(id, Some((start, end)))], _ => vec![], }; + let target_ids = || targets.iter().copied().filter(|_| ranges.is_empty()).chain(ranges.iter().map(|(id, _)| *id)); + // Prepare every dimensional copy before changing defaults or the remembered sample. A bad + // source or target transform must refuse the entire pick, including a multi-frame range. + let characters = if attrs.character && !append { + let d = &s.doc()?.doc; + copied_character_styles(&node, target_ids().filter_map(|id| d.node(id)))? + } else { + HashMap::new() + }; // Character styles cannot represent object transparency. Refuse before even changing // paint defaults; applying it to the object would also alter the unselected characters. if attrs.appearance.transparency { @@ -1298,11 +1304,33 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { } } } - if !reverse { - picked.to_defaults(s, &attrs.appearance); - } + // The session's bounds check follows the selection. Check text targets reached through + // explicit IDs, a reverse pick, or a highlighted story as well. Paragraph changes can + // move point text even when character copying is disabled. + let text_ids: Vec<_> = if attrs.paragraph && !append && picked.text.is_some() { + let d = &s.doc()?.doc; + target_ids().filter(|id| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))).collect() + } else { + characters.keys().copied().collect() + }; + let check_text_bounds = |d: &Document| { + if !text_ids.is_empty() && !crate::sanity::objects_in_range(d, &text_ids) { + return Err(bad(C, "sampled text would exceed the canvas (coordinates out of range)")); + } + Ok(()) + }; + // Remember the pick only after the document edit has passed its own validation. + let finish = |s: &mut Session, ids: &[NodeId]| { + if !reverse { + if !defaults_only { + s.eyedropper_sample = Some(node); + } + picked.to_defaults(s, &attrs.appearance); + } + json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }) + }; if (targets.is_empty() && ranges.is_empty()) || attrs.is_empty() { - return Ok(json!({ "ids": [] })); + return Ok(finish(s, &[])); } if !ranges.is_empty() { let ids: Vec<NodeId> = ranges.iter().map(|(f, _)| *f).collect(); @@ -1312,24 +1340,26 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs))); let placed = picked.placed(Some(t.local_bounds())); - vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs)); + vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| Picked::run(st, &placed, &attrs, characters.get(&id))); if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) { t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone()); } super::typecmd::refresh_bounds(t); } + check_text_bounds(d)?; Ok(count_changed(d, &before, &ids)) })?; - return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })); + return Ok(finish(s, &ids)); } // When every target comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Eyedropper", |d| { for id in &targets { if let Some(n) = d.node_mut(*id) { - picked.apply(n, &attrs, append); + picked.apply(n, &attrs, append, characters.get(id)); } } + check_text_bounds(d)?; // The paints the pick wrote, with a weight going with the paint of its stroke, as in `set_item`. `append` adds // only the colors of the visible rows the source has. let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke); @@ -1369,7 +1399,59 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> { let object = super::graph::capture_series_object_opacity(d, &objects); Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object)) })?; - Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() })) + Ok(finish(s, &targets)) +} + +/// Read source typography in document space, then compensate for each target's transform. +/// Paint stays in its existing sampling path; character scale never changes object placement. +fn copied_character_styles<'a>(source: &Node, targets: impl Iterator<Item = &'a Node>) -> Result<HashMap<NodeId, CharStyle>> { + const C: &str = "appearance.copyFrom"; + let mut styles = HashMap::new(); + let NodeKind::Text(source) = &source.kind else { return Ok(styles) }; + let Some(run) = source.runs.first() else { return Ok(styles) }; + let mut targets = targets + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((n.id, t)), + _ => None, + }) + .peekable(); + if targets.peek().is_none() { + return Ok(styles); + } + let effective = source.effective_char_style(&run.style).ok_or_else(|| bad(C, "source text transform is collapsed or unrepresentable"))?; + if !copied_dimensions_fit(&run.style, &effective) { + return Err(bad(C, "character dimensions cannot be represented with the source text transform")); + } + for (id, text) in targets { + let scale = text.style_scale().ok_or_else(|| bad(C, "target text transform is collapsed or unrepresentable"))?; + let mut local = effective.clone(); + local.size /= scale.points; + local.leading = local.leading.map(|v| v / scale.points); + local.baseline_shift /= scale.points; + local.tcy_up_down /= scale.points; + local.tcy_left_right /= scale.points; + local.h_scale /= scale.horizontal; + // As with dimensional type commands, reject overflow and underflow before layout. + if !copied_dimensions_fit(&effective, &local) { + return Err(bad(C, "character dimensions cannot be represented with the target text transform")); + } + styles.insert(id, local); + } + Ok(styles) +} + +/// Bound each converted type dimension and refuse loss to zero before layout reads it. +fn copied_dimensions_fit(from: &CharStyle, to: &CharStyle) -> bool { + [ + (from.size, to.size), + (from.leading.unwrap_or(0.0), to.leading.unwrap_or(0.0)), + (from.baseline_shift, to.baseline_shift), + (from.tcy_up_down, to.tcy_up_down), + (from.tcy_left_right, to.tcy_left_right), + (from.h_scale, to.h_scale), + ] + .iter() + .all(|(from, to)| to.is_finite() && to.abs() <= crate::MAX_COORD && (*from == 0.0 || *to != 0.0)) } /// What the Eyedropper picks up from an object. @@ -1422,14 +1504,17 @@ impl Picked { /// Copy character attributes and the enabled paint attributes through the same path for /// whole text objects and highlighted character ranges. - fn run(&self, st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs) { - if let Some((cs, _)) = self.text.as_ref().filter(|_| a.character) { + fn run(st: &mut CharStyle, placed: &Appearance, a: &EyedropperAttrs, character: Option<&CharStyle>) { + if let Some(cs) = character { *st = CharStyle { fill: std::mem::take(&mut st.fill), stroke: std::mem::take(&mut st.stroke), stroke_width: st.stroke_width, overprint_fill: st.overprint_fill, overprint_stroke: st.overprint_stroke, + // The space before a line's first character belongs to where the character is, + // not to how it looks: a sample from one doesn't move the target's (#5111). + kerning_before: st.kerning_before, ..cs.clone() }; } @@ -1439,7 +1524,7 @@ impl Picked { /// Apply attributes `a` to `n`. `append` adds the fills and strokes (and effects) on top of its /// stack instead. Type takes the paints on its characters, and character and paragraph /// attributes from type. - fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool) { + fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool, character: Option<&CharStyle>) { let ap = &a.appearance; if ap.transparency { n.opacity = self.opacity; @@ -1456,7 +1541,7 @@ impl Picked { let placed = self.placed(Some(t.local_bounds())); let text = self.text.as_ref(); for r in &mut t.runs { - self.run(&mut r.style, &placed, a); + Self::run(&mut r.style, &placed, a, character); } if let Some((_, para)) = text.filter(|_| a.paragraph) { // The source's first paragraph's attributes, on every paragraph. diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 0b57565af4..1ebde5c026 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -116,13 +116,15 @@ pub(crate) fn art_under(doc: &vectorcraft_doc::Document, id: NodeId, out: &mut V let Some(n) = doc.node(id) else { return }; if n.is_layer() { if let Some(kids) = n.children() { - for c in kids { + for c in kids.iter().filter(|c| !c.is_ruler_guide()) { art_under(doc, c.id, out); } } return; } - out.push(id); + if !n.is_ruler_guide() { + out.push(id); + } } fn add(s: &mut Session, p: &Value) -> Result<Value> { diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index b58af91ff8..981f85e6f5 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -11,7 +11,9 @@ use std::collections::HashSet; use std::sync::{Arc, LazyLock}; use serde_json::{Value, json}; -use vectorcraft_brush::{self as brush, ArtBrush, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation}; +use vectorcraft_brush::{ + self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation, +}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes}; @@ -21,7 +23,7 @@ use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::patterncmds::add_pattern; use super::swatch::str_list; -use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem}; +use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem}; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param}; /// The extension of saved brush libraries: native documents. @@ -169,9 +171,11 @@ pub struct BuiltinBrushLibrary { pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, + BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, + BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, ]; /// Built-in library `id`, made once. @@ -289,6 +293,31 @@ fn calligraphic_nibs() -> BrushLibrary { built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes) } +/// A bristle brush: `shape`, then size (pt), bristle length, density, thickness, paint opacity +/// and stiffness (%). +fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, opacity, stiffness]: [f64; 6]) -> Brush { + Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) } +} + +/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for +/// blending and texture. +fn bristle_brushes() -> BrushLibrary { + use BristleShape::*; + let brushes = vec![ + bristle("Fine Liner", RoundPoint, [2.0, 140.0, 30.0, 30.0, 90.0, 75.0]), + bristle("Pointed Flat", FlatPoint, [5.0, 120.0, 55.0, 35.0, 80.0, 60.0]), + bristle("Stubby Round", RoundBlunt, [8.0, 60.0, 70.0, 50.0, 85.0, 80.0]), + bristle("Dry Scrub", FlatBlunt, [10.0, 40.0, 25.0, 60.0, 60.0, 95.0]), + bristle("Soft Dome", RoundCurve, [12.0, 160.0, 85.0, 20.0, 45.0, 25.0]), + bristle("Filbert", FlatCurve, [9.0, 110.0, 65.0, 40.0, 70.0, 45.0]), + bristle("Angled Round", RoundAngle, [7.0, 130.0, 50.0, 35.0, 75.0, 55.0]), + bristle("Angled Flat", FlatAngle, [11.0, 100.0, 60.0, 45.0, 80.0, 65.0]), + bristle("Fan Blender", RoundFan, [16.0, 220.0, 40.0, 15.0, 35.0, 20.0]), + bristle("Grass Fan", FlatFan, [20.0, 260.0, 15.0, 25.0, 65.0, 35.0]), + ]; + built("Bristle Brushes", Document::new(100.0, 100.0), brushes) +} + fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brush { let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() }); Brush { name: name.into(), kind } @@ -416,6 +445,35 @@ fn game_trails() -> BrushLibrary { built("Game Trails", Document::new(100.0, 100.0), brushes) } +/// Energy Beams: art brushes for laser, plasma and charge strokes (original game VFX art). +fn energy_beams() -> BrushLibrary { + let laser = { + let n = 32; + let half = |x: f64| 1.6 * (1.0 - (x / 100.0 - 0.5).abs() * 1.6).max(0.12); + let xs = |i: usize| 100.0 * i as f64 / n as f64; + let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect(); + pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x)))); + PathData::single(SubPath::polyline(&pts, true)) + }; + let plasma = band(100.0, 2.2, 48, |x| 4.0 * (x / 100.0 * std::f64::consts::PI).sin()); + let charge = band(100.0, 1.6, 56, |x| 3.5 * (x / 100.0 * std::f64::consts::TAU).sin()); + let spark = group(vec![ + black(shapes::rounded_rectangle(Rect::new(0.0, -1.2, 10.0, 1.2), 0.8)), + black(shapes::rounded_rectangle(Rect::new(18.0, -0.9, 28.0, 0.9), 0.7)), + black(shapes::rounded_rectangle(Rect::new(36.0, -1.4, 48.0, 1.4), 0.9)), + black(shapes::rounded_rectangle(Rect::new(56.0, -0.8, 66.0, 0.8), 0.6)), + black(shapes::rounded_rectangle(Rect::new(74.0, -1.1, 86.0, 1.1), 0.8)), + black(shapes::rounded_rectangle(Rect::new(92.0, -0.7, 100.0, 0.7), 0.5)), + ]); + let brushes = vec![ + art("Laser Bolt", black(laser), Colorization::Tints), + art("Plasma Arc", black(plasma), Colorization::Tints), + art("Charge Wave", black(charge), Colorization::Tints), + art("Spark Trail", spark, Colorization::Tints), + ]; + built("Energy Beams", Document::new(100.0, 100.0), brushes) +} + // ---------- commands ---------- fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo { @@ -432,6 +490,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary> if let Some(found) = s.brush_libraries.get(key) { return Some(found); } + if let Some(found) = concealed_library_id(s, key).and_then(|id| s.brush_libraries.get(&id)) { + return Some(found); + } if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { return Some((builtin_info(b), builtin_library(key)?)); } @@ -446,20 +507,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc< fn list(s: &mut Session, _: &Value) -> Result<Value> { s.brush_libraries.rescan(); + let concealed = concealed_library_ids(s, []); let libs: Vec<Value> = libraries(s) .into_iter() .map(|l| { let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len()); - json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)}) + let (id, path) = (shown_id(&concealed, &l.id), s.brush_libraries.shown_path(&l.id)); + json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path}) }) .collect(); - Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() })) + Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.shown_user_dir() })) } fn get(s: &mut Session, p: &Value) -> Result<Value> { let (info, lib) = library_param(s, p, "brush.library")?; let brushes: Vec<Value> = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect(); - Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes})) + Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "brushes": brushes})) } fn add(s: &mut Session, p: &Value) -> Result<Value> { @@ -515,7 +578,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n)); let applied: Vec<u64> = paths.iter().map(|id| id.0).collect(); - Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied})) + Ok(json!({"library": shown_library_id(s, &info.id), "names": doc_names, "added": added, "existing": existing, "applied": applied})) } fn save(s: &mut Session, p: &Value) -> Result<Value> { @@ -541,5 +604,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> { } BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e)) })?; - Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 85c1412f0c..fb8af2b11e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -33,10 +33,10 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; use brushes::{ - brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove, - brush_selection_art, brush_set_current, brush_unused, expand_brush, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, + brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; -pub(crate) use dynamic::{edit_part, part_only, selected_part}; +pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; use symbols::selected_instances; pub(crate) use symbols::{ @@ -45,7 +45,7 @@ pub(crate) use symbols::{ }; use symbols::{ symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options, - symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, + symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_sort, symbol_spray, symbol_unused, symbol_update, }; const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES; @@ -67,6 +67,24 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, brush_selection_art ), + cmd!( + "brush.placeArt", + "Place Brush Art", + [], + None, + "{name, x?, y?} place a copy of the art a scatter, art or pattern brush is made of, centered on (x, y) (default: the center of the first artboard), and select it, as dragging the brush from the Brushes panel onto an empty part of the canvas does; a pattern brush places its tiles left to right (side, outer corner, inner corner, start, end; the ones it has art for) 10 pt apart, each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile, with an unpainted rectangle at the back of a tile that has a repeat frame marking that frame; a calligraphic or bristle brush is refused → {id}", + has_doc, + brush_place_art + ), + cmd!( + "brush.replaceArt", + "Replace Brush Art", + [], + None, + "{name, ids?|id?, applyToStrokes?: true} make the selected art (several objects become one group, as in brush.new) the art of a scatter, art or pattern brush, keeping its other options, as Alt-dragging (Option-dragging on macOS) art onto the brush in the Brushes panel does; a pattern brush takes a group named for one of its tiles, or a group of such groups (as brush.placeArt places them), tile by tile (of two named for one tile, the frontmost), each with the repeat frame an unpainted rectangle at its back marks (other tiles stay as they are), and other art as its side tile; when strokes use the brush and applyToStrokes is false, the brush and its strokes stay as they were and a copy of the brush with the new art, named `<name> copy`, goes after it and becomes the current brush; otherwise the strokes redraw with the new art; one undo step; refused for a calligraphic or bristle brush, with nothing selected, and for art (or a tile) with no width → {name: the brush that has the new art}", + has_doc, + brush_replace_art + ), cmd!( "brush.apply", "Apply Brush", @@ -144,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -312,6 +330,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, symbol_unused ), + cmd!( + "symbol.sortByName", + "Sort by Name", + ["Window", "Symbols"], + None, + "{} sort the document's symbols by name, ignoring case (symbols whose names differ only in case keep their order), as one undo step; the current symbol stays current; no undo step is added when they are already in order", + has_doc, + symbol_sort + ), cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances), cmd!( "symbol.spray", diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index cf5dedb6bd..1f63076cfd 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -239,7 +239,7 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> { && v.get(k).is_none() { let art = selection_art(s, p)?.ok_or_else(|| bad(C, format!("{ty} brushes need selected art (or params.{k})")))?; - if art.geometric_bounds().is_none_or(|b| b.width() <= 1e-6) { + if !has_width(&art, &s.doc()?.doc.symbol_boxes()) { return Err(bad(C, "the selected art has no width")); } v[k] = serde_json::to_value(&art).unwrap_or_default(); @@ -249,6 +249,12 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "name": name })) } +/// Whether art `n` has width for a brush to be made of, with symbol instances measured by their +/// symbols' art in `symbols`. +fn has_width(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> bool { + n.geometric_bounds_with(symbols).is_some_and(|b| b.width() > 1e-6) +} + /// Refuses `name` for a bristle brush when it has more than [`Bristle::MAX_NAME_CHARS`] characters. fn bristle_name_fits(cmd: &str, name: &str) -> Result<()> { let (count, max) = (name.chars().count(), Bristle::MAX_NAME_CHARS); @@ -367,6 +373,12 @@ fn art_brushes(n: &Node, out: &mut Vec<String>) { pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> { let d = &s.doc()?.doc; let lib = brush::library(d); + let names = brush_unused_in(d, &lib); + Ok(json!({ "names": names })) +} + +/// The brushes of `lib` no stroke in `d` paints with, in library order ([`brush_unused`]). +fn brush_unused_in(d: &Document, lib: &[Brush]) -> Vec<String> { let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); @@ -379,8 +391,7 @@ pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> { used.insert(name); } } - let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).filter(|n| !used.contains(*n)).collect(); - Ok(json!({ "names": names })) + lib.iter().map(|b| b.name.clone()).filter(|n| !used.contains(n)).collect() } pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> { @@ -483,6 +494,217 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "name": out })) } +/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it +/// places them; `brush.replaceArt` reads a group of that name as that tile. +const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; + +/// The space between the pattern brush tiles `brush.placeArt` places, in points. +const TILE_GAP: f64 = 10.0; + +/// The message for a brush that is not made of art. +fn no_art(name: &str) -> String { + format!("`{name}` has no art (only scatter, art and pattern brushes do)") +} + +/// Tile `i` of `p` ([`TILE_NAMES`] order): its art and its repeat frame, when it has art. +fn tile(p: &brush::PatternBrush, i: usize) -> Option<(&Node, Option<vectorcraft_geom::Rect>)> { + match i { + 0 => Some((&p.side, p.side_frame)), + 1 => p.outer_corner.as_ref().map(|n| (n, p.outer_corner_frame)), + 2 => p.inner_corner.as_ref().map(|n| (n, p.inner_corner_frame)), + 3 => p.start.as_ref().map(|n| (n, p.start_frame)), + _ => p.end.as_ref().map(|n| (n, p.end_frame)), + } +} + +/// Gives tile `i` of `p` ([`TILE_NAMES`] order) the art `art` and the repeat frame `frame`. The tile +/// no longer comes from a pattern swatch, and a corner draws its own art. +fn set_tile(p: &mut brush::PatternBrush, i: usize, art: Node, frame: Option<vectorcraft_geom::Rect>) { + match i { + 0 => (p.side, p.side_frame, p.side_swatch) = (art, frame, None), + 1 => (p.outer_corner, p.outer_corner_frame, p.outer_corner_swatch, p.outer_source) = (Some(art), frame, None, None), + 2 => (p.inner_corner, p.inner_corner_frame, p.inner_corner_swatch, p.inner_source) = (Some(art), frame, None, None), + 3 => (p.start, p.start_frame, p.start_swatch) = (Some(art), frame, None), + _ => (p.end, p.end_frame, p.end_swatch) = (Some(art), frame, None), + } +} + +/// The art `brush.placeArt` places for brush `b`, in the brush's own coordinates: a scatter or art +/// brush's art, or a pattern brush's tiles in a row, each in a group named for its tile +/// ([`TILE_NAMES`]), with an unpainted rectangle at the back of a tile that has a repeat frame +/// marking that frame. `None` for a brush that is not made of art. Symbol instances in the art are +/// measured by their symbols' art in `symbols`. +fn placed_art(b: &Brush, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Node> { + match &b.kind { + BrushKind::Scatter(sc) => Some(sc.art.clone()), + BrushKind::Art(a) => Some(a.art.clone()), + BrushKind::Pattern(pb) => { + let mut tiles = vec![]; + let mut x = 0.0; + for (i, tile_name) in TILE_NAMES.iter().enumerate() { + let Some((art, frame)) = tile(pb, i) else { continue }; + let mut children = vec![]; + if let Some(f) = frame { + let marker = Node::path( + NodeId(0), + vectorcraft_geom::shapes::rectangle(f), + vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0), + ); + children.push(Arc::new(marker)); + } + children.push(Arc::new(art.clone())); + let mut g = Node::group(NodeId(0), children); + g.name = Some((*tile_name).to_string()); + let Some(r) = g.geometric_bounds_with(symbols) else { continue }; + // Each tile sits right of the one before it, centered on the line y = 0. + g.transform(vectorcraft_geom::Affine::translate((x - r.x0, -r.center().y)), false); + x += r.width() + TILE_GAP; + tiles.push(Arc::new(g)); + } + Some(Node::group(NodeId(0), tiles)) + } + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => None, + } +} + +/// `brush.placeArt`: a copy of the art brush `name` is made of, centered on (`x`, `y`) (default: the +/// center of the first artboard) in the layer new art goes into, and selected, as one undo step. +/// Scatter and art brushes place their art; pattern brushes place their tiles ([`placed_art`]). +pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "brush.placeArt"; + let name = name_param(p, C)?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(super::Point::ZERO); + let at = super::Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let b = brush::find(d, &name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; + let symbols = d.symbol_boxes(); + let mut art = placed_art(&b, &symbols).ok_or_else(|| bad(C, no_art(&name)))?; + if let Some(r) = art.geometric_bounds_with(&symbols) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Brush Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its +/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. +fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> { + let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; + let unpainted = n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| match i { + AppearanceItem::Fill(f) => f.paint.is_none(), + AppearanceItem::Stroke(st) => st.paint.is_none(), + }); + let [sp] = path.subpaths.as_slice() else { return None }; + let r = n.geometric_bounds()?; + let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; + let at_corners = sp.anchors.len() == 4 + && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) +} + +/// The tiles in `art` for a pattern brush, by tile ([`TILE_NAMES`] order), with their repeat frames: +/// a group named for a tile, as `brush.placeArt` places them, is the art of its tile (an unpainted +/// rectangle at its back marks the tile's frame, [`frame_marker`], and is left out of the art; a +/// group left with one member gives that member), and so is each member of a group whose members +/// are all such groups; any other art is the side tile. +fn tiles_of(art: Node) -> Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> { + let named = |c: &Node| matches!(c.kind, NodeKind::Group { clip: false, .. }) && c.name.as_deref().is_some_and(|n| TILE_NAMES.contains(&n)); + let tiles = match &art.kind { + _ if named(&art) => vec![Arc::new(art)], + NodeKind::Group { children, clip: false } if !children.is_empty() && children.iter().all(|c| named(c)) => children.clone(), + _ => return vec![(0, art, None)], + }; + let mut out: Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> = vec![]; + for t in tiles { + let Some(i) = t.name.as_deref().and_then(|n| TILE_NAMES.iter().position(|x| *x == n)) else { continue }; + let mut g = (*t).clone(); + let mut frame = None; + if let NodeKind::Group { children, .. } = &mut g.kind + && let Some(f) = children.first().and_then(|c| frame_marker(c)) + { + frame = Some(f); + children.remove(0); + } + g.name = None; + // The group `brush.placeArt` put around the tile's art: the art itself goes back, so a + // tile does not gain a group each time it goes out and back. + if let NodeKind::Group { children, clip: false } = &g.kind + && let [only] = children.as_slice() + && g == Node::group(g.id, children.clone()) + { + g = (**only).clone(); + } + // A tile named twice: the frontmost one counts. + out.retain(|(j, ..)| *j != i); + out.push((i, g, frame)); + } + out +} + +/// `brush.replaceArt`: the selected art (or `ids`/`id`; several objects become one group, as in +/// `brush.new`) becomes the art of scatter, art or pattern brush `name`, keeping its other options, +/// as one undo step. A pattern brush takes the tiles `brush.placeArt` places by their names +/// ([`tiles_of`]) and other art as its side tile. When strokes use the brush and `applyToStrokes` is +/// false, the brush and its strokes stay as they were and a copy of the brush with the new art is +/// added after it and becomes the current brush; otherwise the strokes redraw with the new art. +pub(super) fn brush_replace_art(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "brush.replaceArt"; + let name = name_param(p, C)?.to_string(); + let apply = super::switch_or(p, "applyToStrokes", true, C)?; + let mut lib = brush::library(&s.doc()?.doc); + let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; + if lib[i].art().is_empty() { + return Err(bad(C, no_art(&name))); + } + let art = selection_art(s, p)?.ok_or_else(|| bad(C, "nothing selected"))?; + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let check = |n: &Node| if has_width(n, &symbols) { Ok(()) } else { Err(bad(C, "the selected art has no width")) }; + let mut b = lib[i].clone(); + match &mut b.kind { + BrushKind::Scatter(sc) => { + check(&art)?; + sc.art = art; + } + BrushKind::Art(a) => { + check(&art)?; + a.art = art; + } + BrushKind::Pattern(pb) => { + for (t, art, frame) in tiles_of(art) { + check(&art)?; + set_tile(pb, t, art, frame); + } + } + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => return Err(bad(C, no_art(&name))), + } + let used = !brush_unused_in(d, &lib).contains(&name); + if apply || !used { + lib[i] = b; + save_library(s, "Replace Brush Art", lib, &[])?; + return Ok(json!({ "name": name })); + } + b.name = brush::unique_name(&lib, &format!("{} copy", name.trim())); + let copy = b.name.clone(); + lib.insert(i + 1, b); + s.edit("Replace Brush Art", |d, _| { + d.unknown.insert(brush::CURRENT_KEY.into(), json!(copy)); + brush::store(d, &lib); + Ok(()) + })?; + Ok(json!({ "name": copy })) +} + pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> { let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect(); diff --git a/crates/engine/src/cmd/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs index 32edc44f86..f5cef8351e 100644 --- a/crates/engine/src/cmd/brushsym/dynamic.rs +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -2,7 +2,7 @@ //! appearance of objects in the symbol's art and stays linked to the symbol //! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance //! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still -//! there ([`fit_overrides`]). +//! there and draws them ([`fit_overrides`]). use std::sync::Arc; @@ -27,7 +27,7 @@ pub(super) fn type_id(dynamic: bool) -> &'static str { } /// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or -/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art. +/// missing) symbol keeps none, an instance of a dynamic one those its art still draws ([`fit_parts`]). pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { for id in ids { let art = match d.node(*id) { @@ -40,7 +40,7 @@ pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { let Some(n) = d.node_mut(*id) else { continue }; let mut e = n.extras_mut(); match art { - Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art), + Some(art) => fit_parts(&mut e.symbol_overrides, &art), None => e.symbol_overrides.clear(), } } @@ -137,7 +137,7 @@ fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> { /// stroke has a Convert to Shape or Outline Object effect. fn paint_refusal(n: &Node, key: &str, cmd: &str) -> Option<EngineError> { Some(match &n.kind { - NodeKind::Path { guide: true, .. } => bad(cmd, format!("{key} cannot be set on a guide")), + NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => bad(cmd, format!("{key} cannot be set on a guide")), NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) | NodeKind::Group { .. } | NodeKind::Layer { .. } => return None, NodeKind::Image(_) => { let effects = if key == "fill" { n.appearance.fill().map(|f| &f.effects) } else { n.appearance.stroke().map(|s| &s.effects) }; @@ -177,17 +177,42 @@ fn check_paint_kinds(p: &Value, art: &Node, path: &[u32], cmd: &str) -> Result<( fn solid_fill_check(p: &Value, art: &Node, path: &[u32], fill: Option<&vectorcraft_color::Paint>, cmd: &str) -> Result<()> { let asked = p.get("fill").is_some_and(|v| !v.is_null()); let is_instance = symbol_overrides::part(art, path).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })); - let draws_nothing = |f: &vectorcraft_color::Paint| match f { - vectorcraft_color::Paint::Gradient(_) => true, - vectorcraft_color::Paint::Pattern { .. } => true, - vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => false, - }; - if asked && is_instance && fill.is_some_and(draws_nothing) { + if asked && is_instance && fill.is_some_and(|f| !stains(f)) { return Err(bad(cmd, "fill on a symbol instance must be a solid color or none")); } Ok(()) } +/// Can a symbol instance's fill be `f`? An instance stains its art with a solid fill only. +fn stains(f: &vectorcraft_color::Paint) -> bool { + match f { + vectorcraft_color::Paint::Gradient(_) => false, + vectorcraft_color::Paint::Pattern { .. } => false, + vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => true, + } +} + +/// Keep the appearance changes `overrides` that name an object of `art` (a symbol's new art), each +/// without a fill or stroke that object does not draw ([`paint_refusal`], [`stains`]); a change +/// left with nothing in it is dropped. +pub(crate) fn fit_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) { + symbol_overrides::retain_parts(overrides, art); + for o in overrides.iter_mut() { + let Some(n) = symbol_overrides::part(art, &o.path) else { continue }; + let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); + if paint_refusal(n, "fill", FIT).is_some() || (instance && o.fill.as_ref().is_some_and(|f| !stains(f))) { + o.fill = None; + } + if paint_refusal(n, "stroke", FIT).is_some() { + o.stroke = None; + } + } + overrides.retain(|o| !o.is_empty()); +} + +/// The command name [`fit_parts`] gives [`paint_refusal`], whose refusal it does not show. +const FIT: &str = "symbol.update"; + /// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or /// an object of `paint.setFill`'s paint params sets it. fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 4c5cd89edf..b789f600b4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -140,6 +140,27 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> { Ok(json!({ "names": names })) } +/// `symbol.sortByName`: the symbols in name order, ignoring case; a stable sort, so names that +/// differ only in case keep their order. The current symbol is stored by name first, so a document +/// whose current symbol is its first one keeps that symbol current. Nothing is changed, and no undo +/// step is added, when the symbols are already in order. +pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> { + let key = |sym: &Symbol| sym.name.to_lowercase(); + let d = &s.doc()?.doc; + if d.symbols.is_sorted_by_key(key) { + return ok(); + } + let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next()); + s.edit("Sort by Name", |d, _| { + if let Some(name) = current { + d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); + } + d.symbols.sort_by_cached_key(key); + Ok(()) + })?; + ok() +} + fn symbol_names(d: &Document) -> Vec<String> { d.symbols.iter().map(|s| s.name.clone()).collect() } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index d392449247..53e1b655a1 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -29,8 +29,8 @@ use super::edit::{outermost, selected_roots}; use super::paint::paint_from; use super::pathops::{Beside, shape_node}; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, named_ids, - number_or, point_param, str_param, switch_or, + CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, named_ids, number_or, + object_param, point_param, str_param, switch_or, }; mod live_paint; @@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", has_doc, lp_fill ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 207182d40a..e5e7757486 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,7 +1,7 @@ use super::{ Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point, - Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, id_param, ids_json, - is_live_paint, json, number_or, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, + Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, + json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -272,9 +272,38 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "livePaint.fill"; let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> { + let values = input + .as_array() + .filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS) + .ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?; + let points: Vec<_> = values + .iter() + .map(|point| { + let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?; + let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?; + let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?; + let point = Point::new(x, y); + if !finite(point) { + return Err(bad(C, "points must be finite canvas points")); + } + Ok(point) + }) + .collect::<Result<_>>()?; + if points.first() != Some(&start) { + return Err(bad(C, "path chunks must share their boundary point")); + } + Ok(points) + }; + let points = p.get("points"); + let continuation = match p.get("continuation") { + None => &[][..], + Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(), + Some(_) => return Err(bad(C, "continuation requires points")), + }; crate::cmd::paint::check_keep_model(p, C)?; let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone()); - let group = id_param(p, "group"); + let group = object_param(p, "group", C)?; let roots = if group.is_none() { root_ids(s, p)? } else { vec![] }; let (g, face) = s.edit("Live Paint Bucket", |d, sel| { let gid = match group { @@ -302,7 +331,33 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> { .and_then(|n| b::visible_face_at(n, pt)) .map(|f| f.id) .ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?; - d.node_mut(fid).ok_or(EngineError::NoNode(fid))?.appearance.set_fill(paint.clone()); + let mut targets = std::collections::BTreeSet::from([fid]); + if let Some(points) = points { + let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; + // Use the existing region-crossing probes, so even a face narrower than the distance + // between pointer events is filled. Reversing matches visible_face_at's front first. + let faces: Vec<_> = b::faces(n).into_iter().rev().filter(|f| f.visible).collect(); + let mut face_ids = vec![]; + let mut regions = vec![]; + for f in faces { + if let Some(path) = f.path_data() + && let Some(bounds) = path.bounds() + { + face_ids.push(f.id); + regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds)); + } + } + let map = b::BuilderMap { regions, ..Default::default() }; + let mut last = pt; + for input in std::iter::once(points).chain(continuation) { + let chunk = parse_chunk(input, last)?; + last = chunk.last().copied().unwrap_or(last); + targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied())); + } + } + for target in targets { + d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); + } Ok((gid, fid)) })?; s.remember_paint(&paint); @@ -312,7 +367,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "livePaint.strokeEdge"; let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; - let g = id_param(p, "group").ok_or_else(|| bad(C, "missing group"))?; + let g = object_param(p, "group", C)?.ok_or_else(|| bad(C, "missing group"))?; crate::cmd::paint::check_keep_model(p, C)?; let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone()); let width = number_or(p, "width", s.paint.stroke_width.max(0.0), C)?; @@ -335,7 +390,10 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> { } pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> { - let g = id_param(p, "group").or_else(|| id_param(p, "id")).ok_or_else(|| bad("livePaint.info", "missing group"))?; + let g = match object_param(p, "group", "livePaint.info")? { + Some(g) => g, + None => object_param(p, "id", "livePaint.info")?.ok_or_else(|| bad("livePaint.info", "missing group"))?, + }; let d = &s.doc()?.doc; let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad("livePaint.info", format!("{g} is not a Live Paint group")))?; let faces: Vec<Value> = b::faces(n) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 5ff09dc284..9e52454de1 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -322,7 +322,18 @@ impl Clipboard { /// Every object of `src` (each top-level layer's contents) with its resources, for Place and /// pasting outside SVG. Their layers don't count for Paste Remembers Layers. pub fn from_document(src: &Document) -> Self { - let nodes = src.layers.iter().flat_map(|l| l.children().into_iter().flatten()).map(|n| (**n).clone()).collect(); + // Ruler guides are not objects: the ones of `src`'s layers and sublayers stay behind. + let nodes = src + .layers + .iter() + .flat_map(|l| l.children().into_iter().flatten()) + .filter(|n| !n.is_ruler_guide()) + .map(|n| { + let mut n = (**n).clone(); + n.strip_ruler_guides(); + n + }) + .collect(); Self::gather(src, nodes) } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index ac082d7a05..bbc56dbc15 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -19,8 +19,8 @@ use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; use super::edit::selected_roots; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, bool_or, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param, - str_param, unique_name, + CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param, switch_or, + text_param, unique_name, }; pub fn specs() -> Vec<CommandSpec> { @@ -166,13 +166,15 @@ pub(crate) struct Scope { } impl Scope { - pub(crate) fn of(p: &Value) -> Self { - Self { - fill: bool_or(p, "fill", true), - stroke: bool_or(p, "stroke", true), - images: bool_or(p, "includeImages", true), - patterns: bool_or(p, "includePatterns", true), - } + /// The scope `p` gives; each switch left out (or null) is on. A switch that is not true or false, + /// such as `"false"`, is an error that names `cmd`. + pub(crate) fn of(p: &Value, cmd: &str) -> Result<Self> { + Ok(Self { + fill: switch_or(p, "fill", true, cmd)?, + stroke: switch_or(p, "stroke", true, cmd)?, + images: switch_or(p, "includeImages", true, cmd)?, + patterns: switch_or(p, "includePatterns", true, cmd)?, + }) } } @@ -414,18 +416,18 @@ impl ColorVisitor for Visit<'_, '_> { } pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> { - run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f)) + run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f)) } /// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel. fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> { - run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) }) + run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) }) } /// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch /// link and tint. pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> { - run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p), f, links)) + run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links)) } /// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`; @@ -462,7 +464,7 @@ fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) - pub(crate) fn left_out(d: &Document, iso: Option<NodeId>, roots: &[NodeId]) -> Vec<(NodeId, bool)> { fn visit(n: &Node, hidden: bool, locked: bool, all: &HashSet<NodeId>, board_locked: &dyn Fn(&Node) -> bool, out: &mut Vec<(NodeId, bool)>) { for c in n.children().into_iter().flatten() { - if c.is_template() { + if c.is_template() || c.is_ruler_guide() { continue; } let (hidden, locked) = (hidden || !c.visible, locked || c.locked); @@ -548,8 +550,9 @@ fn saturate(s: &mut Session, p: &Value) -> Result<Value> { fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "edit.colors.adjustBalance"; check_numbers(p, &["r", "g", "b", "c", "m", "y", "k", "gray", "tint"], C)?; + let convert = switch_or(p, "convert", false, C)?; let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some()); - let mode = match str_param(p, "mode") { + let mode = match text_param(p, "mode", C)? { Some(m) => m.to_ascii_lowercase(), None if given(&["c", "m", "y", "k"]) => "cmyk".into(), None if given(&["gray"]) => "gray".into(), @@ -592,11 +595,10 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> { (*tint, *c) = (t, base.tinted(t)); true }; - return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p), &shift)); + return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p, C)?, &shift)); } other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))), }; - let convert = bool_or(p, "convert", false); let f = move |c| { let out = adjust(c); if convert { out } else { keep_model(c, out) } @@ -703,7 +705,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> { fn harmony(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "color.harmony"; let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?; - let rule = str_param(p, "rule").ok_or_else(|| bad(C, "missing `rule`"))?; + let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?; let rule = Harmony::parse(rule).ok_or_else(|| { let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect(); bad(C, format!("unknown rule `{rule}` ({})", ids.join("|"))) @@ -713,7 +715,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> { if let Some(n) = p.get("steps").and_then(Value::as_u64) { opts.steps = n.min(u32::MAX as u64) as u32; } - if let Some(v) = str_param(p, "variation") { + if let Some(v) = text_param(p, "variation", C)? { opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?; } if let Some(a) = p.get("amount").and_then(Value::as_f64) { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 03b171de71..da7dc42ece 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -582,7 +582,7 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo } } if let Some(ch) = n.children_mut() { - for c in ch.iter_mut() { + for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) { map_more_colors(Arc::make_mut(c), f); } } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 407b20a1ae..37473cc59f 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -17,19 +17,43 @@ pub fn specs() -> Vec<CommandSpec> { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg (about centre)} → {id}", + "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), - cmd!("shape.ellipse", "Ellipse", [], None, "{x, y, width, height, rotation?: deg (about centre)} → {id}", has_doc, ellipse), - cmd!("shape.polygon", "Polygon", [], None, "{cx, cy, radius, sides=6, rotation?: deg} → {id}", has_doc, polygon), - cmd!("shape.star", "Star", [], None, "{cx, cy, radius1, radius2, points=5, rotation?: deg} → {id}", has_doc, star), + cmd!( + "shape.ellipse", + "Ellipse", + [], + None, + "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}", + has_doc, + ellipse + ), + cmd!( + "shape.polygon", + "Polygon", + [], + None, + "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + has_doc, + polygon + ), + cmd!( + "shape.star", + "Star", + [], + None, + "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + has_doc, + star + ), cmd!( "shape.flare", "Flare", [], None, - "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg), seed?} → {id}", + "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}", has_doc, flare ), @@ -49,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> { "Rectangular Grid", [], None, - "{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}", + "{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rect_grid ), @@ -58,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> { "Polar Grid", [], None, - "{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}", + "{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, polar_grid ), @@ -85,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Text", [], None, - "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -138,7 +162,8 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 { } } -/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. +/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or +/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on. fn insert_look_turned( s: &mut Session, label: &str, @@ -156,6 +181,7 @@ fn insert_look_turned( let id = d.alloc_id(); let mut n = Node::new(id, kind); look.apply(d, &mut n); + super::object::align_new_object(d, &mut n); n.name = name; n.bbox_angle = bbox_angle; let mut into = None; @@ -488,6 +514,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> { n.name = Some(name.into()); n.blend = BlendMode::Screen; n.opacity = op; + super::object::align_new_object(d, &mut n); std::sync::Arc::new(n) }) .collect(); @@ -579,6 +606,7 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>, Node::path(d.alloc_id(), pd, Appearance::default()) }; look.apply(d, &mut n); + super::object::align_new_object(d, &mut n); n.bbox_angle = bbox_angle; std::sync::Arc::new(n) }) @@ -728,7 +756,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> { let w = f64_or(a, "width", 200.0); let h = f64_or(a, "height", 100.0); t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) }; - t.area.fit = new_area_fit(s, a, "text.create")?; + new_area_fit(s, a, "text.create", &mut t)?; } t.system_layout = s.doc()?.doc.setup.system_layout; if bool_or(p, "placeholder", false) { @@ -755,12 +783,14 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> { /// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of /// each paragraph's direction (left, right for Hebrew and Arabic), Japanese punctuation composed -/// with Line-end Punctuation Half Width and Standard burasagari. Imported text keeps its own. +/// with Line-end Punctuation Half Width and Standard burasagari, and Korean words kept whole +/// (Korean Line Break Anywhere off). Imported text keeps its own. pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle { vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Auto, mojikumi: vectorcraft_doc::Mojikumi::LineEndHalf, burasagari: vectorcraft_doc::Burasagari::Standard, + korean_line_break_anywhere: false, ..Default::default() } } @@ -803,11 +833,16 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut Ok(()) } -/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes -/// them), else Auto Size when the "Auto Size New Area Type" preference is on. -pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraft_doc::AreaFit> { +/// The fit new area type `t` gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes +/// them, `block` turning Dynamic Text on), else Auto Size when the "Auto Size New Area Type" +/// preference is on; and Block's `wordGap` and `lineGap`. +pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) -> Result<()> { let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None }; - Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default)) + let (word_gap, line_gap) = super::typecmd::block_gaps(p, c)?; + (t.area.fit, t.dynamic_text) = super::typecmd::fit_param(p, default, false, c)?.unwrap_or((default, false)); + t.area.word_gap = word_gap.unwrap_or(t.area.word_gap); + t.area.line_gap = line_gap.unwrap_or(t.area.line_gap); + Ok(()) } /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index bcaa59426b..2dbb7a9a18 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -15,8 +15,8 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, id_param, - matrix_param, named_id, named_ids, number_or, ok, point_indices, point_param, str_param, switch_or, targets, + CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, }; use crate::EngineError; @@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> { "Liquify", [], None, - "{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}", + "{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle? (deg clockwise: the brush's width axis from level), intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °, positive turns clockwise), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}", has_doc, liquify ), @@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> { "Puppet Warp", [], None, - "{id?|ids? (default: selection), pins: [[x,y]…] (current pin positions), moved: [[x,y]…] (targets, same length), angles?: [deg|null…] (same length: the turn the art takes around each pin, as Alt-dragging around a pin does; null leaves it free), expand?: pt, rest?: bool, auto?: bool (as object.puppetWarp.pins reports; ignored)} as-rigid-as-possible mesh warp of anchors and handles. rest: true = the Puppet Warp tool's pins: `pins` are points on the shape the pins started from (object.puppetWarp.pins), each must be on its mesh, the warp replaces the previous one instead of adding to it, and the pins are kept with the document for Undo (an empty list removes them all, leaving the art as it is)", + "{id?|ids? (default: selection), pins: [[x,y]…] (current pin positions), moved: [[x,y]…] (targets, same length), angles?: [deg|null…] (same length: the turn the art takes around each pin, clockwise, as Alt-dragging around a pin does; null leaves it free), expand?: pt, rest?: bool, auto?: bool (as object.puppetWarp.pins reports; ignored)} as-rigid-as-possible mesh warp of anchors and handles. rest: true = the Puppet Warp tool's pins: `pins` are points on the shape the pins started from (object.puppetWarp.pins), each must be on its mesh, the warp replaces the previous one instead of adding to it, and the pins are kept with the document for Undo (an empty list removes them all, leaving the art as it is)", has_doc, puppet_warp ), @@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> { "Puppet Warp Pins", [], None, - "{id?|ids? (default: selection), expand?: pt} → {ids, pins, moved, angles, expand, rest: true, auto} the Puppet Warp pins on the art: pins = where each sits on the shape they started from, moved = where it is now, angles = the turn it holds (deg, null = free); auto: none placed yet (the tool's automatic pins: the centre and the end of each limb). Change moved/angles (or add/remove pins) and pass it back to object.puppetWarp", + "{id?|ids? (default: selection), expand?: pt} → {ids, pins, moved, angles, expand, rest: true, auto} the Puppet Warp pins on the art: pins = where each sits on the shape they started from, moved = where it is now, angles = the turn it holds (deg clockwise, null = free); auto: none placed yet (the tool's automatic pins: the centre and the end of each limb). Change moved/angles (or add/remove pins) and pass it back to object.puppetWarp", has_doc, puppet_pins ), @@ -305,7 +305,7 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.set"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let t = f64_req(p, "t", C)?.clamp(0.0, 1.0); let (left, right) = (f64_req(p, "left", C)?, f64_req(p, "right", C)?); if !(left.is_finite() && right.is_finite()) || left < 0.0 || right < 0.0 || left.max(right) > 1.0e5 { @@ -362,7 +362,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.copy"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let t = f64_req(p, "t", C)?.clamp(0.0, 1.0); // When the profile comes out as it was (the copy replaces a side of a discontinuous point that has // its widths already), the document and its undo history stay as they are. @@ -382,7 +382,7 @@ fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> { fn width_point_remove(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.remove"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let indices = match (p.get("indices"), p.get("index")) { (Some(a), _) => point_indices(a), (None, Some(i)) => point_indices(&json!([i])), diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index e6e75c1f3a..ff1fbe3591 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -1,7 +1,7 @@ //! Document Info panel data, its categories and the text report (Document Info › Save…, File → //! Package), and Object → Make Pixel Perfect. -use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone", has_doc, info ), @@ -42,7 +42,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [ ("brushes", "Brushes"), ("spotColors", "Spot Colors"), ("patterns", "Pattern Objects"), - ("gradients", "Gradient Swatches"), + ("gradients", "Gradient Objects"), ("symbols", "Symbols"), ("fonts", "Fonts"), ("fontDetails", "Font Details"), @@ -131,7 +131,8 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S /// The Document Info categories of `d` (only `category` when given) from `info` (what /// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the -/// rows of its objects filled or stroked with a pattern. +/// rows of its objects filled or stroked with a pattern and with a gradient. +#[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, @@ -139,6 +140,7 @@ fn sections( images: &[ImageRow], repeats: &[(String, String)], pattern_objects: &[(String, String)], + gradient_objects: &[(String, String)], category: Option<&str>, ) -> Vec<Section> { let names = |k: &str| -> Vec<(String, String)> { @@ -183,7 +185,7 @@ fn sections( "brushes" => names("brushNames"), "spotColors" => names("spotColors"), "patterns" => pattern_objects.to_vec(), - "gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(), + "gradients" => gradient_objects.to_vec(), "symbols" => names("symbols"), "fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(), "fontDetails" => { @@ -254,19 +256,37 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result<String> { Ok(v["text"].as_str().unwrap_or_default().to_string()) } -/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a -/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and -/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the -/// type object's own fills and strokes paint on its characters, so only those runs paint. The type -/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out. +/// The pattern paint `p` uses: the pattern's name. +fn pattern_label(p: &Paint) -> Option<String> { + match p { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + } +} + +/// The gradient paint `p` uses: the name of the gradient swatch it is linked to, else its kind +/// ("Linear gradient", "Radial gradient" or "Freeform gradient"). +fn gradient_label(p: &Paint) -> Option<String> { + match p { + Paint::Gradient(g) => Some(g.swatch.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("{} gradient", g.gradient.kind.label()))), + _ => None, + } +} + +/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient: +/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough +/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and +/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs +/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the +/// renderer lays it out. fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> { let NodeKind::Text(t) = &n.kind else { return None }; - let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); + let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)); let own = n.appearance.items.iter().any(|i| match i { - vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint), - vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint), + vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint), + vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint), }); - if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) { + if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) { return None; } let db = vectorcraft_text::FontDb::global(); @@ -277,42 +297,38 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T Some((t, painted)) } -/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke -/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide -/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint -/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint -/// only where an effect gives them a shape. -fn own_patterns<'a>( +/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own +/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint +/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound +/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose +/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect +/// gives them a shape. +fn own_paints( d: &Document, - n: &'a Node, + n: &Node, members: &HashSet<*const Node>, painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>, -) -> Vec<&'a str> { + label: fn(&Paint) -> Option<String>, +) -> Vec<String> { if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) || painted_runs.is_some_and(|(_, r)| r.is_empty()) + || !n.appearance.items.iter().any(|i| label(i.paint()).is_some()) { return vec![]; } - // The patterns an image's shaped fills and strokes paint (their effects can transform the - // pattern, so they are matched by name). - let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)).then(|| { - vectorcraft_render::effects::image_paint(Some(d), n) - .into_iter() - .filter_map(|(_, _, item)| match item.paint() { - Paint::Pattern { pattern, .. } => Some(pattern.clone()), - _ => None, - }) - .collect() - }); - let mut out: Vec<&str> = vec![]; + // The patterns or gradients an image's shaped fills and strokes paint (their effects can + // transform the paint, so they are matched by label). + let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)) + .then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect()); + let mut out: Vec<String> = vec![]; for item in &n.appearance.items { - let Paint::Pattern { pattern, .. } = item.paint() else { continue }; + let Some(name) = label(item.paint()) else { continue }; let paints = item.visible() && !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) - && shaped.as_ref().is_none_or(|s| s.contains(pattern)); - if paints && !out.contains(&pattern.as_str()) { - out.push(pattern); + && shaped.as_ref().is_none_or(|s| s.contains(&name)); + if paints && !out.contains(&name) { + out.push(name); } } out @@ -342,6 +358,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { let mut fonts = BTreeSet::new(); let mut images: BTreeMap<String, Value> = BTreeMap::new(); let mut image_rows: Vec<ImageRow> = vec![]; + // Whether the request being served may read each linked file (a relative path read from the + // document's folder), checked once per file. + let mut readable: HashMap<String, bool> = HashMap::new(); + let link_doc = super::links::LinkBase::of(st).doc; + let mut may_read = |stored: &str| { + *readable.entry(stored.to_string()).or_insert_with(|| { + let resolved = super::fileio::document_path(stored, link_doc).ok(); + crate::file_access::check_read(resolved.as_deref().unwrap_or(stored)).is_ok() + }) + }; let mut patterns = BTreeSet::new(); let mut symbols = BTreeSet::new(); let mut spot = BTreeSet::new(); @@ -354,6 +380,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { // `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order. let mut pattern_objects: Vec<Value> = vec![]; let mut pattern_rows: Vec<(String, String)> = vec![]; + // `gradient_objects`, `gradient_rows` and `gradients` hold the `gradientObjects` entries, the rows of the objects filled or stroked + // with a gradient, in walk order, and the gradients they use. + let mut gradient_objects: Vec<Value> = vec![]; + let mut gradient_rows: Vec<(String, String)> = vec![]; + let mut gradients = BTreeSet::new(); // The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once. // The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two. let mut seen: HashSet<*const Node> = HashSet::new(); @@ -370,7 +401,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { return; } let k = match &n.kind { - NodeKind::Layer { .. } => None, + // The Guides row counts paths made into guides; ruler guides are not objects. + NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => None, NodeKind::Group { clip: true, .. } => Some("clipGroups"), NodeKind::Group { .. } => Some("groups"), NodeKind::Path { guide: true, .. } => Some("guides"), @@ -389,12 +421,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { Some("textObjects") } NodeKind::Image(im) => { + // A linked file outside a confined request's read roots: `link` is null, and the row + // names the file alone. + let link = im.link.as_ref().map(|l| (l, may_read(&l.path))); images.insert( im.key.clone(), - json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": im.link.as_ref().map(|l| &l.path) }), + json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }), ); let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string()); - image_rows.push((name, im.width, im.height, im.link.as_ref().map(|l| l.path.clone()))); + image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() }))); Some("images") } NodeKind::SymbolInstance { symbol, .. } => { @@ -411,27 +446,17 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { if let Some(k) = k { *counts.entry(k).or_default() += 1; } - // The paint kinds this object's fills and strokes use, each once. - let mut kinds = BTreeSet::new(); - // The patterns this object's fills and strokes use, each once. - let mut used_patterns: Vec<&str> = vec![]; - let painted_runs = painted_runs(d, n); - for pattern in own_patterns(d, n, &members, painted_runs.as_ref()) { - patterns.insert(pattern.to_string()); - used_patterns.push(pattern); - } for item in &n.appearance.items { - let paint = item.paint(); - // Objects counts an object with a pattern when Pattern Objects lists it, below. - if let Paint::Gradient(_) = paint { - kinds.insert("gradients"); - } - if let Paint::Solid { swatch: Some(name), .. } = paint + if let Paint::Solid { swatch: Some(name), .. } = item.paint() && d.swatch(name).is_some_and(|s| s.spot) { spot.insert(name.clone()); } } + // The patterns and the gradients this object's fills and strokes paint, each once. + let painted_runs = painted_runs(d, n); + let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label); + let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label); // The characters' own paints: an inline graphic draws no outline and does not take its // run's paint (a list marker set in its run does), and a stroke with no width paints // nothing. @@ -439,23 +464,32 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { for run in painted.iter().filter_map(|i| t.runs.get(*i)) { let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke); for paint in std::iter::once(&run.style.fill).chain(stroke) { - if let Paint::Pattern { pattern, .. } = paint { - patterns.insert(pattern.clone()); - if !used_patterns.contains(&pattern.as_str()) { - used_patterns.push(pattern); + for (used, label) in + [(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)] + { + if let Some(name) = label(paint) + && !used.contains(&name) + { + used.push(name); } } } } } + // Objects counts the objects that Pattern Objects and Gradient Objects list. if !used_patterns.is_empty() { let name = n.display_name(); + patterns.extend(used_patterns.iter().cloned()); + pattern_rows.push((name.clone(), used_patterns.join(", "))); pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns })); - pattern_rows.push((name, used_patterns.join(", "))); - kinds.insert("patterns"); + *counts.entry("patterns").or_default() += 1; } - for k in kinds { - *counts.entry(k).or_default() += 1; + if !used_gradients.is_empty() { + let name = n.display_name(); + gradients.extend(used_gradients.iter().cloned()); + gradient_rows.push((name.clone(), used_gradients.join(", "))); + gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients })); + *counts.entry("gradients").or_default() += 1; } if n.extras().mask.is_some() { *counts.entry("opacityMasks").or_default() += 1; @@ -505,10 +539,12 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> { "patterns": d.patterns.len(), "patternNames": patterns, "patternObjects": pattern_objects, + "gradientNames": gradients, + "gradientObjects": gradient_objects, }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category); + let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -582,12 +618,14 @@ mod tests { &json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), ) .unwrap(); - s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone(); let i = s.execute("document.info", &json!({})).unwrap(); + // The type's characters take the current gradient fill, so it is a gradient object too. assert_eq!( (i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()), - (Some(1), Some(1), Some(1)) + (Some(1), Some(1), Some(2)) ); + assert_eq!((i["gradientObjects"][0]["id"].clone(), i["gradientObjects"][1]["id"].clone()), (r.clone(), t)); assert_eq!(i["fonts"][0], "Source Sans 3 Regular"); assert_eq!(i["document"]["artboards"][0]["width"], 200.0); s.execute("select.set", &json!({"ids": [r]})).unwrap(); @@ -841,6 +879,124 @@ mod tests { assert!(!text.contains("Unused"), "{text}"); } + /// Document Info › Gradient Objects lists each object filled or stroked with a gradient once, + /// with the gradients it uses (a linked swatch by name, else the gradient's kind), one in a + /// group and a type object whose characters use a gradient included; a gradient swatch no art + /// uses adds no row, paint that draws nothing is left out by the rules Pattern Objects follows, + /// and Objects counts the listed objects. With Selection Only it lists the objects in the + /// selection, each once, and the report writes the same rows. + #[test] + fn info_lists_the_gradient_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = + |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp("linear")})).unwrap(); + s.execute("swatch.new", &json!({"name": "Spare", "gradient": ramp("radial")})).unwrap(); + let (a, b, c, f) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0), square(&mut s, 0.0)); + s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ramp"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a], "gradient": ramp("linear")})).unwrap(); + s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [b], "gradient": ramp("radial")})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("freeform")})).unwrap(); + s.execute("select.set", &json!({"ids": [b, c]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + // A type object whose characters are filled with the gradient. + let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ramp"})).unwrap(); + s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap(); + // A hidden gradient fill and a gradient stroke with no width paint nothing, so neither object is listed. + let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0)); + s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ramp"})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [e], "gradient": ramp("linear")})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap(); + // Type with no characters, or of only spaces and a line break, paints nothing, and neither + // does a guide made from a path with a gradient. + let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ramp"})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap(); + let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ramp"})).unwrap(); + let guide = square(&mut s, 300.0); + s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ramp"})).unwrap(); + s.execute("select.set", &json!({"ids": [guide]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + // Nor does a compound path's member's own gradient fill, or an image's gradient fill + // without an effect that gives it a shape. + let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0)); + s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap(); + let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance); + let pic = square(&mut s, 360.0); + s.execute("select.set", &json!({"ids": [pic]})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let image = s.doc().unwrap().selection.objects[0]; + s.edit("own paint", |d, _| { + d.node_mut(member).unwrap().appearance = paint.clone(); + d.node_mut(image).unwrap().appearance = paint; + Ok(()) + }) + .unwrap(); + // Underlined spaces draw a bar in the gradient, so that type object is listed. + let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Ramp"})).unwrap(); + s.execute("select.set", &json!({"ids": [bar]})).unwrap(); + s.execute("text.setFormat", &json!({"underline": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!( + i["gradientObjects"], + json!([ + {"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]}, + {"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"]}, + {"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"]}, + {"id": t, "name": "Type", "gradients": ["Ramp"]}, + {"id": bar, "name": "Bar", "gradients": ["Ramp"]}, + ]) + ); + assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"])); + // Objects counts the objects that Gradient Objects lists. + assert_eq!(i["objects"]["gradients"].as_u64(), Some(5), "{}", i["objects"]); + s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + assert!(i["objects"]["gradients"].is_null() && i["gradientObjects"] == json!([]), "{}", i["objects"]); + let i = s.execute("document.info", &json!({"category": "gradients"})).unwrap(); + assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("gradients"), Some("Gradient Objects"))); + assert_eq!( + i["sections"][0]["rows"], + json!([ + ["Both", "Ramp, Linear gradient"], + ["<Rectangle>", "Radial gradient"], + ["<Rectangle>", "Freeform gradient"], + ["Type", "Ramp"], + ["Bar", "Ramp"] + ]) + ); + // A selection that holds the group and the object inside it lists that object once. + for ids in [json!([group, b]), json!([b, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap(); + assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Radial gradient"]]), "{ids}"); + assert_eq!(i["objects"]["gradients"].as_u64(), Some(1), "{ids}"); + } + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap(); + assert_eq!((i["sections"][0]["rows"].clone(), i["gradientNames"].clone()), (json!([["Type", "Ramp"]]), json!(["Ramp"]))); + let text = s.execute("document.info", &json!({"category": "gradients", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!( + text.contains("\nGRADIENT OBJECTS\nBoth: Ramp, Linear gradient\n<Rectangle>: Radial gradient\n<Rectangle>: Freeform gradient\nType: Ramp\nBar: Ramp\n"), + "{text}" + ); + assert!(!text.contains("Spare"), "{text}"); + } + /// Document Info › Objects counts an object with a gradient or a pattern on both its fill and /// its stroke once, and with Selection Only a selection that holds a group and an object inside /// it counts that object once. diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 5f8508f4e9..ae3fc521f0 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -13,8 +13,8 @@ use super::edit::selected_roots; 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, switch_or, + CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, + str_param, switch_or, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -482,7 +482,7 @@ fn save_selection(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc()?; let ids = st.selection.objects.clone(); let saved = &st.doc.saved_selections; - let name = str_param(p, "name").and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved)); + let name = text_param(p, "name", C)?.and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved)); let existing = saved.iter().position(|x| x.name == name); if existing.is_none() && saved.len() >= SavedSelection::MAX { return Err(bad(C, format!("a document keeps at most {} saved selections", SavedSelection::MAX))); @@ -577,10 +577,12 @@ fn edit_saved(s: &mut Session, p: &Value) -> Result<Value> { for e in edits { let name = str_param(e, "name").ok_or_else(|| bad(C, "missing name"))?; let i = *index.get(name).ok_or_else(|| bad(C, format!("no saved selection `{name}`")))?; + let delete = switch_or(e, "delete", false, C)?; + let new_name = text_param(e, "newName", C)?; let Some(slot) = after.get_mut(i) else { continue }; - if bool_or(e, "delete", false) { + if delete { *slot = None; - } else if let Some(n) = str_param(e, "newName").and_then(SavedSelection::clean_name) + } else if let Some(n) = new_name.and_then(SavedSelection::clean_name) && let Some(x) = slot { x.name = n; @@ -666,7 +668,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> { if (index.is_some() || ids.is_some()) && s.menu.guides_locked { return Err(EngineError::Other("guides are locked".into())); } - let (rulers, paths): (Vec<usize>, Vec<NodeId>) = if index.is_some() || ids.is_some() { + let (rulers, paths): (Vec<NodeId>, Vec<NodeId>) = if index.is_some() || ids.is_some() { let rulers = match index { Some(v) => vec![editable_guide_index(s, Some(v), C)?], None => vec![], @@ -689,10 +691,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> { let st = s.doc()?; let all = guide_paths(&st.doc); let sel: Vec<NodeId> = all.iter().copied().filter(|id| st.selection.contains(*id)).collect(); - let rulers: Vec<usize> = if s.menu.guides_locked { + let rulers: Vec<NodeId> = if s.menu.guides_locked { vec![] } else { - st.selection.guides.iter().copied().filter(|i| st.doc.guides.get(*i).is_some_and(|g| st.doc.guide_editable(g))).collect() + st.selection.guides.iter().copied().filter(|id| st.doc.ruler_guide(*id).is_some_and(|g| st.doc.guide_editable(&g))).collect() }; let editable = st.doc.editable(); if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| editable(*id)).collect()) } else { (rulers, sel) } @@ -702,8 +704,8 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> { let artboards = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)); let mut lines = Vec::with_capacity(rulers.len()); for &i in &rulers { - let Some(g) = st.doc.guides.get(i) else { continue }; - let span = st.doc.guide_span(g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })); + let Some(g) = st.doc.ruler_guide(i) else { continue }; + let span = st.doc.guide_span(&g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })); let Some((a, b)) = span else { continue }; let (a, b) = if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) }; let parent = match g.layer.filter(|l| st.doc.node(*l).is_some_and(Node::is_layer)) { @@ -729,7 +731,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> { d.insert(parent, usize::MAX, Node::path(id, vectorcraft_geom::shapes::line(a, b), look))?; made.push(id); } - d.retain_guides(sel, |i, _| !lines.iter().any(|l| l.0 == i)); + d.retain_guides(sel, |g| !lines.iter().any(|l| Some(l.0) == g.id)); sel.set(paths.iter().copied().chain(made)); Ok(()) })?; @@ -745,12 +747,12 @@ fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> { fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> { let st = s.doc()?; let paths = guide_paths(&st.doc); - let n = paths.len() + st.doc.guides.len(); + let n = paths.len() + st.doc.ruler_guides().len(); if n == 0 { return Ok(json!({ "count": 0 })); } - s.edit("Clear Guides", |d, _| { - d.guides.clear(); + s.edit("Clear Guides", |d, sel| { + d.retain_guides(sel, |_| false); let mut gone = Beside::replacing(d, &paths); for id in &paths { if d.node(*id).is_some() { @@ -764,7 +766,7 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> { fn guide_add(s: &mut Session, p: &Value) -> Result<Value> { let pos = f64_req(p, "pos", "guide.add")?; - let vertical = bool_or(p, "vertical", false); + let vertical = switch_or(p, "vertical", false, "guide.add")?; let artboard = match p.get("artboard").filter(|v| !v.is_null()) { Some(v) => { let boards = &s.doc()?.doc.artboards; @@ -780,17 +782,29 @@ fn guide_add(s: &mut Session, p: &Value) -> Result<Value> { // Where new art goes (refused when no layer is shown and unlocked), or that group's layer. None => st.target_parent()?.and_then(|p| if st.doc.node(p).is_some_and(Node::is_layer) { Some(p) } else { st.doc.layer_containing(p) }), }; - let i = s.edit("New Guide", |d, _| { - d.guides.push(Guide { artboard, layer, ..Guide::new(vertical, pos) }); - Ok(d.guides.len() - 1) - })?; + let id = s.edit("New Guide", |d, _| Ok(d.add_ruler_guide(&Guide { artboard, layer, ..Guide::new(vertical, pos) })))?; + let i = guide_indexes(&s.doc()?.doc, &[id]).first().copied(); Ok(json!({ "index": i })) } +/// The ids of the active document's ruler guides by index: the order of `guide.list` (ascending +/// id). +pub(crate) fn guide_ids(d: &vectorcraft_doc::Document) -> Vec<NodeId> { + d.ruler_guides().into_iter().filter_map(|g| g.id).collect() +} + +/// The `guide.list` indexes of ruler guides `ids`, in the order of `ids` (an id that is not a ruler +/// guide is left out). +pub fn guide_indexes(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<usize> { + let all = guide_ids(d); + ids.iter().filter_map(|id| all.binary_search(id).ok()).collect() +} + fn guide_list(s: &mut Session, _: &Value) -> Result<Value> { let st = s.doc()?; let row = |(i, g): (usize, &Guide)| { - let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": st.selection.guides.contains(&i) }); + let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id)); + let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected }); if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) { r["artboard"] = json!(ab); } @@ -801,32 +815,39 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> { r["editable"] = json!(st.doc.guide_editable(g)); r }; - Ok(Value::Array(st.doc.guides.iter().enumerate().map(row).collect())) + Ok(Value::Array(st.doc.ruler_guides().iter().enumerate().map(row).collect())) } -/// Ruler guide `index` of the active document (`index` validated). -fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> { +/// The id of ruler guide `index` in `ids` ([`guide_ids`]; `index` validated). +fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId> { let i = v.and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "an index must be a whole number"))?; - if i >= s.doc()?.doc.guides.len() { - return Err(bad(cmd, format!("no guide {i}"))); + ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}"))) +} + +/// The id of ruler guide `index` of the active document (`index` validated). +fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> { + guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd) +} + +/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer? +fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> { + let d = &s.doc()?.doc; + if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) { + return Err(EngineError::Other("the guide is on a hidden or locked layer".into())); } - Ok(i) + Ok(id) } /// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer. -fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> { - let i = guide_index(s, v, cmd)?; - let d = &s.doc()?.doc; - if !d.guides.get(i).is_some_and(|g| d.guide_editable(g)) { - return Err(EngineError::Other("the guide is on a hidden or locked layer".into())); - } - Ok(i) +fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> { + check_editable_guide(s, guide_index(s, v, cmd)?) } fn guide_select(s: &mut Session, p: &Value) -> Result<Value> { let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?; - let picked = list.iter().map(|v| guide_index(s, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?; - if bool_or(p, "toggle", false) { + let ids = guide_ids(&s.doc()?.doc); + let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?; + if switch_or(p, "toggle", false, "guide.select")? { // Added to (or taken from) what is selected, the art included. s.select(|_, sel| { for i in picked { @@ -836,12 +857,13 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> { } else { s.select(|_, sel| sel.set_guides(picked))?; } - Ok(json!({ "selected": s.doc()?.selection.guides })) + let st = s.doc()?; + Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) })) } /// Delete ruler guide `index`, else the selected guides, in one undo step → {count}. pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> { - let gone: Vec<usize> = match p.get("index") { + let gone: Vec<NodeId> = match p.get("index") { Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?], None => s.doc()?.selection.guides.clone(), }; @@ -850,7 +872,7 @@ pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> { } let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" }; s.edit(label, |d, sel| { - d.retain_guides(sel, |i, _| !gone.contains(&i)); + d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); Ok(()) })?; Ok(json!({ "count": gone.len() })) @@ -866,18 +888,22 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> { if super::layer::locked_within(d, layer) { return Err(EngineError::Other("the layer or group is locked".into())); } - let moving: Vec<usize> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) { + let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) { (Some(v), _) => vec![editable_guide_index(s, Some(v), C)?], - (None, Some(list)) => list.iter().take(10_000).map(|v| editable_guide_index(s, Some(v), C)).collect::<Result<Vec<_>>>()?, + (None, Some(list)) => { + let ids = guide_ids(&s.doc()?.doc); + list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()? + } (None, None) => s.doc()?.selection.guides.clone(), }; if moving.is_empty() { return Err(bad(C, "no guide selected (or give an index)")); } s.edit("Move Guide to Layer", |d, _| { - for i in &moving { - if let Some(g) = d.guides.get_mut(*i) { - g.layer = Some(layer); + // Each keeps its id (and so its index), at the top of the layer. + for id in &moving { + if d.parent_of(*id) != Some(layer) && d.ruler_guide(*id).is_some() { + d.move_node(*id, Some(layer), usize::MAX)?; } } Ok(()) @@ -891,9 +917,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> { let i = editable_guide_index(s, Some(v), "guide.move")?; let pos = f64_req(p, "pos", "guide.move")?; s.edit("Move Guide", |d, _| { - if let Some(g) = d.guides.get_mut(i) { - g.pos = pos; - } + d.edit_ruler_guide(i, |g| g.pos = pos); Ok(()) })?; return ok(); @@ -902,7 +926,9 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> { if moving.is_empty() { return Err(bad("guide.move", "no guide selected (or give an index)")); } - let (dx, dy, copy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0), bool_or(p, "copy", false)); + let dx = number_or(p, "dx", 0.0, "guide.move")?; + let dy = number_or(p, "dy", 0.0, "guide.move")?; + let copy = switch_or(p, "copy", false, "guide.move")?; if !s.doc()?.selection.is_empty() { let ids = super::edit::selected_roots(s)?; return super::object::apply_transform( @@ -917,18 +943,14 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> { s.edit(if copy { "Copy Guide" } else { "Move Guide" }, |d, sel| { let mut copies = vec![]; for &i in &moving { - let Some(g) = d.guides.get_mut(i) else { continue }; - let moved = g.moved(Vec2::new(dx, dy)); if copy { - copies.push(moved); + copies.extend(d.ruler_guide(i).map(|g| d.add_ruler_guide(&g.moved(Vec2::new(dx, dy))))); } else { - *g = moved; + d.edit_ruler_guide(i, |g| *g = g.moved(Vec2::new(dx, dy))); } } if copy { - let first = d.guides.len(); - d.guides.extend(copies); - sel.set_guides(first..d.guides.len()); + sel.set_guides(copies); } Ok(()) })?; diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index 894d9b90ae..dadafaa1b8 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> { "Document Setup", [], None, - "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", + "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", has_doc, setup )] @@ -46,6 +46,7 @@ pub(crate) fn setup_json(d: &Document) -> Value { "smallCapsSize": s.small_caps_size, "exportText": s.export_text.id(), "backgroundContents": s.background.id(), + "alignNewObjectsToPixelGrid": s.align_new_objects_to_pixel_grid, }) } @@ -140,6 +141,7 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value "smallCapsSize" => s.small_caps_size = percent(k, v, 1.0, vectorcraft_doc::setup::MAX_SMALL_CAPS)?, "exportText" => s.export_text = v.as_str().and_then(ExportText::parse).ok_or_else(|| bad(C, "exportText must be editable or appearance"))?, "backgroundContents" => s.background = background_param(v, C)?, + "alignNewObjectsToPixelGrid" => s.align_new_objects_to_pixel_grid = flag(k, v)?, // Read-only values `document.setup` reports. "gridColorsName" | "warnings" => {} _ => return Err(bad(C, format!("unknown setting `{k}`"))), diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 7d1c1208d8..d469c7a613 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -18,8 +18,8 @@ use super::create::{add_look, insert_look}; use super::newart::NewArt; use super::pathops::{Beside, remove_each}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, id_param, index, number_or, ok, str_param, - switch_or, + CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, index, number_or, object_param, ok, + str_param, switch_or, }; use crate::EngineError; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index dbca59b00d..10254f3cd3 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -1,7 +1,7 @@ use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound}; use super::{ Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2, - add_look, bad, check_numbers, f64_or, id_param, json, number_or, ok, po, str_param, switch_or, + add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or, }; // ---------- Curvature ---------- @@ -41,7 +41,7 @@ enum CurvatureOp { pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> { use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move}; const C: &str = "path.curvatureEdit"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); check_numbers(p, &["x", "y", "t"], C)?; let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) { @@ -106,7 +106,7 @@ pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.removeAnchor"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let ai = usize_req(p, "anchor", C)?; let curvature = switch_or(p, "curvature", false, C)?; @@ -220,7 +220,7 @@ fn remove_anchors_of( pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.convertAnchor"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let ai = usize_req(p, "anchor", C)?; let smooth = str_param(p, "to") == Some("smooth"); @@ -257,7 +257,7 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.reshapeSegment"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let seg = usize_req(p, "segment", C)?; let t = number_or(p, "t", 0.5, C)?.clamp(0.05, 0.95); diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 1d2f006f1d..8946aa4351 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 126fa57a1b..645c184b14 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -4,7 +4,7 @@ use super::common::{ }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath, - Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, id_param, json, number_or, po, + Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; /// Split a filled path into connected pieces (each outer contour with its holes). @@ -170,7 +170,7 @@ pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn( pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "path.split"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = usize_opt(p, "subpath", C)?.unwrap_or(0); let anchor = usize_opt(p, "anchor", C)?; let seg = usize_opt(p, "segment", C)?; diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 660f52121e..f13b0a0ba4 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -4,7 +4,8 @@ use super::common::{ }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, - Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, id_param, insert_look, json, number_or, po, remove_each, str_param, switch_or, + Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, insert_look, json, number_or, object_param, po, remove_each, str_param, + switch_or, }; // ---------- Pencil / Paintbrush ---------- @@ -158,7 +159,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { - let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?; + let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = str_param(ext, "end") == Some("start"); let (pd, _) = path_of(&s.doc()?.doc, id)?; let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?; @@ -179,7 +180,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { - let other = id_param(cn, "id").ok_or_else(|| bad(C, "connect needs id"))?; + let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; if other == id { return Err(bad(C, "connect needs a path other than the one extended")); } @@ -299,7 +300,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> { return Ok(json!({ "id": id.0 })); } if let Some(rd) = p.get("redraw").filter(|v| !v.is_null()) { - let id = id_param(rd, "id").ok_or_else(|| bad(C, "redraw needs id"))?; + let id = object_param(rd, "id", C)?.ok_or_else(|| bad(C, "redraw needs id"))?; let within = number_or(rd, "within", 12.0, C)?; if !within.is_finite() || within < 0.0 { return Err(bad(C, "redraw within must be a finite distance of 0 or more")); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3558f1b569..4f3dc3403a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -9,9 +9,9 @@ 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, clock_date, cmd, date_param, - 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, switch_or, + CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param, + f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or, + object_param, ok, point_param, str_param, switch_or, }; use crate::{Clipboard, EngineError, inspect}; @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), @@ -184,7 +184,7 @@ pub fn specs() -> Vec<CommandSpec> { "Paste in Front", ["Edit"], Some("Cmd+F"), - "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Front) ), @@ -193,7 +193,7 @@ pub fn specs() -> Vec<CommandSpec> { "Paste in Back", ["Edit"], Some("Cmd+B"), - "{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Back) ), @@ -202,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> { "Paste in Place", ["Edit"], Some("Cmd+Shift+V"), - "{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::InPlace) ), @@ -237,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> { } fn file_close(s: &mut Session, p: &Value) -> Result<Value> { - let i = p.get("index").and_then(Value::as_u64).map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; + let i = opt_u64(p, "file.close", "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; if !s.close_document(i) { return Err(bad("file.close", "no such document")); } @@ -267,9 +267,9 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> { } fn doc_node(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?; + let id = object_param(p, "id", "document.node")?.ok_or_else(|| bad("document.node", "missing id"))?; let mut opts = slice_opts(p, "document.node")?; - let summary = bool_or(p, "summary", false); + let summary = switch_or(p, "summary", false, "document.node")?; if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) { // The full object JSON is never truncated: a slice without `summary` would // otherwise silently return the whole subtree. @@ -663,7 +663,8 @@ fn undo_group_begin(s: &mut Session, p: &Value) -> Result<Value> { } fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> { - s.end_undo_group(bool_or(p, "cancel", false)); + let cancel = switch_or(p, "cancel", false, "edit.undoGroup.end")?; + s.end_undo_group(cancel); ok() } @@ -672,10 +673,14 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> { /// the step before. As any new edit it ends the steps to redo, so Redo never swaps the document /// under an interaction that would then preview on, or cancel to, the document from before (#1719). /// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the -/// document. +/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own +/// commit applies it; when it fails, the interaction is canceled. pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { let typing = typing_in_progress(s); - s.commit_interaction()?; + match s.unapplied_interaction_preview().filter(|_| !s.previewing) { + Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?, + _ => s.commit_interaction()?, + } if typing { s.set_tool_option("endTyping", &Value::Bool(true)); } @@ -991,8 +996,8 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> { .selection .guides .iter() - .filter_map(|i| st.doc.guides.get(*i)) - .map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() }) + .filter_map(|i| st.doc.ruler_guide(*i)) + .map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, id: None, ..g }) .collect(); let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets }; let mut clip = Clipboard::copy(st, &roots, direct); @@ -1004,7 +1009,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> { // 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() - && let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i)) + && let Some(g) = st.selection.guides.first().and_then(|i| st.doc.ruler_guide(*i)) { let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| { st.doc @@ -1053,7 +1058,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> { 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)); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); let mut survivors = vec![]; let mut pieces = super::pathops::Beside::replacing(d, roots); for id in roots { @@ -1153,7 +1158,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> { } if with_guides { let gone = sel.guides.clone(); - d.retain_guides(sel, |i, _| !gone.contains(&i)); + d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } if is_explicit { for id in &ids { @@ -1231,6 +1236,9 @@ impl PasteMode { fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result<Value> { let choices = SwatchChoices::parse(mode.label(), p)?; + if mode == PasteMode::Offset { + check_numbers(p, &["dx", "dy"], "edit.paste")?; + } // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); let r = paste_clip(s, p, mode, &clip, &choices); @@ -1246,15 +1254,79 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_ paste_clip(s, &json!({ "center": [center.x, center.y] }), PasteMode::Library, clip, &choices) } -/// Paste in Place, in Front or in Back onto artboard `artboard` (the active one, #693): where the -/// objects were on the artboard they were copied from, on that one; without it (or a copy from no -/// artboard), where they were. -fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine { - let target = p.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).and_then(|i| doc.artboards.get(i)); - match (target, clip.source_artboard) { - (Some(t), Some(src)) => Affine::translate(t.rect.origin() - src.origin()), - _ => Affine::IDENTITY, +/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard` +/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several +/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same +/// ones); `None` when none is named. A named index that is not an artboard of the document, a +/// repeated one or an empty list is an error. +fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Vec<usize>>> { + let n = s.doc()?.doc.artboards.len(); + let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); + let single = match p.get("artboard") { + Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?), + None => None, + }; + let listed = match p.get("artboards") { + Some(v) => { + let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?; + let mut all = list + .iter() + .map(one) + .collect::<Option<Vec<usize>>>() + .ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?; + all.sort_unstable(); + if all.windows(2).any(|w| w[0] == w[1]) { + return Err(bad(cmd, "`artboards` names an artboard twice")); + } + Some(all) + } + None => None, + }; + if let Some(i) = single { + return Ok(Some(vec![i])); } + if listed.is_some() { + return Ok(listed); + } + let picked = artboard_tool_picks(s); + if picked.is_empty() { + return Ok(None); + } + s.note_journal("artboards", json!(picked)); + Ok(Some(picked)) +} + +/// The artboards of the active document the Artboard tool has selected, in artboard order, while +/// that tool is chosen with two or more of them selected; otherwise none. Indices the document +/// does not have are left out. +pub(crate) fn artboard_tool_picks(s: &Session) -> Vec<usize> { + if s.tool_id() != "artboard" { + return Vec::new(); + } + let n = s.active().map_or(0, |d| d.doc.artboards.len()); + let mut picked: Vec<usize> = s.tool_options_of("artboard")["selected"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok())) + .filter(|i| *i < n) + .collect(); + picked.sort_unstable(); + picked.dedup(); + if picked.len() < 2 { + picked.clear(); + } + picked +} + +/// Paste in Place, in Front or in Back onto artboards `targets`: one copy on each, where the objects +/// were on the artboard they were copied from. A copy from no artboard keeps its place on the first +/// target and its offset to that one on the others; without targets, the objects go where they were. +fn onto_artboards(doc: &Document, targets: Option<&[usize]>, clip: &Clipboard) -> Vec<Affine> { + let rects: Vec<_> = targets.unwrap_or_default().iter().filter_map(|i| doc.artboards.get(*i)).map(|a| a.rect.origin()).collect(); + let Some(first) = rects.first().copied() else { return vec![Affine::IDENTITY] }; + let src = clip.source_artboard.map_or(first, |r| r.origin()); + rects.iter().map(|o| Affine::translate(*o - src)).collect() } /// Insert clipboard resources atomically in the active editable context using the requested placement mode. @@ -1268,6 +1340,12 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho ), _ => None, }; + let targets = match mode { + PasteMode::Front => paste_targets(s, p, "edit.pasteInFront")?, + PasteMode::Back => paste_targets(s, p, "edit.pasteInBack")?, + PasteMode::InPlace => paste_targets(s, p, "edit.pasteInPlace")?, + _ => None, + }; let st = s.doc()?; let same_doc = clip.source_doc == Some(st.uid); let parent = st.target_parent_for_path()?; @@ -1315,14 +1393,15 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho (_, Some((_, dv))) => vec![Affine::translate(dv)], (PasteMode::Offset | PasteMode::Library | PasteMode::Drag, None) => vec![match point_param(p, "center") { Some(c) => clip.bounds().map_or(Affine::IDENTITY, |b| Affine::translate(c - b.center())), - None => Affine::translate((f64_or(p, "dx", off), f64_or(p, "dy", off))), + None => Affine::translate((number_or(p, "dx", off, mode.label())?, number_or(p, "dy", off, mode.label())?)), }], (PasteMode::AllArtboards, None) => { let src = clip.source_artboard.or_else(|| st.doc.artboards.first().map(|a| a.rect)).map(|r| r.origin()).unwrap_or_default(); st.doc.artboards.iter().map(|a| Affine::translate(a.rect.origin() - src)).collect() } - // In place, in front, in back: onto the active artboard when the UI names it. - _ => vec![onto_artboard(&st.doc, p, clip)], + // In place, in front, in back: onto the active artboard when the UI names it, or onto each + // artboard the Artboard tool has selected. + _ => onto_artboards(&st.doc, targets.as_deref(), clip), }; // Guides alone don't follow a plain paste's offset or the view centre: they stay where they // were. With objects they move as the objects do. @@ -1438,8 +1517,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for g in &clip.guides { let pos = g.pos + if g.vertical { dv.x } else { dv.y }; if pos.is_finite() { - sel.guides.push(d.guides.len()); - d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() }); + sel.guides.push(d.add_ruler_guide(&vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() })); } } } @@ -1490,8 +1568,8 @@ fn layer_named(d: &mut Document, name: &str) -> NodeId { fn duplicate(s: &mut Session, p: &Value) -> Result<Value> { let roots = selected_roots(s)?; - let dx = f64_or(p, "dx", 0.0); - let dy = f64_or(p, "dy", 0.0); + let dx = number_or(p, "dx", 0.0, "edit.duplicate")?; + let dy = number_or(p, "dy", 0.0, "edit.duplicate")?; let ids = s.edit("Duplicate", |d, sel| duplicate_in(d, sel, &roots, Affine::translate((dx, dy))))?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })) } diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 89d4f5011c..b570ce332a 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> { "3D Lighting Preset", [], None, - "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), which has no lighting presets; one undo step → {ids}", + "{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}", has_doc, lighting_preset ), @@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> { "Refresh Deferred Effects", ["Effect"], None, - "{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}", + "{ids?|id?: [object id] (objects of the document, also in the art of a symbol, pattern, brush or opacity mask; an object without a deferred stage adds nothing; an id of no object is an error; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}", has_deferred, refresh_deferred ), @@ -150,16 +150,27 @@ fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> None => rest.push(object), } } - if rest.is_empty() { + for (id, n) in definition_objects(d, &rest) { + out.entry(id).or_insert((n, false)); + } + out +} + +/// The objects of `ids` found in the art `d` draws from outside its layers: the art of its +/// symbols, patterns and brushes, and opacity masks (in that art or in the layers). +fn definition_objects(d: &Document, ids: &[u64]) -> std::collections::HashMap<u64, Arc<Node>> { + let mut out = std::collections::HashMap::new(); + if ids.is_empty() { return out; } + let ids: std::collections::HashSet<u64> = ids.iter().copied().collect(); let brushes = vectorcraft_brush::library(d); let symbols = d.symbols.iter().map(|s| &*s.art); let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)); let layers = d.layers.iter().map(|a| &**a); let mut look = |n: &Node| { - if rest.contains(&n.id.0) { - out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false)); + if ids.contains(&n.id.0) { + out.entry(n.id.0).or_insert_with(|| Arc::new(n.clone())); } }; for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) { @@ -231,10 +242,19 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> { let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone()); let ids = super::named_ids(p)?; let objects = prune(&doc, &fx); - if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) { - return Err(EngineError::NoNode(*id)); + // An object of the art drawn outside the layers is valid whether or not it has a stage. + let elsewhere: Vec<u64> = ids.iter().flatten().filter(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)).map(|id| id.0).collect(); + let found = definition_objects(&doc, &elsewhere); + if let Some(id) = elsewhere.iter().find(|id| !found.contains_key(id)) { + return Err(EngineError::NoNode(NodeId(*id))); } - let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect()); + // Only the objects with a stage have anything to refresh. + let ids: Option<Vec<u64>> = ids.map(|ids| { + let mut ids: Vec<u64> = ids.iter().map(|id| id.0).filter(|id| objects.contains_key(id)).collect(); + ids.sort_unstable(); + ids.dedup(); + ids + }); let counts = fx.refresh(ids.as_deref(), |targets| { let mut renderer = vectorcraft_render::Renderer::new(); let mut whole = Vec::new(); @@ -656,12 +676,10 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> { if !effect.is_some_and(|e| effects::is_three_d(&e.id)) { return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); } - // Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options. - if effect.is_some_and(|e| e.id == effects::CLASSIC_EXTRUDE) { - return Err(bad( - C, - format!("object {}: Extrude & Bevel (Classic) at index {index} has no lighting presets; set its lights with effect.setParams", id.0), - )); + // The classic 3D effects have no lighting presets; their lights are set in their own options. + if let Some(e) = effect.filter(|e| effects::is_classic_three_d(&e.id)) { + let name = effects::effect_info(&e.id).map_or("This effect", |info| info.label.trim_end_matches('…')); + return Err(bad(C, format!("object {}: {name} at index {index} has no lighting presets; set its lights with effect.setParams", id.0))); } } let mut options = p.clone(); @@ -889,6 +907,10 @@ fn expand_pieces( let mut seen = std::collections::HashSet::from([id]); let mut expanded = std::collections::HashMap::new(); for c in m.children_mut().into_iter().flatten() { + // A layer's ruler guides are not art: they keep their ids and expand to nothing. + if c.is_ruler_guide() { + continue; + } let c = Arc::make_mut(c); let mut listed = None; if all || c.id == id { @@ -1084,6 +1106,11 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br // The place of each member in the walk of `n`: after `n` and the members before it. let mut at = 1; for c in n.children_mut().into_iter().flatten() { + if c.is_ruler_guide() { + // A layer's ruler guide expands to nothing, but the walk of `n` still visits it. + at += 1; + continue; + } let from = out.len(); match members.remove(&c.id) { Some(listed) => out.extend(listed), @@ -1097,7 +1124,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br for (_, place) in &mut out[from..] { *place += at; } - at += c.count(); + // Every node the walk visits, ruler guides in a sublayer too (`Node::count` leaves them out). + c.walk(&mut |_| at += 1); } } changed.then_some(n) diff --git a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs index 812ce09664..2dff0d23f1 100644 --- a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs +++ b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs @@ -115,3 +115,32 @@ fn lighting_presets_refuse_extrude_and_bevel_classic_and_leave_a_mixed_selection let params = &s.doc().unwrap().doc.node(NodeId(classic)).unwrap().appearance.effects[0].params; assert_eq!((params["lightRotation"].as_f64(), params["lightHeight"].as_f64()), (Some(135.0), Some(45.0))); } + +#[test] +fn lighting_presets_refuse_revolve_classic() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("path.create", &json!({"d":"M100 40 L130 60 L130 140 L100 160"})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color":"#3366cc"})).unwrap(); + s.execute("effect.apply", &json!({"effect":"threeD.classicRevolve","item":null,"params":{"surface":"diffuse"}})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"topLeft"})).unwrap_err().to_string(); + assert!(err.contains(&format!("object {id}: Revolve (Classic) at index 0 has no lighting presets")), "{err}"); + assert_eq!(s.doc().unwrap().doc, before); + assert!(!s.doc().unwrap().is_dirty()); +} + +#[test] +fn lighting_presets_refuse_rotate_classic() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x":100,"y":100,"width":80,"height":60})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect":"threeD.classicRotate","item":null,"params":{"lightRotation":40}})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"diffuse"})).unwrap_err().to_string(); + assert!(err.contains(&format!("object {id}: Rotate (Classic) at index 0 has no lighting presets")), "{err}"); + assert_eq!(s.doc().unwrap().doc, before); + assert!(!s.doc().unwrap().is_dirty()); +} diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index e4c8d79450..5584073563 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -881,3 +881,56 @@ fn move_takes_several_effects_that_land_together_in_order() { assert!(s.execute("effect.move", &json!({"from": [0, 9], "to": 0, "fromItem": null, "ids": [id.0]})).is_err()); assert_eq!(node(&s, id).appearance, before); } + +/// A 3D effect's shadow is set with `effect.setParams` in one undo step, saved in the native file, +/// drawn in exports and kept as a path by Expand Appearance; settings out of range are refused +/// without an undo step. +#[test] +fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + for (params, why) in [ + (json!({"shadowBounds": 401}), "shadowBounds must be a number from 10 to 400"), + (json!({"shadowPosition": "left"}), "shadowPosition must be behind or below"), + ] { + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap_err().to_string(); + assert!(e.contains(why), "{params}: {e}"); + assert_eq!(s.doc().unwrap().doc, before); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + let params = json!({"shadow": true, "shadowPosition": "below", "shadowDistance": 20, "shadowBounds": 150}); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let art = effects::solid_art(&node(&s, id)).unwrap(); + let shadow = art.children().unwrap()[0].clone(); + assert!(matches!(shadow.kind, NodeKind::Path { .. })); + // Saved and opened again, the effect keeps its shadow settings and draws the same shadow. + let doc = &s.doc().unwrap().doc; + let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + let fx = &restored.node(id).unwrap().appearance.effects[0]; + for (key, value) in params.as_object().unwrap() { + assert_eq!(fx.params.get(key), Some(value), "{key}"); + } + assert_eq!(effects::solid_art(restored.node(id).unwrap()).unwrap(), art); + // SVG export draws it: one more shape than without the shadow. + let shapes = |s: &mut Session| { + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); + vectorcraft_testkit::svg_shapes(&svg) + }; + let with = shapes(&mut s); + s.execute("edit.undo", &json!({})).unwrap(); + let without = shapes(&mut s); + assert_eq!(with, without + 1); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + let mut shadows = 0; + s.doc().unwrap().doc.walk(|n| { + if n.path_data().is_some() && n.path_data() == shadow.path_data() && n.appearance.items == shadow.appearance.items { + shadows += 1; + } + }); + assert_eq!(shadows, 1); +} diff --git a/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs index 122d937b98..104363a142 100644 --- a/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs +++ b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs @@ -4,7 +4,7 @@ use vectorcraft_doc::{NodeId, NodeKind}; use crate::Session; -const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"]; +const TYPES: [&str; 6] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.classicRotate", "threeD.revolve"]; fn id_of(v: &Value) -> NodeId { NodeId(v["id"].as_u64().unwrap()) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index ffb58d9d4b..1d39e2b4e4 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -36,6 +36,9 @@ pub const MAX_STEPS: u32 = 1000; const FREEFORM_MESH: u32 = 8; /// Columns (around the centre) of the mesh a radial gradient expands to. const RADIAL_MESH_COLS: usize = 8; +/// Largest turn between a conic gradient's mesh columns, so their straight outer edges stay +/// close enough to a circle to reach past the box. +const CONIC_MESH_GAP: f64 = 1.0 / 32.0; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -44,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> { "Expand…", ["Object"], None, - "{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}", + "{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}", has_selection, expand ), @@ -534,7 +537,7 @@ fn expand_piece_leaves( } return; } - for c in n.children_mut().into_iter().flatten() { + for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { expand_piece_leaves(d, Arc::make_mut(c), left, expanded, expand); } } @@ -1279,7 +1282,13 @@ fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32 /// end, the vector across it (radial: the ellipse's other axis), and the parameter ranges that /// cover the box (linear: along the vector `t0..t1` and across it `s0..s1` in points; radial: /// `0..t1`, each level's ellipse centred on the way from the focal point to the start). +/// A conic gradient also has its placement, the box and the radius in its frame that reaches +/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center). A +/// diamond gradient has its frame ([`vectorcraft_color::GradientGeom::diamond_frame`]; `None` +/// when it has no extent), the box and the level of the square that reaches its corners. struct Frame { + conic: Option<(vectorcraft_color::GradientGeom, Rect, f64)>, + diamond: Option<(Option<Affine>, Rect, f64)>, radial: bool, start: Point, focal: Point, @@ -1309,7 +1318,19 @@ impl Frame { } // Keep a sliver of span so the art maps back invertibly. t1 = t1.max(t0 + 1e-6); - Self { radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 } + let conic = (g.gradient.kind == GradientKind::Conic).then(|| { + let to_unit = geom.conic_frame().inverse(); + let reach = corners.iter().map(|c| (to_unit * *c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6); + // Past the corners, and far enough out that the chords between columns at most + // CONIC_MESH_GAP of a turn apart stay outside them. + let reach = if reach.is_finite() { reach * 1.01 / (std::f64::consts::PI * CONIC_MESH_GAP).cos() } else { 1.0 }; + (geom, bounds, reach) + }); + let diamond = (g.gradient.kind == GradientKind::Diamond).then(|| { + let reach = corners.iter().map(|c| geom.param_at(GradientKind::Diamond, *c)).fold(0.0f64, f64::max); + (geom.diamond_frame(), bounds, if reach.is_finite() { reach.max(1e-6) * 1.01 } else { 1.0 }) + }); + Self { conic, diamond, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 } } /// Linear: the point at parameter `t` along and `s` across. Radial: the point at parameter `t` @@ -1325,6 +1346,46 @@ impl Frame { /// A gradient mesh covering the box: columns (linear) or rings (radial) where the colour /// changes, so it paints the gradient exactly. fn mesh(&self, g: &Gradient) -> GradientMesh { + if let Some((geom, _, reach)) = &self.conic { + // Columns around the center where the color changes, at most CONIC_MESH_GAP of a turn + // apart so the outer edge stays past the box; the seam is two columns in one place. + let br = breaks(g, 0.0, 1.0, CONIC_MESH_GAP); + let us: Vec<f64> = br.iter().map(|(t, _)| *t).collect(); + let frame = geom.conic_frame(); + let at = |u: f64, v: f64| { + let a = u * std::f64::consts::TAU; + frame * Point::new(reach * v * a.cos(), reach * v * a.sin()) + }; + return GradientMesh::from_grid(&us, &[0.0, 1.0], &at, &|_, c, _| br[c].1); + } + if let Some((frame, b, reach)) = &self.diamond { + let Some(frame) = frame else { + // No extent: the whole box is the last stop. + let last = g.sample_keep_model(1.0); + let at = |u: f64, v: f64| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height()); + return GradientMesh::from_grid(&[0.0, 1.0], &[0.0, 1.0], &at, &|_, _, _| last); + }; + // Rings of squares where the color changes, with columns at the corners: each patch + // lies between two rings along one side, where the level runs straight across it. + let br = breaks(g, 0.0, *reach, f64::INFINITY); + let ts: Vec<f64> = br.iter().map(|(t, _)| t / reach).collect(); + let at = |u: f64, v: f64| *frame * (diamond_perimeter(u).to_vec2() * (v * reach)).to_point(); + const CORNERS: [f64; 5] = [0.0, 0.25, 0.5, 0.75, 1.0]; + let mut mesh = GradientMesh::from_grid(&CORNERS, &ts, &at, &|r, _, _| br[r].1); + // Every column is at a corner, where `from_grid`'s tangent is the mean of the two + // sides: each handle along a ring points a third of the way along its own side, so + // the sides stay straight. + let side = |v: f64, from: usize, to: Option<&f64>| to.map_or(vectorcraft_geom::Vec2::ZERO, |&u| (at(u, v) - at(CORNERS[from], v)) / 3.0); + for (r, &v) in ts.iter().enumerate() { + for c in 0..CORNERS.len() { + if let Some(point) = mesh.points.get_mut(r * CORNERS.len() + c) { + point.handles[0] = side(v, c, CORNERS.get(c + 1)); + point.handles[1] = side(v, c, c.checked_sub(1).and_then(|i| CORNERS.get(i))); + } + } + } + return mesh; + } // Rings as close as the columns around them, so the mesh draws smoothly. let gap = if self.radial { (self.t1 - self.t0) / RADIAL_MESH_COLS as f64 } else { f64::INFINITY }; let br = breaks(g, self.t0, self.t1, gap); @@ -1340,13 +1401,44 @@ impl Frame { /// `n` solid shapes covering the box in paint order, each coloured as the gradient in the /// middle of its band: for a linear gradient, rectangles from each band's start to the far - /// end, for a radial one, nested ellipses (largest first). Each paints over the ones - /// below except its band, so no seam shows between bands. With translucent stops each shape - /// is just its band, so nothing doubles up. + /// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the + /// center from each band's start to the seam, for a diamond one, nested squares (largest + /// first). Each paints over the ones below except its band, so no seam shows between bands. + /// With translucent stops each shape is just its band, so nothing doubles up. fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> { + let opaque = g.stops.iter().all(|s| s.opacity >= 1.0); + if let Some((geom, b, _)) = &self.conic { + return geom + .conic_wedges(*b, n, opaque) + .into_iter() + .map(|(pts, t)| (PathData::single(SubPath::polyline(&pts, true)), g.sample_keep_model(t as f32))) + .collect(); + } + if let Some((frame, b, reach)) = &self.diamond { + let Some(frame) = frame else { + return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))]; + }; + // Nested squares about the center, largest first, as a radial gradient's ellipses. + let step = reach / n as f64; + let square = |t: f64| -> SubPath { + let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + return (0..n) + .rev() + .map(|k| { + let mut shape = PathData::single(square((k + 1) as f64 * step)); + if !opaque && k > 0 { + let mut hole = square(k as f64 * step); + hole.reverse(); + shape.subpaths.push(hole); + } + (shape, g.sample_keep_model(((k as f64 + 0.5) * step) as f32)) + }) + .collect(); + } let step = (self.t1 - self.t0) / n as f64; let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32); - let opaque = g.stops.iter().all(|s| s.opacity >= 1.0); if self.radial { let ellipse = |t: f64| { let c = self.focal + (self.start - self.focal) * t; @@ -1376,3 +1468,14 @@ impl Frame { .collect() } } + +/// The point a fraction `u` (0..1) of the way around the square with corners (1, 0), (0, 1), +/// (-1, 0) and (0, -1), from the first: a diamond gradient's last stop in its frame. +fn diamond_perimeter(u: f64) -> Point { + const CORNERS: [(f64, f64); 5] = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0), (1.0, 0.0)]; + let s = if u.is_finite() { u.clamp(0.0, 1.0) * 4.0 } else { 0.0 }; + let i = (s.floor() as usize).min(3); + let f = s - i as f64; + let ((x0, y0), (x1, y1)) = (CORNERS.get(i).copied().unwrap_or((1.0, 0.0)), CORNERS.get(i + 1).copied().unwrap_or((1.0, 0.0))); + Point::new(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f) +} diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index 36ccd7cdb0..9a59d0f2f8 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -1,7 +1,8 @@ //! File → File Info (`file.info`): the document title and its descriptive metadata (author, //! description, keywords, rating, copyright), with the read-only created and modified dates. The -//! SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or `.ai` opens with the File Info -//! it gives ([`read_pdf`]). +//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]), +//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or +//! `.ai` opens with the File Info it gives ([`read_pdf`]). use serde_json::{Map, Value, json}; use vectorcraft_doc::metadata::{MAX_RATING, iso8601}; @@ -22,7 +23,7 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb pub(crate) fn info_json(d: &Document) -> Value { let m = &d.metadata; json!({ - "title": d.title, + "title": d.info_title(), "author": m.author, "authorTitle": m.author_title, "description": m.description, @@ -48,14 +49,22 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> { _ => return Err(bad(C, "params must be an object")), }; let d = &s.doc()?.doc; - let (mut title, mut m) = (d.title.clone(), d.metadata.clone()); + let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone()); for (k, v) in o { apply(&mut title, &mut m, k, v)?; } let d = &s.doc()?.doc; - if title != d.title || m != d.metadata { + // A title File Info changes becomes the document's own, as it always has (the tab and Save As + // offer it where the document has no file), and replaces the one its file gave. + let retitled = title != d.info_title(); + if retitled { + m.title = None; + } + if retitled || m != d.metadata { s.edit("File Info", |d, _| { - d.title = title; + if retitled { + d.title = title; + } d.metadata = m; Ok(()) })?; @@ -64,8 +73,8 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> { } /// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each -/// field that `file.info` would take (a value it refuses is left out), and the created and -/// modified dates. +/// field that `file.info` would take (a value it refuses is left out), its title ([`imported_title`]) +/// as the File Info title, and the created and modified dates. pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); let fields = [ @@ -83,6 +92,7 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let _ = apply(&mut title, m, k, &v); } } + m.title = f.title.as_deref().and_then(imported_title); m.created = f.created.or(m.created); m.modified = f.modified.or(m.modified); } @@ -141,6 +151,18 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> { Ok(s.to_string()) } +/// The File Info title `raw`, read from a file, makes: runs of white space (line breaks too) +/// become single spaces, other control characters are dropped, at most [`MAX_TEXT`] characters +/// are kept, as `file.info` takes a title. `None` when nothing is left, or when it is the +/// Untitled-N name New gives (what a document that never had a title writes to its files). +pub(crate) fn imported_title(raw: &str) -> Option<String> { + let words: Vec<String> = + raw.split_whitespace().map(|w| w.chars().filter(|c| !c.is_control()).collect::<String>()).filter(|w| !w.is_empty()).collect(); + let title: String = words.join(" ").chars().take(MAX_TEXT).collect(); + let title = title.trim_end(); + super::fileio::is_own_title(title).then(|| title.to_string()) +} + /// Keywords from a list or a comma- or semicolon-separated string: trimmed, each once (ignoring /// case), empty ones dropped. fn keywords(v: &Value) -> Result<Vec<String>> { diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 04a443ed4c..329988cb34 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -2,7 +2,7 @@ //! save, export and serialize by path or bytes (base64), the format table, `command.batch` and //! `action.batch` (the Actions panel menu's Batch…). //! -//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, raster images). +//! - `load`: `document.open` (native, legacy, SVG/SVGZ, PDF/.ai/.ait, DXF, HP-GL, raster images). //! - `action_batch`: play an action on every file in a folder or every data set. //! - `encode`: one encoder per writable format, with typed options parsed from the params. //! - `svg`: the SVG Options (styling, fonts, images, object ids, artboards…). @@ -17,6 +17,7 @@ //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. //! - `metafile`: EMF and WMF export, open and place. +//! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). //! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`). @@ -40,6 +41,7 @@ mod load; mod mesh3d; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; mod heifread; +mod hpgl; mod jp2read; mod metafile; mod naming; @@ -50,6 +52,7 @@ mod pdfimport; pub mod pngtext; pub mod ppi; pub mod progress; +mod psdlayers; pub mod psdread; mod pxrread; mod save; @@ -89,9 +92,9 @@ pub use pdfimport::{LoadOptions, page_document}; pub(crate) use save::job_for; pub(crate) use save::save as save_document; pub use save::{ - SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option, - remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder, - templates_folder, + SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, leave_out_unreadable_save_paths, + reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, + template_filters, templates_dialog_folder, templates_folder, }; pub(crate) use screens::{ PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS, @@ -123,7 +126,9 @@ pub(crate) use access::list_dir; pub use access::write_file_with; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::{Placed, copy_new, file_metadata}; -pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file}; +pub(crate) use access::{ + absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, shown_link, shown_path, write_file, write_new_file, +}; #[cfg(all(test, windows))] pub(crate) use access::{document_path_on, document_path_with}; #[cfg(test)] @@ -138,6 +143,7 @@ pub(crate) use export_names::{ artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return, }; use export_names::{distinct_names_by, write_encoded}; +pub(crate) use formats::is_own_title; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, @@ -204,6 +210,8 @@ mod tests_eps; #[cfg(test)] mod tests_dxfimport; #[cfg(test)] +mod tests_hpgl; +#[cfg(test)] mod tests_metafile; #[cfg(test)] @@ -218,6 +226,8 @@ mod tests_pdfx; #[cfg(test)] mod tests_psd; #[cfg(test)] +mod tests_psdlayers; +#[cfg(test)] mod tests_psdread; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 4dce2023bb..7b20326106 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -42,6 +42,29 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) { (out, seen) } +/// May a reply to the request being served name `path`, a file or folder the client did not give? +/// Always without roots in force; with them, only inside the read roots ([`crate::file_access::check_read`]). +pub(crate) fn shown(path: &str) -> bool { + crate::file_access::check_read(path).is_ok() +} + +/// `path` as a reply to the request being served names it: whole when [`shown`], else its file name, +/// after the last `/` or `\` whichever platform wrote it (empty for a path that ends in no name, such +/// as `..` or a folder ending in a separator). +pub(crate) fn shown_path(path: &str) -> std::borrow::Cow<'_, str> { + shown_link(path, None) +} + +/// A link's `stored` path as a reply to the request being served names it: whole when the file it +/// names (`resolved`, else `stored` itself) is [`shown`], else its file name as [`shown_path`] gives it. +pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::borrow::Cow<'a, str> { + if shown(resolved.unwrap_or(stored)) { + return std::borrow::Cow::Borrowed(stored); + } + let name = stored.rsplit(vectorcraft_doc::links::path_separators(stored)).next().unwrap_or_default(); + std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name }) +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 74d9185ea3..4953785189 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -11,7 +11,7 @@ use serde_json::json; use super::super::{Result, Session, bad}; #[cfg(not(target_arch = "wasm32"))] -use super::super::{bool_or, find_command, str_param}; +use super::super::{check_switches, find_command, switch_or, text_param}; #[cfg(target_arch = "wasm32")] pub(super) fn action_batch(_: &mut Session, _: &Value) -> Result<Value> { @@ -68,12 +68,24 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { )); } } - let source = str_param(p, "source").unwrap_or("folder"); - let destination = str_param(p, "destination").unwrap_or("none"); + // Every option is checked before the destination folder is made. + let source = text_param(p, "source", C)?.unwrap_or("folder"); + if !matches!(source, "folder" | "datasets") { + return Err(bad(C, "`source` must be `folder` or `datasets`")); + } + let destination = text_param(p, "destination", C)?.unwrap_or("none"); if !matches!(destination, "none" | "saveAndClose" | "folder") { return Err(bad(C, "`destination` must be `none`, `saveAndClose` or `folder`")); } - let dest_folder = str_param(p, "destinationFolder").map(absolute_path); + let dest_folder = text_param(p, "destinationFolder", C)?.map(absolute_path); + text_param(p, "folder", C)?; + let label = text_param(p, "label", C)?.unwrap_or("Batch").to_string(); + let dataset_file_naming = text_param(p, "datasetFileNaming", C)?.unwrap_or("fileDataSetName"); + let override_open = switch_or(p, "overrideOpen", true, C)?; + let stop_on_error = switch_or(p, "stopOnError", true, C)?; + let override_save = switch_or(p, "overrideSave", true, C)?; + let override_export = switch_or(p, "overrideExport", true, C)?; + check_switches(p, &["includeSubdirs"], C)?; if destination == "folder" { let Some(ref folder) = dest_folder else { return Err(bad(C, "`destinationFolder` is required when destination is `folder`")); @@ -81,17 +93,15 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { may_write(folder)?; std::fs::create_dir_all(folder).map_err(|e| bad(C, format!("{folder}: {e}")))?; } - let label = str_param(p, "label").unwrap_or("Batch").to_string(); - let override_open = bool_or(p, "overrideOpen", true); let run = Run { label: &label, steps: cmds, - stop_on_error: bool_or(p, "stopOnError", true), - override_save: bool_or(p, "overrideSave", true), - override_export: bool_or(p, "overrideExport", true), + stop_on_error, + override_save, + override_export, destination, dest_folder: dest_folder.as_deref(), - dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")), + dataset_file_naming, }; match source { "folder" => batch_folder(s, C, p, override_open, &run), @@ -186,9 +196,9 @@ fn retargeting_save(c: &Value, redirected: bool) -> bool { fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result<Value> { use super::{absolute_path, may_read}; - let folder = str_param(p, "folder").map(absolute_path).ok_or_else(|| bad(cmd, "missing `folder`"))?; + let folder = text_param(p, "folder", cmd)?.map(absolute_path).ok_or_else(|| bad(cmd, "missing `folder`"))?; may_read(&folder)?; - let include_subdirs = bool_or(p, "includeSubdirs", false); + let include_subdirs = switch_or(p, "includeSubdirs", false, cmd)?; let files = collect_files(&folder, include_subdirs, 0)?; if files.len() > MAX_BATCH_FILES { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} files"))); @@ -526,6 +536,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def | "dxf" | "emf" | "wmf" + | "hpgl" | "ai" ) }; @@ -716,6 +727,11 @@ fn collect_files(folder: &str, include_subdirs: bool, depth: usize) -> Result<Ve } } files.sort(); + // Names that are not valid text come back lossily, so different names can give one path: each + // folder is listed once. + files.dedup(); + subdirs.sort(); + subdirs.dedup(); for sub in subdirs { let mut nested = collect_files(&sub, true, depth + 1)?; files.append(&mut nested); @@ -749,6 +765,22 @@ mod tests { d } + #[cfg(unix)] + #[test] + fn folders_whose_names_alias_after_lossy_conversion_are_listed_once() { + use std::os::unix::ffi::OsStrExt; + let root = tmp("alias"); + // `a\u{FFFD}` is a real folder; two others with bytes that aren't text give the same name. + let real = root.join("a\u{FFFD}"); + std::fs::create_dir_all(&real).unwrap(); + write_svg(&real, "x.svg", "red"); + for bad in [b"a\xFF", b"a\xFE"] { + let _ = std::fs::create_dir_all(root.join(std::ffi::OsStr::from_bytes(bad))); + } + let files = collect_files(&root.to_string_lossy(), true, 0).unwrap(); + assert_eq!(files.len(), 1, "{files:?}"); + } + fn write_svg(dir: &std::path::Path, name: &str, fill: &str) -> std::path::PathBuf { let p = dir.join(name); std::fs::write( @@ -789,6 +821,46 @@ mod tests { assert!(dest.join("b.svg").is_file(), "b.svg written"); } + #[test] + fn batch_refuses_options_of_the_wrong_type_before_it_writes() { + let src = tmp("types-src"); + let dest = tmp("types-dest"); + write_svg(&src, "a.svg", "#f00"); + let mut s = Session::new(); + let cases = [ + ("stopOnError", json!("false"), "`stopOnError` must be true or false"), + ("overrideOpen", json!(0), "`overrideOpen` must be true or false"), + ("overrideSave", json!("true"), "`overrideSave` must be true or false"), + ("overrideExport", json!([]), "`overrideExport` must be true or false"), + ("includeSubdirs", json!(1), "`includeSubdirs` must be true or false"), + ("source", json!(1), "`source` must be a string"), + ("source", json!("files"), "`source` must be `folder` or `datasets`"), + ("destination", json!(true), "`destination` must be a string"), + ("folder", json!(5), "`folder` must be a string"), + ("label", json!(5), "`label` must be a string"), + ("datasetFileNaming", json!(3), "`datasetFileNaming` must be a string"), + ]; + for (key, value, message) in cases { + let out = dest.join(key); + let mut p = json!({ + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": out.to_string_lossy(), + "commands": [{"command": "object.unlockAll", "params": {}}], + }); + p[key] = value; + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!(e.contains(message), "{key}: {e}"); + assert!(!out.exists(), "{key}: the destination folder was created"); + } + let e = s + .execute("action.batch", &json!({"folder": src.to_string_lossy(), "destination": "folder", "destinationFolder": 7, "commands": [{"command": "object.unlockAll"}]})) + .unwrap_err() + .to_string(); + assert!(e.contains("`destinationFolder` must be a string"), "{e}"); + assert!(s.active().is_none(), "no file was opened"); + } + #[cfg(unix)] #[test] fn batch_folder_keeps_backslash_in_source_file_name() { diff --git a/crates/engine/src/cmd/fileio/affinity/layout.rs b/crates/engine/src/cmd/fileio/affinity/layout.rs index 8b6d4c4a8f..262f688b13 100644 --- a/crates/engine/src/cmd/fileio/affinity/layout.rs +++ b/crates/engine/src/cmd/fileio/affinity/layout.rs @@ -157,7 +157,8 @@ pub(super) fn align_lines(obj: &mut TextObject) { return; } let lines = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), obj).lines; - let w = lines.iter().map(|l| l.x1 - l.x0).filter(|w| w.is_finite()).fold(0.0, f64::max); + // Each line as wide as VectorCraft aligns it: without the tracking after its last character. + let w = lines.iter().map(|l| l.x1 - l.trailing - l.x0).filter(|w| w.is_finite()).fold(0.0, f64::max); if !(w > 0.0 && w < 1e6) { return; } diff --git a/crates/engine/src/cmd/fileio/affinity/paint.rs b/crates/engine/src/cmd/fileio/affinity/paint.rs index ed2b44ad3a..c81877632c 100644 --- a/crates/engine/src/cmd/fileio/affinity/paint.rs +++ b/crates/engine/src/cmd/fileio/affinity/paint.rs @@ -188,17 +188,24 @@ impl Builder { let kind = match g.kind { AfKind::Linear => GradientKind::Linear, AfKind::Radial => GradientKind::Radial, - AfKind::Conical => { - self.warn("conical gradients import as radial gradients"); - GradientKind::Radial - } + AfKind::Conical => GradientKind::Conic, }; let (u, v): (Vec2, Vec2) = (x - o, y - o); - if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 { + if kind.is_centered() && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 { self.warn("skewed elliptical gradients import as upright ellipses"); } let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 }; - let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None }; + let geom = match kind { + // A conic sweeps from unit +x towards unit +y: its unit frame carried onto the + // page as a transform carries it (mirrored when the transform is a reflection). + GradientKind::Conic => { + let mut geom = GradientGeom { start: Point::ZERO, end: Point::new(1.0, 0.0), aspect: 1.0, focal: None }; + geom.transform(m, GradientKind::Conic); + geom + } + GradientKind::Radial => GradientGeom { start: o, end: x, aspect, focal: None }, + _ => GradientGeom { start: o, end: x, aspect: 1.0, focal: None }, + }; let mut gp = GradientPaint::new(Gradient::new(kind, stops)); gp.angle = (-(u.y)).atan2(u.x).to_degrees(); gp.geom = Some(geom); diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index dec69c9eee..18bc78b5d9 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -76,7 +76,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> { /// starts (one for all the steps in that document), so a step may open, switch or close documents. /// A step that acts on the active artboard ([`crate::ON_ACTIVE_ARTBOARD`]) and names none gets /// `artboard`, as the Artboards panel shows it in the document the step runs in: past that -/// document's last artboard, the last one. A step that resizes the active artboard +/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names +/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with +/// several artboards selected, pastes on those. A step that resizes the active artboard /// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`. /// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them. fn run_steps( @@ -104,9 +106,14 @@ fn run_steps( } else { crate::FIT_ACTIVE_ARTBOARD.contains(&id.as_str()).then_some("index") }; + // A paste step that names its `artboards` keeps them; one that names neither key, while the + // Artboard tool is chosen with several artboards selected, pastes on those. + let names_artboards = id.starts_with("edit.pasteIn") + && (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty())); if let Some(a) = artboard && let Some(key) = key && params.get(key).is_none() + && !names_artboards && let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1)) && let Some(o) = params.as_object_mut() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 81e8168d06..7f95b8e203 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)", always, load::open ), @@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", has_doc, export::serialize ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), 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}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), 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 (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {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. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|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 (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {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. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored", has_selection, export::export_selection ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused", has_doc, screens::export_for_screens ), @@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Presets", [], None, - "{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones; any name works as document.exportForScreens' exportPreset", + "{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones (a folder outside the automation read roots is left out of settings); any name works as document.exportForScreens' exportPreset", always, screens::presets_list ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export Export Presets", [], None, - "{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}", + "{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON; a folder outside the automation read roots is left out); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}", always, screens::presets_export ), @@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), @@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens Settings", [], None, - "{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them)", + "{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them; a folder outside the automation read roots is left out)", has_doc, screens::export_settings ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index b63447e228..16cf3b2631 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export DXF", [], None, - "{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused", + "{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused", has_doc, export_dxf )] @@ -37,7 +37,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "dxfPreset", ty: "string", default: "\"custom\"", - description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it", + description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, no images, no fill hatches); the options given override it", }, FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" }, FormatOption { @@ -60,6 +60,18 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ default: "\"png\"", description: "png or jpeg: the files placed images are written to, next to the drawing", }, + FormatOption { + name: "includeImages", + ty: "boolean", + default: "true", + description: "placed images are written, linked to their files; false leaves them and their files out", + }, + FormatOption { + name: "includeHatches", + ty: "boolean", + default: "true", + description: "filled areas get a solid hatch after their outlines; false writes the outlines alone", + }, FormatOption { name: "preserve", ty: "string", @@ -133,6 +145,8 @@ struct Params { scale_lineweights: Option<bool>, colors: Option<Value>, raster_format: Option<String>, + include_images: Option<bool>, + include_hatches: Option<bool>, preserve: Option<String>, alter_paths: Option<bool>, outline_text: Option<bool>, @@ -176,6 +190,8 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> { scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights), colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?, raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?, + include_images: q.include_images.unwrap_or(d.include_images), + include_hatches: q.include_hatches.unwrap_or(d.include_hatches), preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?, alter_paths: q.alter_paths.unwrap_or(d.alter_paths), outline_text: q.outline_text.unwrap_or(d.outline_text), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 84188c313a..0f91007515 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -464,7 +464,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> { } // Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so // themselves: SVG only when it outlines or embeds fonts). - if (f.raster || matches!(f.id, "eps" | "emf" | "wmf")) + if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl")) && let Some(w) = crate::cmd::fonts::substitution_warning(doc) { enc.warnings.push(w); @@ -503,7 +503,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { let doc = &*doc.without_edit_modes(); let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). - let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf") { use_artboards(p)? } else { None }; + let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -536,6 +536,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { "eps" => return super::eps::encode(doc, p), "emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf), "wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf), + "hpgl" => return super::hpgl::encode(doc, p, use_artboards), "ai" => return super::save::encode_ai(C, f, doc, p), "pdf" => { let (bytes, warnings) = super::pdf::encode(C, doc, p)?; @@ -591,7 +592,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> { let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?; // File Info as PNG text chunks. let bytes = if matches!(format, RasterFormat::Png | RasterFormat::Png8) { - vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(&doc.title)) + vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(doc.info_title())) } else { bytes }; diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index ac33326994..fe962a36ad 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -1,8 +1,8 @@ //! EPS export for every EPS path (`document.export {format: eps}`, `document.exportEps`, Export As //! → EPS Options): the options parsed from the params, transparency flattened with a flattener //! preset, one file of the art's bounds or one per artboard (with a central file of the whole -//! document when there are several and art shows), the preview and thumbnail rendered, -//! and the native document embedded for reopening. +//! document when there are several and art shows), the preview rendered and the thumbnail made +//! from it, and the native document embedded for reopening. use std::borrow::Cow; @@ -11,6 +11,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; +use vectorcraft_render::Rendered; use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; @@ -47,7 +48,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "useArtboards", ty: "boolean", default: "null", - description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (none when no art shows); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named", + description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (when no art shows, Export writes none and Save writes it on the first artboard); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named (Save: the first artboard when no art shows)", }, FormatOption { name: "level", ty: "integer", default: "3", description: "PostScript language level, 2 or 3" }, FormatOption { @@ -202,10 +203,15 @@ fn expanded(cmd: &str, p: &Value, saved: &[super::super::FlattenerPreset]) -> Re } } +/// One file to write: its artboard, region and origin. +type Page = (Option<usize>, Rect, Point); + /// The files to write: `(artboard, region, origin)` each — every chosen artboard with its corner /// as the origin, or the visible art's bounds with the first artboard's corner. With two or more /// chosen artboards, a central file of the visible art comes first (none when no art shows). -fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Point)>> { +/// `saving`: Save always writes the file it names, so with no visible art that file's region is +/// the first artboard, and the second value is true. +fn pages(doc: &Document, set: &Settings, saving: bool) -> Result<(Vec<Page>, bool)> { let n = doc.artboards.len(); let named = set.boards.resolve(n).map_err(|e| bad(C, e))?; let boards = match (set.use_artboards, named) { @@ -216,29 +222,61 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi }; let corner = |r: Rect| Point::new(r.x0, r.y1); let art = |art: Rect| (None, art, doc.artboards.first().map_or(corner(art), |a| corner(a.rect))); + // The visible art's bounds; for Save with no visible art, the first artboard (true). + let visible = || match vectorcraft_render::encode::art_bounds(doc) { + Some(bounds) => Some((bounds, false)), + None if saving => doc.artboards.first().map(|a| (a.rect, true)), + None => None, + }; match boards { Some(boards) => { - let central = (boards.len() > 1).then(|| vectorcraft_render::encode::art_bounds(doc).map(art)).flatten(); + let central = (boards.len() > 1).then(visible).flatten(); let each = boards .into_iter() .map(|b| doc.artboards.get(b).map(|a| (Some(b), a.rect, corner(a.rect))).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))); - central.map(Ok).into_iter().chain(each).collect() + let pages = central.map(|(bounds, _)| Ok(art(bounds))).into_iter().chain(each).collect::<Result<_>>()?; + Ok((pages, central.is_some_and(|(_, blank)| blank))) } None => { - let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?; - Ok(vec![art(bounds)]) + let missing = if saving { "the document has no artboard" } else { "nothing to export: the document has no visible art" }; + let (bounds, blank) = visible().ok_or_else(|| bad(C, missing))?; + Ok((vec![art(bounds)], blank)) } } } -/// `rect` of `doc` drawn at a pixel a point (fewer when larger than `max` a side), straight RGBA, -/// transparent or on white. -fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Raster> { +/// Pixels a point for `rect`: one, or fewer when it is larger than `max` a side. +fn fit(rect: Rect, max: f64) -> f64 { let long = rect.width().max(rect.height()); - let scale = if long > max { max / long } else { 1.0 }; + if long > max { max / long } else { 1.0 } +} + +/// `rect` of `doc` drawn at [`fit`]'s scale for `max`, transparent or on white. +fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Rendered> { + let scale = fit(rect, max); vectorcraft_render::raster_size(rect, scale).map_err(|e| bad(C, e))?; - let img = r.render_region(doc, rect, scale, !transparent); - Ok(Raster { width: img.width, height: img.height, rgba: img.to_straight() }) + Ok(r.render_region(doc, rect, scale, !transparent)) +} + +/// `img` as the writer takes it: straight RGBA. +fn straight(img: &Rendered) -> Raster { + Raster { width: img.width, height: img.height, rgba: img.to_straight() } +} + +/// The thumbnail of `rect` made from `preview`, the same rect rendered larger: at the size a +/// thumbnail render of `rect` has, each pixel the average of the preview's pixels under it, on white. +fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> { + let (width, height) = vectorcraft_render::raster_size(rect, fit(rect, THUMBNAIL)).map_err(|e| bad(C, e))?; + let mut rgba = preview.area_resized(width, height).map_err(|e| bad(C, e))?.pixels; + // Premultiplied over white: each channel gains the white the pixel's alpha leaves showing. + for px in rgba.as_chunks_mut::<4>().0 { + let clear = 255 - px[3]; + for c in &mut px[..3] { + *c = c.saturating_add(clear); + } + px[3] = 255; + } + Ok(Raster { width, height, rgba }) } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of @@ -268,16 +306,17 @@ pub(super) fn encode(doc: &Document, p: &Value) -> Result<Encoded> { encode_document(doc, p, false) } -/// Save keeps a single page's original frame and all native editing data, unlike Export's -/// optional art-bound crop or separate file per artboard. Existing EPS loss warnings still apply. +/// Save writes the pages Export does (the visible art's bounds, or with Use Artboards the chosen +/// artboards), with a smaller preview. A single file, the one the document becomes, carries all +/// the native editing data; with no visible art its page is the first artboard. pub(super) fn encode_save(doc: &Document, p: &Value) -> Result<Encoded> { encode_document(doc, p, true) } fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { let set = parse(p)?; - if saving && (set.use_artboards == Some(false) || bool_or(p, "selectedOnly", false)) { - return Err(bad(C, "EPS Save retains the artboard and all artwork: use document.export for cropped or selected-only EPS")); + if saving && bool_or(p, "selectedOnly", false) { + return Err(bad(C, "EPS Save writes all artwork: use document.export for selected-only EPS")); } let original = doc; let (full, warnings) = crate::cmd::place::document::full_documents(doc); @@ -290,18 +329,16 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { } else { Cow::Borrowed(original) }; - let pages = if saving { - let board = set.boards.one(doc.artboards.len()).map_err(|e| bad(C, e))?; - let rect = doc.artboards.get(board).ok_or_else(|| bad(C, "the document has no artboard"))?.rect; - vec![(Some(board), rect, Point::new(rect.x0, rect.y1))] - } else { - pages(doc, &set)? - }; + let (pages, blank) = pages(doc, &set, saving)?; if pages.is_empty() { return Err(bad(C, "the document has no artboard")); } - // The artboards' background colors, behind the art (the editing data keeps them as colors). - let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?; + // The file Save writes alone becomes the document's own, so it carries every artboard. + let whole = saving && pages.len() == 1; + // The artboards' background colors, behind the art (the editing data keeps them as colors); + // a page on the first artboard because no art shows has that artboard's color. + let fills = pages.iter().filter_map(|(b, ..)| *b).chain(blank.then_some(0)); + let filled = super::export::with_artboard_fills(doc, p, fills).map_err(|e| bad(C, e))?; let doc = &*filled; let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect(); let expanded = expand_transparent_tile_images(doc, &set.flatten)?; @@ -318,17 +355,24 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> { let mut renderer = vectorcraft_render::Renderer::new(); for (board, region, origin) in pages { let rect = vectorcraft_eps::preview_rect(region, origin); - let preview = match set.eps.preview { + let shown = match set.eps.preview { Preview::None => None, kind => Some(render(&mut renderer, doc, rect, preview_limit, set.eps.transparent_preview && kind == Preview::TiffColor)?), }; - let thumbnail = set.thumbnails.then(|| render(&mut renderer, doc, rect, THUMBNAIL, false)).transpose()?; + // The thumbnail is made from the preview; only a file without one renders it. + let thumbnail = match (set.thumbnails, &shown) { + (false, _) => None, + (true, Some(img)) => Some(thumbnail_of(img, rect)?), + (true, None) => Some(straight(&render(&mut renderer, doc, rect, THUMBNAIL, false)?)), + }; + let preview = shown.as_ref().map(straight); + drop(shown); let o = EpsOptions { region, origin, - title: doc.title.clone(), + title: doc.info_title().to_owned(), created, - native: Some(native(&editing, if saving { None } else { board }, set.include_linked)), + native: Some(native(&editing, if whole { None } else { board }, set.include_linked)), ..set.eps.clone() }; let out = vectorcraft_eps::export(drawn, &o, preview.as_ref(), thumbnail.as_ref()).map_err(|e| bad(C, e))?; diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 02dda6f0f0..62e5b78e6b 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -9,14 +9,14 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes}; use crate::DocState; -use super::super::{Result, Session, bad, bool_or, edit, f64_or, str_param}; +use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param}; use super::encode::single_artboard; use super::{ ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return, }; pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> { - let f = writable("document.serialize", Some(str_param(p, "format").unwrap_or("vectorcraft")), None)?; + let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?; let expanded = expand_presets(s, "document.serialize", p)?; let p = with_black_output(s, &expanded); let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?; @@ -53,11 +53,11 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> { } pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> { - let path = str_param(p, "path"); + let path = text_param(p, "path", "document.export")?; if let Some(path) = path { super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?; } - let f = writable("document.export", str_param(p, "format"), path)?; + let f = writable("document.export", text_param(p, "format", "document.export")?, path)?; let expanded = expand_presets(s, "document.export", p)?; let p = with_black_output(s, &expanded); let (doc, display_doc_title) = source(s, f, &p, "document.export")?; @@ -86,7 +86,7 @@ pub fn export_doc<'a>(st: &'a DocState, f: &Format, p: &Value) -> Result<Cow<'a, /// The document an export of `st` writes: the whole document, or with `selectedOnly` just the /// selected objects, each in its layers and groups (a clipping group keeps its clipping path). pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document>> { - if !bool_or(p, "selectedOnly", false) { + if !switch_or(p, "selectedOnly", false, "document.export")? { return Ok(Cow::Borrowed(&*st.doc)); } let keep: HashSet<NodeId> = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc)).into_iter().collect(); @@ -237,7 +237,8 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va /// The document an export of `f` writes: the active one (see [`export_source`]), or for text /// with `selectionOnly` the selected objects alone. fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> { - if f.id == "txt" && bool_or(p, "selectionOnly", false) { + check_switches(p, &["selectedOnly"], cmd)?; + if switch_or(p, "selectionOnly", false, cmd)? && f.id == "txt" { let doc = selection(s, cmd, true)?.0; let display_doc_title = super::has_own_title(&doc); return Ok((Cow::Owned(doc), display_doc_title)); @@ -309,11 +310,11 @@ pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Do /// are guides, not artwork, and are left out. pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "document.exportSelection"; - if let Some(path) = str_param(p, "path") { + let path = text_param(p, "path", C)?; + if let Some(path) = path { super::check_not_lossy_overwrite(s.doc()?, path, p, C)?; } - let path = str_param(p, "path"); - let f = writable(C, str_param(p, "format"), path)?; + let f = writable(C, text_param(p, "format", C)?, path)?; let expanded = expand_presets(s, C, p)?; let p = with_black_output(s, &expanded); let (d, bounds) = selection(s, C, f.id == "txt")?; @@ -327,11 +328,12 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> { /// `transparent`, with the encoder's warnings. pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "document.exportForOffice"; - if let Some(path) = str_param(p, "path") { + let path = text_param(p, "path", C)?; + if let Some(path) = path { super::check_not_lossy_overwrite(s.doc()?, path, p, C)?; } - let path = str_param(p, "path"); - let ppi = f64_or(p, "ppi", 150.0); + let ppi = number_or(p, "ppi", 150.0, C)?; + let transparent = switch_or(p, "transparent", false, C)?; let doc = &s.doc()?.doc; let artboard = match p.get("artboard") { None | Some(Value::Null) => 0, @@ -340,7 +342,7 @@ pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> { if artboard >= doc.artboards.len() { return Err(bad(C, format!("no artboard {artboard} (0-based; the document has {})", doc.artboards.len()))); } - let background = if bool_or(p, "transparent", false) { "transparent" } else { "white" }; + let background = if transparent { "transparent" } else { "white" }; let opts = with_black_output(s, &json!({ "ppi": ppi, "background": background, "artboard": artboard })); let (bytes, warnings) = encode_with_warnings(doc, "png", &opts)?; // The pixel size, from the PNG header. diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 23aeb83bb0..d5137c8b1a 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -1,6 +1,7 @@ use super::super::unique_name; use super::{ - Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, json, metafile, native, pdf, screens, svg, text, unsupported, + Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text, + unsupported, }; /// One option a format's encoder reads from the export params. @@ -479,6 +480,17 @@ pub const FORMATS: &[Format] = &[ }, Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS }, Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS }, + // HP-GL/2 plot files, read by `vectorcraft_cad::hpgl` into paths and written as pen moves. + Format { + id: "hpgl", + label: "HP-GL", + extensions: &["plt", "hpgl", "hgl", "hpg"], + mime: "application/vnd.hp-hpgl", + read: true, + write: true, + raster: false, + options: hpgl::OPTIONS, + }, Format { id: "tga", label: "Targa", @@ -493,7 +505,8 @@ pub const FORMATS: &[Format] = &[ // Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a // vector app for a raster editor's documents. reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false), - // Photoshop's large document format: read like a PSD (its merged image), never written. + // The large document form of PSD: read like a PSD (its layers, or its merged image), never + // written. reader("psb", "PSB", &["psb"], "image/x-psb", true), // PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't. reader("ps", "PostScript", &["ps"], "application/postscript", false), @@ -551,6 +564,10 @@ pub const OPEN_EXTS: &[&str] = &[ "dxf", "emf", "wmf", + "plt", + "hpgl", + "hgl", + "hpg", "eps", "epsf", "ps", @@ -564,9 +581,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. +/// The packaging declares no type for HP-GL plot files either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", + "heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -640,6 +658,10 @@ pub const PLACE_EXTS: &[&str] = &[ "dxf", "emf", "wmf", + "plt", + "hpgl", + "hgl", + "hpg", "eps", "epsf", "ps", @@ -908,13 +930,20 @@ pub(crate) fn import_name(base: &str, taken: impl Fn(&str) -> bool) -> String { /// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep /// the stored title. pub fn has_own_title(doc: &vectorcraft_doc::Document) -> bool { - !doc.title.trim().is_empty() && !doc.title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + is_own_title(doc.info_title()) +} + +/// Is `title` one a person or a file gave, not blank and not the Untitled-N name New gives? +pub(crate) fn is_own_title(title: &str) -> bool { + !title.trim().is_empty() && !title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) } pub fn titled_for_export(doc: &vectorcraft_doc::Document, path: Option<&str>, format: &str) -> Option<vectorcraft_doc::Document> { let path = path.filter(|_| !has_own_title(doc) && !matches!(format, "vectorcraft" | "template" | "ai"))?; let mut d = doc.clone(); d.title = file_stem(path); + // A File Info title that is no title of its own (blank, or an Untitled-N name) would hide it. + d.metadata.title = None; Some(d) } diff --git a/crates/engine/src/cmd/fileio/hpgl.rs b/crates/engine/src/cmd/fileio/hpgl.rs new file mode 100644 index 0000000000..ff6e63fbd7 --- /dev/null +++ b/crates/engine/src/cmd/fileio/hpgl.rs @@ -0,0 +1,126 @@ +//! HP-GL for every path that writes plot files (`vectorcraft_cad::hpgl`): `document.export {format: +//! hpgl}` and Export As (one plot of an artboard, or one per artboard with Use Artboards), with the +//! options parsed from the params. + +use serde_json::Value; +use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; +use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version}; +use vectorcraft_doc::Document; + +use super::super::{Result, bad, number_or, switch_or, text_param}; +use super::{ArtboardPick, Encoded, FormatOption}; + +const C: &str = "document.export"; + +/// The options `document.formats` lists for HP-GL. +pub(super) const OPTIONS: &[FormatOption] = &[ + super::ARTBOARD, + super::ARTBOARDS, + super::RANGE, + super::USE_ARTBOARDS, + FormatOption { + name: "hpglVersion", + ty: "string", + default: "\"hpgl\"", + description: "hpgl (IN, SP, PU and PD only; a coordinate outside -32,768 to 32,767 gets a warning) or hpgl2 (also the pens' colors, NP and PC, and each pen's paths as one encoded polyline, PE)", + }, + FormatOption { + name: "curveTolerance", + ty: "number", + default: "0.1", + description: "how far the straight moves a curve becomes may lie from it, in points (0.01 to 10)", + }, + FormatOption { + name: "pens", + ty: "array", + default: "null", + description: "the pen table, pen 1's color first: up to 255 \"#rrggbb\" colors, each path drawn with the pen of the nearest color; null: a pen for each color in the order the art first draws in it, numbered alike in every file of one export", + }, + FormatOption { + name: "origin", + ty: "string", + default: "\"bottomLeft\"", + description: "bottomLeft or center: where (0, 0) lies on the artboard (or the art's bounds)", + }, + FormatOption { + name: "sortPaths", + ty: "boolean", + default: "false", + description: "draw each pen's next path from the end nearest where the pen stopped, instead of in paint order", + }, + FormatOption { + name: "insideFirst", + ty: "boolean", + default: "false", + description: "draw a path only after the pen's paths that lie inside it (a letter's counter before the letter, a hole before the part), the paths otherwise in paint order; with sortPaths, the nearest of the paths free to draw comes next", + }, +]; + +/// The HP-GL options in `p` (the region is set per plot). +fn parse(p: &Value) -> Result<HpglOptions> { + let mut o = HpglOptions::default(); + if let Some(s) = text_param(p, "hpglVersion", C)? { + let key = "hpglVersion"; + o.version = Version::from_id(s).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", Version::ALL.map(Version::id).join(", "))))?; + } + let x = number_or(p, "curveTolerance", DEFAULT_TOLERANCE, C)?; + if !TOLERANCE_RANGE.contains(&x) { + let (key, min, max) = ("curveTolerance", TOLERANCE_RANGE.start(), TOLERANCE_RANGE.end()); + return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + o.tolerance = x; + match p.get("pens") { + None | Some(Value::Null) => {} + Some(v) => { + let colors: Option<Vec<[u8; 3]>> = v.as_array().filter(|a| (1..=MAX_PENS).contains(&a.len())).and_then(|a| a.iter().map(hex).collect()); + o.pens = colors.ok_or_else(|| bad(C, "`pens` must be an array of 1 to 255 #rrggbb colors"))?; + } + } + if let Some(s) = text_param(p, "origin", C)? { + let key = "origin"; + o.origin = Origin::from_id(s).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", Origin::ALL.map(Origin::id).join(", "))))?; + } + o.sort = switch_or(p, "sortPaths", false, C)?; + o.inside_first = switch_or(p, "insideFirst", false, C)?; + Ok(o) +} + +/// A `#rrggbb` color. +fn hex(v: &Value) -> Option<[u8; 3]> { + let s = v.as_str()?.strip_prefix('#').filter(|s| s.len() == 6 && s.bytes().all(|b| b.is_ascii_hexdigit()))?; + let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + Some([byte(0)?, byte(2)?, byte(4)?]) +} + +/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with +/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all. +pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> { + let opts = parse(p)?; + let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?; + let pick: ArtboardPick = super::encode::options(f, p)?; + let n = doc.artboards.len(); + let boards = match use_artboards { + Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), + _ => vec![pick.one(n).map_err(|e| bad(C, e))?], + }; + let regions = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::<Result<Vec<_>>>()?; + let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?; + let mut enc = Encoded::default(); + for (b, out) in boards.into_iter().zip(plots) { + enc.files.push((Some(b), out.bytes)); + for w in out.warnings { + if !enc.warnings.contains(&w) { + enc.warnings.push(w); + } + } + } + if enc.files.is_empty() { + return Err(bad(C, "the document has no artboard")); + } + let regions: Vec<vectorcraft_geom::Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect(); + enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions))); + Ok(enc) +} diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index a197363b23..1fd3e10a9f 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -145,7 +145,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result } } } - let o = vectorcraft_eps::LegacyAiOptions { title: doc.title.clone(), created, hidden, outline_text }; + let o = vectorcraft_eps::LegacyAiOptions { title: doc.info_title().to_owned(), created, hidden, outline_text }; let out = vectorcraft_eps::export_legacy_ai(&d, &o).map_err(|e| bad(cmd, e))?; for w in placed.iter().chain(&out.warnings) { note(&mut enc.warnings, w); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 9b3223829f..3040cfc43f 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -7,6 +7,7 @@ use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; use vectorcraft_geom::Affine; use vectorcraft_render::effects::pixel::LoadedTexture; +use super::super::fileinfo::imported_title; use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param}; use super::pdfimport::LoadOptions; use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name}; @@ -63,6 +64,7 @@ impl Loaded { /// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG /// (what browsers, PDF and SVG viewers show). +#[derive(Clone)] pub struct RasterImage { /// Content key for `Document::images` (identical files share one blob). pub key: String, @@ -133,6 +135,17 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if clipboard::looks_like_svg(&String::from_utf8_lossy(&bytes[..bytes.len().min(4096)])) { return format("svg"); } + // HP-GL has no signature: a file that starts with plotter instructions, named as one or with an + // extension no other format (text, the formats VectorCraft names as unsupported, and the files + // File › Open takes in other ways included) reads. + let ext = super::extension(name); + let other = by_name.is_some_and(|f| f.id != "hpgl") + || super::TEXT_EXTS.contains(&ext.as_str()) + || super::unsupported(&ext).is_some() + || super::opens_as_other(&ext); + if !other && vectorcraft_cad::hpgl::is_hpgl(bytes) { + return format("hpgl"); + } by_name } @@ -305,10 +318,10 @@ pub(super) fn outlined_if_asked(mut doc: Document, warnings: Vec<String>, opts: (doc, warnings) } -/// Does `doc` hold no art: only layers, with nothing in them? +/// Does `doc` hold no art: only layers, with nothing in them but ruler guides? fn draws_nothing(doc: &Document) -> bool { let mut art = false; - doc.walk(|n| art |= !n.is_layer()); + doc.walk(|n| art |= !n.is_layer() && !n.is_ruler_guide()); !art } @@ -486,11 +499,25 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> let (doc, warnings) = super::metafile::import(bytes)?; (doc, warnings, false) } + "hpgl" => { + let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?; + (i.document, i.warnings, false) + } "affinity" => { let i = super::affinity::import(&title, bytes)?; preview_only = i.preview_only; (i.doc, i.warnings, false) } + // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with + // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. + "psd" | "psb" if opts.layers => { + let cms = vectorcraft_color::cms::active(); + match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) { + Ok(Some((doc, warnings))) => (doc, warnings, false), + Ok(None) => (raster_doc(&title, bytes)?, vec![], false), + Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false), + } + } _ if format.raster => (raster_doc(&title, bytes)?, vec![], false), _ => return Err(err(format!("{} files can't be opened yet", format.label))), }; @@ -524,6 +551,15 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) { super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays); } + // The title the file gives itself (an SVG's `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` + // or Info `Title`, which the readers put in File Info) is separate from the document's name. + // Restored File Info is preserved exactly; newly imported SVG candidates and a restored + // document's legacy name fallback are cleaned as imported text. The name stays the file's (#3626). + if !restored && matches!(format.id, "svg" | "svgz") { + doc.metadata.title = doc.metadata.title.as_deref().and_then(imported_title); + } + let held = restored.then_some(doc.title.as_str()).filter(|t| *t != title); + doc.metadata.title = doc.metadata.title.or_else(|| held.and_then(imported_title)); // Imports are named after the file; a native document keeps its own title (the tab shows the // file name once it has a path). if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() { @@ -652,6 +688,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St if template { doc.template = false; doc.title = s.next_untitled(); + doc.metadata.title = None; } // A .ai (or .ait) another app wrote carries no open Layers rows we read: all of them start // closed, its top-level layers as its groups (#1475). Ours carry their own. @@ -685,7 +722,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St st.import_losses = losses; st.links_from = read_from; let opened = &s.documents()[index]; - let (title, file_info_title) = (opened.title(), opened.doc.title.clone()); + let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string()); Ok(super::merge( json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json(), diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index ccafc96e5e..1f166797f8 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -42,7 +42,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "compatibility", ty: "string", default: "\"1.7\"", - description: "PDF version: 1.3 (transparency flattened) | 1.4 | 1.5 | 1.6 | 1.7 | 2.0", + description: "PDF version: 1.3 (transparency flattened) | 1.4 | 1.5 | 1.6 | 1.7 | 2.0 (a pdfA2b file at 1.4 with a page longer than 14,400 pt is written as 1.6, with a UserUnit as at 1.6, and a warning; see document.exportPdf)", }, FormatOption { name: "preserveEditing", @@ -95,6 +95,12 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ default: "false", description: "keep the layers whose Print option is off (left out otherwise, unless createLayers)", }, + FormatOption { + name: "longPagesInPoints", + ty: "boolean", + default: "false", + description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)", + }, FormatOption { name: "createLayers", ty: "boolean", @@ -122,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 2a67cf4a45..2a0dede17f 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -28,8 +28,10 @@ pub struct LoadOptions { /// What a PDF's text becomes. pub text_as: TextAs, /// A PDF's optional content groups become layers (else one layer per page, without the art - /// that is off). + /// that is off), and a PSD or PSB file's layers become layers (else its merged image opens). pub layers: bool, + /// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out). + pub hidden_layers: bool, /// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]). pub dxf: vectorcraft_cad::ImportOptions, /// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its @@ -57,6 +59,7 @@ impl Default for LoadOptions { grays: Grays::default(), text_as: TextAs::default(), layers: true, + hidden_layers: false, dxf: Default::default(), editing_data: true, trust_editing_data: false, @@ -69,7 +72,8 @@ impl Default for LoadOptions { impl LoadOptions { /// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, - /// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`), + /// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false), + /// `editingData` (true | false | `always`), /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF /// import options). pub fn from_params(cmd: &str, p: &Value) -> Result<Self> { @@ -95,6 +99,10 @@ impl LoadOptions { None => true, Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?, }; + let hidden_layers = match p.get("hiddenLayers").filter(|v| !v.is_null()) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?, + }; let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) { None => (true, false), Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true), @@ -108,7 +116,21 @@ impl LoadOptions { .ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?, }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; - Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true }) + Ok(Self { + pages, + crop, + password, + color_mode, + grays, + text_as, + layers, + hidden_layers, + dxf, + editing_data, + trust_editing_data, + legacy_names, + native: true, + }) } /// Does the document read only part of the file, or read it differently (a page range, another diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs new file mode 100644 index 0000000000..c3c45029a0 --- /dev/null +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -0,0 +1,1529 @@ +//! File › Open of a PSD or PSB file with its layers as objects. The import option that converts +//! layers to objects +//! (<https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html>) +//! keeps as much of the layer structure as it can, merges the layers of a clipping mask into one +//! layer, and discards hidden layers that need merging; the rest of what this module does is +//! VectorCraft's own. Read from the layer records of the public PSD file format specification +//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). +//! +//! Each layer becomes a layer of the document, with the layer's name, visibility, opacity and blend +//! mode, holding its pixels as an image at their place on the canvas. A layer group becomes a layer +//! whose sublayers are the group's layers (a pass-through group lets them blend with what is below +//! it; any other group is isolated). A layer mask becomes the layer's opacity mask: a gray image +//! whose outside is hidden or shown as the mask's default color says, kept and switched off when +//! the mask is disabled. A layer's opacity is multiplied by its fill opacity, except in a layer +//! that others are clipped to, whose fill opacity fades only its own pixels. A solid color fill +//! layer that stores no pixels and has no vector mask comes in as an image of its color over the +//! canvas (an RGB, CMYK, Grayscale, Lab or HSB color); type, shape and other fill layers come in as +//! the pixels the file stores for them. +//! +//! Layers clipped to the layer below them are merged into it as one image (named after them all, +//! joined with " + "), shown where the layer below has pixels. Layers clipped to an adjustment +//! layer, or to a fill layer drawn over the whole canvas, show over the whole canvas. A layer in a +//! blend mode VectorCraft doesn't have (Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear +//! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the +//! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque +//! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern +//! that differs from layer to layer. When a merge's canvases would need more memory than allowed, +//! the layer comes in alone: in the Normal mode, or unclipped. +//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge +//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or +//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers, +//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask, +//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings +//! count them and the hidden layers left out. +//! +//! The file is untrusted: every count, length and size is checked before anything is allocated, +//! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the +//! group around them, with a warning), each layer's pixels, like the canvases one step of a +//! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases +//! the merges make must fit [`TOTAL_DECODED`] times that. + +use std::cell::Cell; +use std::sync::Arc; + +use image::RgbaImage; +use vectorcraft_color::BlendMode; +use vectorcraft_color::blend::{blend_rgb, composite}; +use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; +use vectorcraft_doc::{Document, ImageObject, LAYER_COLORS, LayerColor, Node, NodeKind, OpacityMask}; +use vectorcraft_geom::Affine; + +use super::load::{RasterImage, as_png}; +use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb}; +use crate::cmd::place::text::mac_roman; + +/// Most layer groups inside one another. +pub(super) const MAX_DEPTH: usize = 64; +/// The pixels all layers and masks decode to, merges' second readings included, and the canvases +/// the merges make may take this many times the memory allowed for one image. +const TOTAL_DECODED: u64 = 8; +/// Most channels one layer has (colors, transparency and masks), as many as a document may. +const MAX_CHANNELS: usize = 56; +/// The fewest bytes a layer record takes. +const MIN_RECORD: usize = 34; +const DAMAGED: &str = "the PSD file's layer records are damaged"; + +/// The keys of the tagged blocks that make a layer an adjustment layer. +const ADJUSTMENTS: [&[u8; 4]; 18] = [ + b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL", + b"blwh", b"CgEd", +]; + +/// A layer's blend mode. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Blend { + Mode(BlendMode), + /// A group's Pass Through. + Pass, + /// A mode VectorCraft doesn't have: the layer is merged with the layers below it. + Other(Other), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Other { + Dissolve, + LinearBurn, + LinearDodge, + VividLight, + LinearLight, + PinLight, + HardMix, + Subtract, + Divide, + DarkerColor, + LighterColor, +} + +impl Other { + fn label(self) -> &'static str { + match self { + Other::Dissolve => "Dissolve", + Other::LinearBurn => "Linear Burn", + Other::LinearDodge => "Linear Dodge", + Other::VividLight => "Vivid Light", + Other::LinearLight => "Linear Light", + Other::PinLight => "Pin Light", + Other::HardMix => "Hard Mix", + Other::Subtract => "Subtract", + Other::Divide => "Divide", + Other::DarkerColor => "Darker Color", + Other::LighterColor => "Lighter Color", + } + } +} + +/// The blend mode a record's key names (an unknown key: Normal). +fn blend(key: &[u8; 4]) -> Blend { + use BlendMode as M; + let mode = match key { + b"pass" => return Blend::Pass, + b"diss" => return Blend::Other(Other::Dissolve), + b"lbrn" => return Blend::Other(Other::LinearBurn), + b"lddg" => return Blend::Other(Other::LinearDodge), + b"vLit" => return Blend::Other(Other::VividLight), + b"lLit" => return Blend::Other(Other::LinearLight), + b"pLit" => return Blend::Other(Other::PinLight), + b"hMix" => return Blend::Other(Other::HardMix), + b"fsub" => return Blend::Other(Other::Subtract), + b"fdiv" => return Blend::Other(Other::Divide), + b"dkCl" => return Blend::Other(Other::DarkerColor), + b"lgCl" => return Blend::Other(Other::LighterColor), + b"dark" => M::Darken, + b"mul " => M::Multiply, + b"idiv" => M::ColorBurn, + b"lite" => M::Lighten, + b"scrn" => M::Screen, + b"div " => M::ColorDodge, + b"over" => M::Overlay, + b"sLit" => M::SoftLight, + b"hLit" => M::HardLight, + b"diff" => M::Difference, + b"smud" => M::Exclusion, + b"hue " => M::Hue, + b"sat " => M::Saturation, + b"colr" => M::Color, + b"lum " => M::Luminosity, + _ => M::Normal, + }; + Blend::Mode(mode) +} + +/// A rectangle of the canvas, in pixels: top, left, bottom, right. +#[derive(Clone, Copy, Debug, Default)] +struct Bounds { + top: i32, + left: i32, + bottom: i32, + right: i32, +} + +impl Bounds { + fn read(r: &mut Reader<'_>) -> Result<Self, String> { + let mut v = || r.u32().map(|v| v as i32); + Ok(Self { top: v()?, left: v()?, bottom: v()?, right: v()? }) + } + /// Width and height (0 when empty or inverted). + fn size(self) -> (usize, usize) { + let side = |a: i32, b: i32| usize::try_from(i64::from(b) - i64::from(a)).unwrap_or(0); + (side(self.left, self.right), side(self.top, self.bottom)) + } +} + +/// What a layer holds besides plain pixels. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Content { + Pixels, + /// A type layer: its pixels come in. + Type, + /// An adjustment layer: not applied. + Adjustment, + /// A solid color fill layer: its stored pixels, or its color over the whole canvas when it + /// stores none (nothing when the color can't be read, or when its shape is a vector mask). + Solid(Option<Paint>), + /// A gradient or pattern fill layer: its stored pixels, if any. + Fill, +} + +/// A solid color fill layer's color. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Paint { + /// sRGB, 0..1. + Rgb([f32; 3]), + /// Ink amounts, 0..1. + Cmyk([f32; 4]), +} + +/// A layer mask's place and its color outside it. +#[derive(Clone, Copy, Debug)] +struct MaskInfo { + bounds: Bounds, + default: u8, + disabled: bool, + /// The mask's values, and its default color, are read inverted. + inverted: bool, +} + +/// One layer record: a layer, or a group's opening or closing divider. +struct Record<'a> { + name: String, + bounds: Bounds, + /// Channel id (−1 transparency, −2 the layer mask, 0.. the colors) and its data, compression + /// method first. + channels: Vec<(i16, &'a [u8])>, + blend: Blend, + /// The layer's opacity, 0..1. + opacity: f32, + /// Its fill opacity, 0..1. + fill: f32, + clipped: bool, + hidden: bool, + mask: Option<MaskInfo>, + /// The section divider type: 0 a layer, 1 or 2 a group (open or closed in the panel), 3 the + /// end of a group (the record below its layers). + divider: u32, + content: Content, + effects: bool, + vector_mask: bool, + knockout: bool, +} + +/// The layer records of `info` (the layer count, the records, then their channels' data). +fn records(info: &[u8], psb: bool) -> Result<Vec<Record<'_>>, String> { + let mut r = Reader::new(info); + let count = usize::from((r.u16()? as i16).unsigned_abs()); + if count.saturating_mul(MIN_RECORD) > info.len() { + return Err(DAMAGED.into()); + } + let mut heads = Vec::with_capacity(count); + for _ in 0..count { + heads.push(record(&mut r, psb)?); + } + let mut out = Vec::with_capacity(count); + for (mut rec, lengths) in heads { + rec.channels = lengths.into_iter().map(|(id, n)| r.take(n).map(|d| (id, d))).collect::<Result<_, _>>()?; + out.push(rec); + } + Ok(out) +} + +/// One record, with the lengths of its channels' data (which follows every record). +fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, usize)>), String> { + let bounds = Bounds::read(r)?; + let n = usize::from(r.u16()?); + if n > MAX_CHANNELS { + return Err(DAMAGED.into()); + } + let mut lengths = Vec::with_capacity(n); + for _ in 0..n { + let id = r.u16()? as i16; + lengths.push((id, r.length(psb)?)); + } + if &r.array::<4>()? != b"8BIM" { + return Err(DAMAGED.into()); + } + let blend = blend(&r.array()?); + let opacity = f32::from(r.u8()?) / 255.0; + let clipped = r.u8()? != 0; + // Bit 1: hidden. + let hidden = r.u8()? & 2 != 0; + r.u8()?; + let extra = r.section(false)?; + let mut rec = Record { + name: String::new(), + bounds, + channels: vec![], + blend, + opacity, + fill: 1.0, + clipped, + hidden, + mask: None, + divider: 0, + content: Content::Pixels, + effects: false, + vector_mask: false, + knockout: false, + }; + rec.read_extra(extra, psb)?; + Ok((rec, lengths)) +} + +impl Record<'_> { + /// The layer mask, blending ranges, name and tagged blocks after the record's fixed part. A + /// damaged mask, blending ranges or name is an error; a damaged tagged block keeps what was + /// read before it. + fn read_extra(&mut self, extra: &[u8], psb: bool) -> Result<(), String> { + let damaged = |_| DAMAGED.to_string(); + let mut e = Reader::new(extra); + let mask = e.section(false).map_err(damaged)?; + self.mask = match mask_info(mask) { + Some(info) => Some(info), + None if mask.is_empty() => None, + None => return Err(DAMAGED.into()), + }; + // The blending ranges. + e.section(false).map_err(damaged)?; + // A Pascal string padded to a multiple of 4 bytes, length byte included, in the system's + // encoding (its Unicode name follows in `luni`), read as Mac Roman as psd-tools (MIT) reads + // it: <https://github.com/psd-tools/psd-tools>, `psd/layer_and_mask.py`. + let n = usize::from(e.u8().map_err(damaged)?); + let name = e.take(n).map_err(damaged)?; + self.name = name.iter().map(|&b| mac_roman(b)).collect(); + e.take((4 - (n + 1) % 4) % 4).map_err(damaged)?; + // Effects in a descriptor (`lfx2`, `lmfx`) say whether they are switched on; the older + // `lrFX` block is counted whenever it is there. + let (mut effects, mut old_effects) = (None, false); + while e.rest().len() >= 12 { + let (Ok(signature), Ok(key)) = (e.array::<4>(), e.array::<4>()) else { break }; + if !matches!(&signature, b"8BIM" | b"8B64") { + break; + } + let Ok(data) = e.section(psb && long_key(&key)) else { break }; + match &key { + b"luni" => { + if let Some(name) = unicode(data) { + self.name = name; + } + } + b"lsct" | b"lsdk" => { + if let Some(t) = data.get(..4) { + self.divider = u32::from_be_bytes([t[0], t[1], t[2], t[3]]); + } + if data.get(4..8) == Some(b"8BIM") + && let Some(Ok(key)) = data.get(8..12).map(<[u8; 4]>::try_from) + { + self.blend = blend(&key); + } + } + b"iOpa" => self.fill = data.first().map_or(1.0, |&v| f32::from(v) / 255.0), + b"TySh" | b"tySh" => self.content = Content::Type, + b"SoCo" => self.content = Content::Solid(solid_color(data)), + b"GdFl" | b"PtFl" => self.content = Content::Fill, + b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)), + b"lrFX" => old_effects = true, + b"vmsk" | b"vsms" => self.vector_mask = true, + // Shallow or deep knockout. + b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0), + k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, + _ => {} + } + // Some writers pad blocks further: skip to the next signature. + for _ in 0..3 { + if e.rest().is_empty() || e.rest().starts_with(b"8BIM") || e.rest().starts_with(b"8B64") { + break; + } + let _ = e.take(1); + } + } + self.effects = effects.unwrap_or(old_effects); + Ok(()) + } + + /// Does the record store no pixels (bounds of no area, or no color channel)? + fn stores_nothing(&self) -> bool { + let (w, h) = self.bounds.size(); + w == 0 || h == 0 || !self.channels.iter().any(|(id, _)| *id >= 0) + } + + /// Is the layer a fill drawn from its color over the whole canvas (a solid color fill that + /// stores no pixels and has no vector mask)? + fn color_over_canvas(&self) -> bool { + matches!(self.content, Content::Solid(Some(_))) && self.stores_nothing() && !self.vector_mask + } + + /// Does the layer cover the whole canvas without drawing (an adjustment layer, or a fill that + /// stores no pixels, has no vector mask and isn't drawn from its color)? Layers clipped to it + /// show over the whole canvas. + fn covers_without_drawing(&self) -> bool { + match self.content { + Content::Adjustment => true, + Content::Solid(None) | Content::Fill => self.stores_nothing() && !self.vector_mask, + _ => false, + } + } + + /// Is the layer a fill that stores no pixels and whose shape is a vector mask, so that it + /// isn't drawn? + fn undrawn_shape(&self) -> bool { + matches!(self.content, Content::Solid(_) | Content::Fill) && self.stores_nothing() && self.vector_mask + } +} + +/// Does an effects descriptor (`lfx2`, `lmfx`) have its master switch on and an effect switched on? +/// Read as psd-tools (MIT) reads them, a missing switch being off: `masterFXSwitch` and each +/// effect's `enab` (<https://github.com/psd-tools/psd-tools>, `api/effects.py`). +fn effects_on(data: &[u8]) -> bool { + // A key, then its type `bool`, then one byte. + let values = |key: &'static [u8]| data.windows(key.len() + 1).filter(move |w| w.starts_with(key)).filter_map(|w| w.last().map(|&v| v != 0)); + values(b"masterFXSwitchbool").any(|on| on) && values(b"enabbool").any(|on| on) +} + +/// The layer mask data's place, default color, disabled flag (bit 1) and invert flag (bit 2). +fn mask_info(data: &[u8]) -> Option<MaskInfo> { + let mut r = Reader::new(data); + let bounds = Bounds::read(&mut r).ok()?; + let default = r.u8().ok()?; + let flags = r.u8().ok()?; + Some(MaskInfo { bounds, default, disabled: flags & 2 != 0, inverted: flags & 4 != 0 }) +} + +/// A `luni` block's name: a count of UTF-16 units, then the units. +fn unicode(data: &[u8]) -> Option<String> { + let mut r = Reader::new(data); + let n = usize::try_from(r.u32().ok()?).ok()?; + let units: Vec<u16> = r.take(n.checked_mul(2)?).ok()?.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect(); + Some(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) +} + +/// The color of a solid color fill layer's descriptor, from the values after its color keys: red, +/// green and blue (0..255, or 0..1 in the `redFloat` keys), cyan, magenta, yellow and black (0..100 +/// percent ink), gray (0..100 percent black), Lab (L 0..100, a and b) or hue (degrees), saturation +/// and brightness (0..100). `None` for a color in another model. +fn solid_color(data: &[u8]) -> Option<Paint> { + // A key, then `doub` and a double, or `UntF`, a unit and a double. + let value = |key: &[u8]| -> Option<f64> { + let at = data.windows(key.len()).position(|w| w == key)? + key.len(); + let at = match data.get(at..at + 4)? { + b"doub" => at + 4, + b"UntF" => at + 8, + _ => return None, + }; + let v = f64::from_be_bytes(data.get(at..at + 8)?.try_into().ok()?); + v.is_finite().then_some(v) + }; + let unit = |v: f64| v.clamp(0.0, 1.0) as f32; + let rgb = |keys: [&[u8]; 3], scale: f64| -> Option<[f32; 3]> { + Some([unit(value(keys[0])? / scale), unit(value(keys[1])? / scale), unit(value(keys[2])? / scale)]) + }; + if let Some(c) = rgb([b"Rd ", b"Grn ", b"Bl "], 255.0).or_else(|| rgb([b"redFloat", b"greenFloat", b"blueFloat"], 1.0)) { + return Some(Paint::Rgb(c)); + } + if let (Some(c), Some(m), Some(y), Some(k)) = (value(b"Cyn "), value(b"Mgnt"), value(b"Ylw "), value(b"Blck")) { + return Some(Paint::Cmyk([c, m, y, k].map(|v| unit(v / 100.0)))); + } + if let Some(g) = value(b"Gry ") { + return Some(Paint::Rgb([unit(1.0 - g / 100.0); 3])); + } + if let (Some(l), Some(a), Some(b)) = (value(b"Lmnc"), value(b"A "), value(b"B ")) { + let [r, g, b] = lab_to_srgb(Lab { l: l as f32, a: a as f32, b: b as f32 }); + return Some(Paint::Rgb([r, g, b].map(|v| v.clamp(0.0, 1.0)))); + } + let (h, s, b) = (value(b"H ")?, value(b"Strt")?, value(b"Brgh")?); + Some(Paint::Rgb(hsb(h, unit(s / 100.0), unit(b / 100.0)))) +} + +/// Hue `h` (degrees), saturation `s` and brightness `b` (0..1) as RGB. +fn hsb(h: f64, s: f32, b: f32) -> [f32; 3] { + let h = (h.rem_euclid(360.0) / 60.0) as f32; + let f = |n: f32| { + let k = (n + h) % 6.0; + b - b * s * k.min(4.0 - k).clamp(0.0, 1.0) + }; + [f(5.0), f(3.0), f(1.0)] +} + +/// The layer tree: records in the order the file stores them, bottom first. +enum Item { + Layer(usize), + /// A group's record and its layers. + Group(usize, Vec<Item>), +} + +fn tree(records: &[Record<'_>]) -> Result<Vec<Item>, String> { + let mut stack: Vec<Vec<Item>> = vec![vec![]]; + for (i, rec) in records.iter().enumerate() { + match rec.divider { + 3 => { + if stack.len() > MAX_DEPTH { + return Err("the PSD file's layer groups are nested too deeply".into()); + } + stack.push(vec![]); + } + 1 | 2 => { + // A group without its end divider holds nothing. + let children = if stack.len() > 1 { stack.pop().unwrap_or_default() } else { vec![] }; + if let Some(top) = stack.last_mut() { + top.push(Item::Group(i, children)); + } + } + _ => { + if let Some(top) = stack.last_mut() { + top.push(Item::Layer(i)); + } + } + } + } + // Groups the file never closes: their layers join the group around them. + while stack.len() > 1 { + let inner = stack.pop().unwrap_or_default(); + if let Some(top) = stack.last_mut() { + top.extend(inner); + } + } + Ok(stack.pop().unwrap_or_default()) +} + +/// Straight RGBA, 0..1, at `left`, `top` on the canvas. +#[derive(Clone, Default)] +struct Canvas { + left: i64, + top: i64, + width: usize, + height: usize, + px: Vec<[f32; 4]>, +} + +impl Canvas { + fn from_image(left: i64, top: i64, img: &RgbaImage) -> Self { + let px = img.pixels().map(|p| p.0.map(|v| f32::from(v) / 255.0)).collect(); + Self { left, top, width: img.width() as usize, height: img.height() as usize, px } + } + fn get(&self, x: i64, y: i64) -> Option<[f32; 4]> { + let (x, y) = (usize::try_from(x - self.left).ok()?, usize::try_from(y - self.top).ok()?); + if x >= self.width || y >= self.height { + return None; + } + self.px.get(y * self.width + x).copied() + } + /// The canvas as an image, cropped to its painted pixels; `None` when nothing is painted. + fn to_image(&self) -> Option<(i64, i64, RgbaImage)> { + let painted = |x: usize, y: usize| self.px.get(y * self.width + x).is_some_and(|p| p[3] > 0.0); + let rows: Vec<usize> = (0..self.height).filter(|&y| (0..self.width).any(|x| painted(x, y))).collect(); + let (&y0, &y1) = (rows.first()?, rows.last()?); + let cols: Vec<usize> = (0..self.width).filter(|&x| (y0..=y1).any(|y| painted(x, y))).collect(); + let (&x0, &x1) = (cols.first()?, cols.last()?); + let img = RgbaImage::from_fn((x1 - x0 + 1) as u32, (y1 - y0 + 1) as u32, |x, y| { + let p = self.px.get((y0 + y as usize) * self.width + x0 + x as usize).copied().unwrap_or_default(); + image::Rgba(p.map(byte)) + }); + Some((self.left + x0 as i64, self.top + y0 as i64, img)) + } +} + +/// The blend function of a mode VectorCraft doesn't have, on straight RGB. +fn blend_other(mode: Other, b: [f32; 3], s: [f32; 3]) -> [f32; 3] { + let each = |f: fn(f32, f32) -> f32| [0, 1, 2].map(|i| f(b[i].clamp(0.0, 1.0), s[i].clamp(0.0, 1.0)).clamp(0.0, 1.0)); + // Darker and Lighter Color compare the total of the channel values. + let total = |c: [f32; 3]| c[0] + c[1] + c[2]; + let burn = |b: f32, s: f32| blend_rgb(BlendMode::ColorBurn, [b; 3], [s; 3])[0]; + let dodge = |b: f32, s: f32| blend_rgb(BlendMode::ColorDodge, [b; 3], [s; 3])[0]; + match mode { + // Dissolve's pixels are opaque or transparent (`coverage`); the opaque ones replace. + Other::Dissolve => s, + Other::LinearBurn => each(|b, s| b + s - 1.0), + Other::LinearDodge => each(|b, s| b + s), + Other::VividLight => [0, 1, 2].map(|i| { + let (b, s) = (b[i].clamp(0.0, 1.0), s[i].clamp(0.0, 1.0)); + if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) } + }), + Other::LinearLight => each(|b, s| b + 2.0 * s - 1.0), + Other::PinLight => each(|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) }), + Other::HardMix => each(|b, s| if b + s >= 1.0 { 1.0 } else { 0.0 }), + Other::Subtract => each(|b, s| b - s), + Other::Divide => each(|b, s| if s <= 0.0 { if b <= 0.0 { 0.0 } else { 1.0 } } else { b / s }), + Other::DarkerColor => { + if total(s) < total(b) { + s + } else { + b + } + } + Other::LighterColor => { + if total(s) > total(b) { + s + } else { + b + } + } + } +} + +/// Source-over compositing of straight `s` onto straight `b` in `mode`, as +/// [`vectorcraft_color::blend::composite`] does for the modes it has. +fn over(mode: Blend, b: [f32; 4], s: [f32; 4]) -> [f32; 4] { + let other = match mode { + Blend::Mode(m) => return composite(m, b, s), + Blend::Pass => return composite(BlendMode::Normal, b, s), + Blend::Other(o) => o, + }; + let (ab, a) = (b[3].clamp(0.0, 1.0), s[3].clamp(0.0, 1.0)); + let ao = a + ab * (1.0 - a); + if ao <= 0.0 { + return [0.0; 4]; + } + let mixed = blend_other(other, [b[0], b[1], b[2]], [s[0], s[1], s[2]]); + let c = |i: usize| ((1.0 - ab) * s[i] + ab * mixed[i]) * a + (1.0 - a) * ab * b[i]; + [c(0) / ao, c(1) / ao, c(2) / ao, ao] +} + +/// What one entry of a layer list becomes: a layer of the document. +struct Unit<'i> { + name: String, + visible: bool, + opacity: f32, + blend: Blend, + /// The record whose layer mask the layer takes. + mask_of: Option<usize>, + /// The record the layer comes from (each record has its own Dissolve pattern). + record: usize, + body: Body<'i>, + /// While layers are clipped to it: how its merged canvas is shaped. + clip: Option<Clip>, +} + +impl Unit<'_> { + /// Is it what a merge of layers in modes VectorCraft lacks made: one image, visible, at full + /// opacity in the Normal mode, without a mask? + fn is_merge(&self) -> bool { + matches!(self.body, Body::Merged(_)) + && self.clip.is_none() + && self.mask_of.is_none() + && self.visible + && self.opacity >= 1.0 + && self.blend == Blend::Mode(BlendMode::Normal) + } +} + +/// The shape of a layer merged with the layers clipped to it. +enum Clip { + /// The layer's own transparency at each pixel of its canvas; the canvas holds its pixels at its + /// fill opacity, the clipped layers composited over them. + Shape(Vec<f32>), + /// The whole canvas of the file (a layer that covers it without drawing): the canvas holds the + /// clipped layers alone. + Whole, +} + +enum Body<'i> { + /// A layer record's pixels. + Layer(usize), + /// A group's layers. + Group(&'i [Item]), + /// Layers merged into one image. + Merged(Canvas), +} + +/// A unit's body drawn alone. +enum Drawn { + /// It draws nothing. + Nothing, + Canvas(Canvas), + /// Its canvas would need more memory than allowed. + TooLarge, +} + +/// What the warnings say. +#[derive(Default)] +struct Notes { + types: usize, + adjustments: usize, + fills: usize, + effects: usize, + vector_masks: usize, + knockouts: usize, + /// Hidden layers left out, and layers clipped to them. + hidden: usize, + merged: Vec<&'static str>, + unmerged: usize, + /// Clipped layers left unclipped: the merge needs more memory than allowed. + unclipped: usize, + /// Layers clipped to a fill that isn't drawn. + clipped_out: usize, +} + +/// The counts a merge that can't be made gives back. +#[derive(Clone, Copy)] +struct Counts { + skipped: usize, + merged: usize, + unmerged: usize, + unclipped: usize, + clipped_out: usize, +} + +/// `n` things: "1 layer was", "2 layers were". +fn count(n: usize, one: &str, many: &str) -> String { + if n == 1 { format!("1 {one} was") } else { format!("{n} {many} were") } +} + +impl Notes { + fn warnings(self) -> Vec<String> { + let mut out = vec![]; + if self.types > 0 { + let n = if self.types == 1 { "1 type layer".to_string() } else { format!("{} type layers", self.types) }; + out.push(format!("{n} came in as pixels: the text isn't editable")); + } + if self.adjustments > 0 { + out.push(format!("{} not applied", count(self.adjustments, "adjustment layer", "adjustment layers"))); + } + if self.fills > 0 { + out.push(format!( + "{} not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", + count(self.fills, "fill layer", "fill layers") + )); + } + let layers = |n: usize| if n == 1 { "1 layer".to_string() } else { format!("{n} layers") }; + if self.effects > 0 { + out.push(format!("the layer effects of {} weren't drawn", layers(self.effects))); + } + if self.vector_masks > 0 { + out.push(format!("the vector masks of {} weren't applied", layers(self.vector_masks))); + } + if self.knockouts > 0 { + out.push(format!("the knockout of {} wasn't applied", layers(self.knockouts))); + } + if self.hidden > 0 { + out.push(format!("{} left out (hidden layers and the layers clipped to them)", count(self.hidden, "layer", "layers"))); + } + if self.clipped_out == 1 { + out.push("1 layer clipped to a fill layer that wasn't drawn was left out".into()); + } else if self.clipped_out > 1 { + out.push(format!("{} layers clipped to fill layers that weren't drawn were left out", self.clipped_out)); + } + if !self.merged.is_empty() { + out.push(format!("layers in blend modes VectorCraft doesn't have ({}) were merged with the layers below them", self.merged.join(", "))); + } + if self.unmerged > 0 { + out.push(format!( + "{} in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + layers(self.unmerged) + )); + } + if self.unclipped > 0 { + out.push(format!("{} clipped to the layer below came in unclipped: the merge needs more memory than allowed", layers(self.unclipped))); + } + out + } + + fn counts(&self, skipped: usize) -> Counts { + Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out } + } +} + +struct Builder<'a, F> { + h: &'a Header<'a>, + records: &'a [Record<'a>], + /// Hidden layers come in, hidden. + hidden: bool, + max_alloc: u64, + /// Bytes held by the copies of what is below the pass-through groups being merged. + held: u64, + cmyk: F, + doc: Document, + /// Canvas pixels to points. + to_doc: Affine, + ppi: Option<(f64, f64)>, + layers: usize, + notes: Notes, + /// The records [`Notes`] counted. + noted: Vec<bool>, + /// The records counted as hidden layers left out. + skipped: Vec<bool>, + /// Those records, in the order they were counted. + skip_log: Vec<usize>, + /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. + spent: Cell<u64>, +} + +impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { + fn record(&self, i: usize) -> Result<&Record<'_>, String> { + self.records.get(i).ok_or_else(|| DAMAGED.to_string()) + } + + /// Refuse to allocate `bytes` past the memory allowed. + fn fits(&self, bytes: u64) -> Result<(), String> { + if bytes > self.max_alloc { Err("a layer of the PSD file is too large to read".into()) } else { Ok(()) } + } + + /// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's + /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. + fn spend(&self, bytes: u64) -> Result<(), String> { + let total = self.spent.get().saturating_add(bytes); + self.spent.set(total); + if total > self.max_alloc.saturating_mul(TOTAL_DECODED) { + return Err("the PSD file's layers take more memory to read than allowed".into()); + } + Ok(()) + } + + /// Record `i`'s pixels as straight RGBA, at their place on the canvas; `None` when it has none. + fn image(&self, i: usize) -> Result<Option<(i64, i64, RgbaImage)>, String> { + let rec = self.record(i)?; + let h = self.h; + let max_side = if h.psb { 300_000 } else { 30_000 }; + let (w, rows) = match rec.content { + Content::Adjustment => return Ok(None), + // A fill layer that stores no pixels (a shape layer stores its shape's; one that + // doesn't, with only its vector mask, isn't drawn). + Content::Solid(Some(paint)) if rec.color_over_canvas() => { + let (w, rows) = (h.width as usize, h.height as usize); + self.fits(4 * w as u64 * rows as u64)?; + self.spend(4 * w as u64 * rows as u64)?; + let rgb = match paint { + Paint::Rgb(rgb) => rgb, + Paint::Cmyk(ink) => (self.cmyk)(ink), + }; + let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]); + return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px)))); + } + Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(), + }; + if rec.stores_nothing() { + return Ok(None); + } + if w > max_side || rows > max_side { + return Err(DAMAGED.into()); + } + let colors = h.mode.colors(); + let row = row_bytes(w, h.depth); + self.fits(((colors as u64 + 1) * row as u64).saturating_add(4 * w as u64).saturating_mul(rows as u64))?; + self.spend(4 * w as u64 * rows as u64)?; + let plane = |id: i16| -> Result<Option<Vec<u8>>, String> { + match rec.channels.iter().find(|(c, _)| *c == id) { + Some((_, data)) => layer_channel(data, rows, row, h.psb, h.depth).map(Some), + None => Ok(None), + } + }; + let planes = (0..colors as i16).map(plane).collect::<Result<Vec<_>, _>>()?; + let alpha = plane(-1)?; + let linear = h.depth == 32; + let img = RgbaImage::from_fn(w as u32, rows as u32, |x, y| { + let (x, y) = (x as usize, y as usize); + let at = |p: &Option<Vec<u8>>, linear: bool, missing: f32| { + p.as_ref().and_then(|p| p.get(y * row..(y + 1) * row)).map_or(missing, |r| sample(r, x, h.depth, linear)) + }; + let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk); + image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))]) + }); + Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img))) + } + + /// Record `i`'s layer mask as gray values at their place, with the value outside them; `None` + /// when it has none, or it is disabled and not `even_disabled`. + fn mask(&self, i: usize, even_disabled: bool) -> Result<Option<(i64, i64, image::GrayImage, u8)>, String> { + let rec = self.record(i)?; + let Some(m) = rec.mask.filter(|m| even_disabled || !m.disabled) else { return Ok(None) }; + let Some((_, data)) = rec.channels.iter().find(|(c, _)| *c == -2) else { return Ok(None) }; + let (w, rows) = m.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + if w > max_side || rows > max_side { + return Err(DAMAGED.into()); + } + let row = row_bytes(w, self.h.depth); + self.fits((row as u64 + w as u64).saturating_mul(rows as u64))?; + self.spend(w as u64 * rows as u64)?; + let plane = layer_channel(data, rows, row, self.h.psb, self.h.depth)?; + let read = |v: u8| if m.inverted { 255 - v } else { v }; + let img = image::GrayImage::from_fn(w as u32, rows as u32, |x, y| { + let r = plane.get(y as usize * row..(y as usize + 1) * row).unwrap_or_default(); + image::Luma([read(byte(sample(r, x as usize, self.h.depth, false)))]) + }); + Ok(Some((i64::from(m.bounds.left), i64::from(m.bounds.top), img, read(m.default)))) + } + + /// Multiply `c`'s transparency by record `i`'s layer mask. + fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { + let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; + let (w, h) = (i64::from(m.width()), i64::from(m.height())); + for (k, p) in c.px.iter_mut().enumerate() { + let (x, y) = (c.left + (k % c.width.max(1)) as i64, c.top + (k / c.width.max(1)) as i64); + let inside = (left..left + w).contains(&x) && (top..top + h).contains(&y); + let v = if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { default }; + p[3] *= f32::from(v) / 255.0; + } + Ok(()) + } + + /// What `items` (a layer list, bottom first) become, before the modes VectorCraft lacks are + /// merged: layers clipped to the one below are merged into it, and hidden ones are left out + /// unless `keep_hidden`. Hidden layers a clip would merge are always left out. + fn units<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result<Vec<Unit<'i>>, String> { + let mut out: Vec<Unit<'i>> = vec![]; + // The layer the next clipped layers clip to: its index in `out`, or `None` when it was left + // out (its clipped layers go with it). + let mut base: Option<Option<usize>> = None; + // The next clipped layers come in unclipped: a merge with their base didn't fit. + let mut unclipped = false; + for item in items { + let (i, body) = match item { + Item::Layer(i) => (*i, Body::Layer(*i)), + Item::Group(i, children) => (*i, Body::Group(children)), + }; + let rec = self.record(i)?; + let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend); + let opacity = rec.opacity * rec.fill; + if clipped && let Some(b) = base { + match b { + // Clipped to a layer left out, or hidden itself: left out. + None => self.skip(i), + Some(_) if hidden => self.skip(i), + // A hidden base (with `keep_hidden`) would need the merge: it is left out with + // the layers clipped to it. + Some(b) if out.get(b).is_some_and(|u| !u.visible) => { + if b < out.len() { + let u = out.remove(b); + self.skip(u.record); + } + self.skip(i); + base = Some(None); + } + Some(b) => { + // Counted even when it draws nothing (an adjustment layer). + self.note(i)?; + if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { + continue; + } + // The merge doesn't fit: this layer and the next ones clipped to the same + // base come in as layers of their own. + unclipped = true; + self.notes.unclipped += 1; + out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + } + } + continue; + } + unclipped = false; + if hidden && !keep_hidden { + self.skip(i); + base = Some(None); + continue; + } + self.note(i)?; + out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + base = Some(Some(out.len() - 1)); + } + for u in &mut out { + self.finish_clip(u); + } + Ok(out) + } + + /// Merge the layer of record `i` (`body`, named `name`, drawn alone with its layer mask, at + /// `opacity` in `blend`) into unit `b` of `out`, which it is clipped to. The base's own layer + /// mask stays its opacity mask, which hides the clipped layers with it. `false`, with `out` as + /// it was, when the canvases would need more memory than allowed. + #[allow(clippy::too_many_arguments)] + fn clip(&mut self, out: &mut [Unit<'_>], b: usize, body: &Body<'_>, i: usize, name: &str, blend: Blend, opacity: f32) -> Result<bool, String> { + let Some(u) = out.get(b) else { return Ok(true) }; + let (whole, undrawn, fill, base_opacity) = { + let r = self.record(u.record)?; + let layer = matches!(u.body, Body::Layer(_)); + (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity) + }; + // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. + if undrawn && u.clip.is_none() { + self.notes.clipped_out += 1; + return Ok(true); + } + let layer = match self.draw_body(body, Some(i))? { + Drawn::Nothing => return Ok(true), + Drawn::TooLarge => return Ok(false), + Drawn::Canvas(c) => c, + }; + let room = self.room(); + let layer_bytes = 16 * layer.px.len() as u64; + let Some(u) = out.get_mut(b) else { return Ok(true) }; + if u.clip.is_none() { + let (canvas, clip) = if whole { + (Canvas::default(), Clip::Whole) + } else { + match self.draw_body(&u.body, None)? { + Drawn::TooLarge => return Ok(false), + // A base that draws nothing shows nothing of its clipped layers either. + Drawn::Nothing => (Canvas::default(), Clip::Shape(vec![])), + Drawn::Canvas(mut c) => { + // Its transparency, 4 bytes a pixel, is kept beside the canvas. + if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { + return Ok(false); + } + self.spend(4 * c.px.len() as u64)?; + let shape = c.px.iter().map(|p| p[3]).collect(); + for p in &mut c.px { + p[3] = fill; + } + (c, Clip::Shape(shape)) + } + } + }; + u.body = Body::Merged(canvas); + u.clip = Some(clip); + u.opacity = base_opacity; + } + let Body::Merged(c) = &mut u.body else { return Ok(true) }; + match &u.clip { + Some(Clip::Shape(_)) => { + if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { + return Ok(false); + } + clip_onto(c, &layer, blend, opacity, i); + } + _ => { + let mut acc = (!c.px.is_empty()).then(|| std::mem::take(c)); + let laid = blend_onto(&mut acc, &layer, blend, opacity, i, room, &|n| self.spend(n)); + *c = acc.unwrap_or_default(); + if !laid? { + return Ok(false); + } + } + } + u.name.push_str(" + "); + u.name.push_str(name); + Ok(true) + } + + /// Unit `u`'s merged canvas, once every layer clipped to it is in: transparent outside its + /// shape. + fn finish_clip(&self, u: &mut Unit<'_>) { + let Some(clip) = u.clip.take() else { return }; + let Body::Merged(c) = &mut u.body else { return }; + match clip { + Clip::Shape(shape) => c.px.iter_mut().zip(shape).for_each(|(p, a)| p[3] *= a), + Clip::Whole => { + let (w, h, width) = (i64::from(self.h.width), i64::from(self.h.height), c.width.max(1)); + for (k, p) in c.px.iter_mut().enumerate() { + let (x, y) = (c.left + (k % width) as i64, c.top + (k / width) as i64); + if !(0..w).contains(&x) || !(0..h).contains(&y) { + p[3] = 0.0; + } + } + } + } + } + + /// Count what record `i` holds that doesn't come in. + fn note(&mut self, i: usize) -> Result<(), String> { + // Once, though a merge may draw it again. + match self.noted.get_mut(i) { + Some(true) => return Ok(()), + Some(n) => *n = true, + None => {} + } + let (content, empty, effects, vector_mask, knockout) = { + let rec = self.record(i)?; + (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout) + }; + match content { + Content::Type => self.notes.types += 1, + Content::Adjustment => self.notes.adjustments += 1, + // A fill drawn from neither its pixels nor its color. + Content::Fill | Content::Solid(None) if empty => self.notes.fills += 1, + Content::Solid(Some(_)) if empty && vector_mask => self.notes.fills += 1, + _ => {} + } + self.notes.effects += usize::from(effects); + self.notes.vector_masks += usize::from(vector_mask); + self.notes.knockouts += usize::from(knockout); + Ok(()) + } + + /// Count record `i` as a hidden layer left out (once). + fn skip(&mut self, i: usize) { + if let Some(s) = self.skipped.get_mut(i) + && !*s + { + *s = true; + self.notes.hidden += 1; + self.skip_log.push(i); + } + } + + /// `items`' units with the layers in blend modes VectorCraft lacks merged with those below. + fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result<Vec<Unit<'i>>, String> { + let mut out: Vec<Unit<'i>> = vec![]; + for mut u in self.units(items, keep_hidden)? { + let Blend::Other(other) = u.blend else { + out.push(u); + continue; + }; + // A hidden layer that would need the merge is left out. + if !u.visible { + self.skip(u.record); + continue; + } + // A merge that can't be made counts nothing its groups would have counted. + let saved = self.notes.counts(self.skip_log.len()); + let made = match out.as_mut_slice() { + // Onto the previous merge alone: composited onto its canvas, in place. + [prev] if prev.is_merge() => { + let mut acc = match &mut prev.body { + Body::Merged(c) => Some(std::mem::take(c)), + _ => None, + }; + let made = self.composite(&mut acc, &u); + if let Body::Merged(c) = &mut prev.body { + *c = acc.unwrap_or_default(); + } + if made? { + prev.name.push_str(" + "); + prev.name.push_str(&u.name); + true + } else { + false + } + } + _ => match self.merge(&out, &u)? { + Some(canvas) => { + let mut name = String::new(); + for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() { + if k == 0 { + name = std::mem::take(&mut b.name); + } else { + name.push_str(" + "); + name.push_str(&b.name); + } + } + if out.iter().any(|b| b.visible) { + name.push_str(" + "); + } + name.push_str(&u.name); + // Hidden layers below are left out with the rest. + for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::<Vec<_>>() { + self.skip(b); + } + out.clear(); + out.push(Unit { + name, + visible: true, + opacity: 1.0, + blend: Blend::Mode(BlendMode::Normal), + mask_of: None, + record: u.record, + body: Body::Merged(canvas), + clip: None, + }); + true + } + None => false, + }, + }; + if made { + if !self.notes.merged.contains(&other.label()) { + self.notes.merged.push(other.label()); + } + } else { + self.restore(saved); + self.notes.unmerged += 1; + u.blend = Blend::Mode(BlendMode::Normal); + out.push(u); + } + } + Ok(out) + } + + /// The counts as they were before a merge that couldn't be made. + fn restore(&mut self, c: Counts) { + for i in self.skip_log.split_off(c.skipped) { + if let Some(s) = self.skipped.get_mut(i) { + *s = false; + self.notes.hidden = self.notes.hidden.saturating_sub(1); + } + } + self.notes.merged.truncate(c.merged); + self.notes.unmerged = c.unmerged; + self.notes.unclipped = c.unclipped; + self.notes.clipped_out = c.clipped_out; + } + + /// The visible units `below` with `top` composited over them; `None` when the canvas would need + /// more memory than allowed. + fn merge(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result<Option<Canvas>, String> { + let mut acc: Option<Canvas> = None; + for u in below.iter().filter(|u| u.visible).chain([top]) { + if !self.composite(&mut acc, u)? { + return Ok(None); + } + } + Ok(Some(acc.unwrap_or_default())) + } + + /// The bytes a merge step may still take: the memory allowed, less the copies of what is below + /// the pass-through groups being merged. + fn room(&self) -> u64 { + self.max_alloc.saturating_sub(self.held) + } + + /// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one, + /// so that they blend with what is below it; at less than full opacity or with a layer mask, the + /// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else + /// is drawn alone first. `false` when the canvas would need more memory than allowed. + fn composite(&mut self, acc: &mut Option<Canvas>, u: &Unit<'_>) -> Result<bool, String> { + if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) { + let mask = match u.mask_of { + Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?, + _ => None, + }; + if u.opacity >= 1.0 && mask.is_none() { + return self.lay(acc, items); + } + let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64); + if bytes > self.room() { + return Ok(false); + } + self.spend(bytes)?; + let below = acc.clone(); + self.held = self.held.saturating_add(bytes); + let laid = self.lay(acc, items); + self.held = self.held.saturating_sub(bytes); + if !laid? { + return Ok(false); + } + if let Some(after) = acc.as_mut() { + fade(after, below.as_ref(), u.opacity, mask.as_ref()); + } + return Ok(true); + } + let c = match self.draw_body(&u.body, u.mask_of)? { + Drawn::Nothing => return Ok(true), + Drawn::Canvas(c) => c, + Drawn::TooLarge => return Ok(false), + }; + blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n)) + } + + /// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more + /// memory than allowed. + fn lay(&mut self, acc: &mut Option<Canvas>, items: &[Item]) -> Result<bool, String> { + for c in self.merged(items, false)? { + if !self.composite(acc, &c)? { + return Ok(false); + } + } + Ok(true) + } + + /// Does record `mask_of` have a layer mask that is switched on? + fn has_mask(&self, mask_of: Option<usize>) -> Result<bool, String> { + let Some(i) = mask_of else { return Ok(false) }; + let rec = self.record(i)?; + Ok(rec.mask.is_some_and(|m| !m.disabled) && rec.channels.iter().any(|(c, _)| *c == -2)) + } + + /// A unit's body drawn alone, with the layer mask of record `mask_of`, before its own opacity + /// and blend mode. Its canvas counts against the import's allowance. + fn draw_body(&mut self, body: &Body<'_>, mask_of: Option<usize>) -> Result<Drawn, String> { + let mut c = match body { + Body::Merged(c) => { + let bytes = 16 * c.px.len() as u64; + if bytes > self.room() { + return Ok(Drawn::TooLarge); + } + self.spend(bytes)?; + c.clone() + } + Body::Layer(i) => match self.image(*i)? { + Some((left, top, img)) => { + let bytes = 16 * u64::from(img.width()) * u64::from(img.height()); + if bytes > self.room() { + return Ok(Drawn::TooLarge); + } + self.spend(bytes)?; + Canvas::from_image(left, top, &img) + } + None => return Ok(Drawn::Nothing), + }, + Body::Group(items) => { + let mut acc: Option<Canvas> = None; + if !self.lay(&mut acc, items)? { + return Ok(Drawn::TooLarge); + } + let Some(acc) = acc else { return Ok(Drawn::Nothing) }; + acc + } + }; + if let Some(i) = mask_of { + self.apply_mask(&mut c, i)?; + } + Ok(Drawn::Canvas(c)) + } + + /// A new layer of the document named `name`, colored as the next new layer would be. + fn layer(&mut self, name: &str) -> Node { + let n = Node::layer(self.doc.alloc_id(), name, LayerColor::Preset((self.layers % LAYER_COLORS.len()) as u8)); + self.layers += 1; + n + } + + /// `img` at `left`, `top` on the canvas as an image of the document named `name`. + fn image_node(&mut self, name: &str, left: i64, top: i64, img: RgbaImage) -> Result<Node, String> { + let RasterImage { key, blob, width, height, .. } = as_png(img, None, self.ppi).map_err(|e| e.to_string())?; + let xf = self.to_doc * Affine::translate((left as f64, top as f64)); + let mut n = Node::new( + self.doc.alloc_id(), + NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), + ); + n.name = Some(name.to_string()); + self.doc.images.insert(key, blob); + Ok(n) + } + + /// Layers of the document for `items`, bottom first. + fn list(&mut self, items: &[Item]) -> Result<Vec<Arc<Node>>, String> { + let mut out = vec![]; + for u in self.merged(items, self.hidden)? { + if let Some(n) = self.node(u)? { + out.push(Arc::new(n)); + } + } + Ok(out) + } + + /// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an + /// adjustment layer, or one without pixels). + fn node(&mut self, u: Unit<'_>) -> Result<Option<Node>, String> { + let children = match &u.body { + Body::Layer(i) => match self.image(*i)? { + Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], + None => return Ok(None), + }, + Body::Merged(c) => match c.to_image() { + Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], + None => return Ok(None), + }, + Body::Group(items) => self.list(items)?, + }; + let mut layer = self.layer(&u.name); + layer.visible = u.visible; + layer.opacity = u.opacity.clamp(0.0, 1.0); + (layer.blend, layer.isolate) = match u.blend { + Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))), + Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false), + }; + if let Some(c) = layer.children_mut() { + *c = children; + } + if let Some(i) = u.mask_of { + layer.extras_mut().mask = self.opacity_mask(i)?.map(Box::new); + } + Ok(Some(layer)) + } + + /// Record `i`'s layer mask as an opacity mask: a gray image, outside which the layer is hidden + /// or shown as the mask's default color says (a mask of no pixels hides all of it, or none). + fn opacity_mask(&mut self, i: usize) -> Result<Option<OpacityMask>, String> { + let disabled = self.record(i)?.mask.is_some_and(|m| m.disabled); + let Some((left, top, gray, default)) = self.mask(i, true)? else { return Ok(None) }; + let (art, clip) = if gray.width() == 0 || gray.height() == 0 { + if default == 255 { + return Ok(None); + } + let black = RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 0, 255])); + (self.image_node("Layer Mask", left, top, black)?, true) + } else { + self.fits(5 * u64::from(gray.width()) * u64::from(gray.height()))?; + let rgba = RgbaImage::from_fn(gray.width(), gray.height(), |x, y| { + let v = gray.get_pixel(x, y).0[0]; + image::Rgba([v, v, v, 255]) + }); + (self.image_node("Layer Mask", left, top, rgba)?, default == 0) + }; + let mut mask = OpacityMask::new(art, clip); + mask.disabled = disabled; + Ok(Some(mask)) + } +} + +/// The coverage of a pixel at `x`, `y` of the canvas with `alpha`, 0..1, in `blend`: in Dissolve +/// fully opaque or fully transparent, opaque at a share of the pixels equal to `alpha`, chosen by a +/// fixed hash of the pixel's place and of `record`, so that each layer has its own pattern; `alpha` +/// in every other mode. +fn coverage(blend: Blend, alpha: f32, x: i64, y: i64, record: usize) -> f32 { + if !matches!(blend, Blend::Other(Other::Dissolve)) { + return alpha; + } + let mut h = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) + ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) + ^ (record as u64).wrapping_mul(0x1656_67B1_9E37_79F9); + h ^= h >> 31; + h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9); + h ^= h >> 29; + // The top 24 bits, 0..1. + let r = (h >> 40) as f32 / (1u64 << 24) as f32; + if r < alpha { 1.0 } else { 0.0 } +} + +/// `layer` (of record `record`) composited onto `base`, the canvas of the layer it is clipped to, +/// in `blend` at `opacity`, where the two overlap. +fn clip_onto(base: &mut Canvas, layer: &Canvas, blend: Blend, opacity: f32, record: usize) { + let (x0, x1) = (base.left.max(layer.left), (base.left + base.width as i64).min(layer.left + layer.width as i64)); + let (y0, y1) = (base.top.max(layer.top), (base.top + base.height as i64).min(layer.top + layer.height as i64)); + for y in y0..y1 { + for x in x0..x1 { + let Some(mut s) = layer.get(x, y) else { continue }; + let k = (y - base.top) as usize * base.width + (x - base.left) as usize; + let Some(b) = base.px.get_mut(k) else { continue }; + s[3] = coverage(blend, s[3] * opacity, x, y, record); + *b = over(blend, *b, s); + } + } +} + +/// `after` faded back toward `before` (transparent where it has no pixels) by `opacity` times the +/// value of `mask` (its place, its gray values and the value outside it) at each pixel, in +/// premultiplied color. +fn fade(after: &mut Canvas, before: Option<&Canvas>, opacity: f32, mask: Option<&(i64, i64, image::GrayImage, u8)>) { + let width = after.width.max(1); + for (k, p) in after.px.iter_mut().enumerate() { + let (x, y) = (after.left + (k % width) as i64, after.top + (k / width) as i64); + let m = mask.map_or(255, |(left, top, m, default)| { + let inside = (*left..*left + i64::from(m.width())).contains(&x) && (*top..*top + i64::from(m.height())).contains(&y); + if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { *default } + }); + let t = opacity * f32::from(m) / 255.0; + let b = before.and_then(|c| c.get(x, y)).unwrap_or([0.0; 4]); + let alpha = (1.0 - t) * b[3] + t * p[3]; + if alpha <= 0.0 { + *p = [0.0; 4]; + continue; + } + let mix = |i: usize| ((1.0 - t) * b[3] * b[i] + t * p[3] * p[i]) / alpha; + *p = [mix(0), mix(1), mix(2), alpha]; + } +} + +/// `src` (of record `record`) at `opacity` composited onto `acc` (nothing when `None`) in `blend`, +/// on a canvas covering both (`acc` itself when it covers `src`; a larger one is counted with +/// `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a larger +/// canvas when one is needed, would take more than `max_alloc` bytes. +fn blend_onto( + acc: &mut Option<Canvas>, + src: &Canvas, + blend: Blend, + opacity: f32, + record: usize, + max_alloc: u64, + spend: &dyn Fn(u64) -> Result<(), String>, +) -> Result<bool, String> { + let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64); + if let Some(a) = acc.as_ref() { + left = left.min(a.left); + top = top.min(a.top); + right = right.max(a.left + a.width as i64); + bottom = bottom.max(a.top + a.height as i64); + } + let (Ok(width), Ok(height)) = (usize::try_from(right - left), usize::try_from(bottom - top)) else { return Ok(false) }; + let held = (src.px.len() as u64).saturating_add(acc.as_ref().map_or(0, |a| a.px.len() as u64)); + let covers = acc.as_ref().is_some_and(|a| (a.left, a.top, a.width, a.height) == (left, top, width, height)); + if covers { + if held.saturating_mul(16) > max_alloc { + return Ok(false); + } + } else { + let bytes = (width as u64).saturating_mul(height as u64).saturating_mul(16); + if bytes.saturating_add(held.saturating_mul(16)) > max_alloc { + return Ok(false); + } + spend(bytes)?; + let mut out = Canvas { left, top, width, height, px: vec![[0.0; 4]; width * height] }; + if let Some(a) = acc.take() { + for (y, row) in a.px.chunks(a.width.max(1)).enumerate() { + let at = (a.top - top) as usize + y; + let start = at * width + (a.left - left) as usize; + if let Some(dst) = out.px.get_mut(start..start + row.len()) { + dst.copy_from_slice(row); + } + } + } + *acc = Some(out); + } + let Some(out) = acc.as_mut() else { return Ok(false) }; + // Only the source's rows and columns change. + let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize); + for (k, s) in src.px.iter().enumerate() { + let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue }; + let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record); + *p = over(blend, *p, [s[0], s[1], s[2], a]); + } + Ok(true) +} + +/// PSD or PSB file `bytes` with its layers as layers of the document (see the module +/// documentation), with warnings for what doesn't come in. `None` when the file has no layers (its +/// merged image is all of it). CMYK converts through `cmyk` (ink amounts 0..1 → sRGB). +pub(super) fn import( + bytes: &[u8], + hidden: bool, + max_alloc: u64, + cmyk: impl Fn([f32; 4]) -> [f32; 3], +) -> Result<Option<(Document, Vec<String>)>, String> { + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + // Layer info that holds only the count (which says whether the merged image has transparency) + // has no layers either. + let Some(info) = layer_info(h.layers, h.psb).filter(|info| info.len() > 2) else { return Ok(None) }; + let records = records(info, h.psb)?; + if records.is_empty() { + return Ok(None); + } + let items = tree(&records)?; + let ppi = super::ppi::resolution(bytes).filter(|(x, y)| x.is_finite() && y.is_finite() && *x > 0.0 && *y > 0.0); + let (sx, sy) = crate::cmd::place::pt_per_px(ppi); + let doc = Document::new(f64::from(h.width) * sx, f64::from(h.height) * sy); + let mut b = Builder { + h: &h, + records: &records, + hidden, + max_alloc, + held: 0, + cmyk, + doc, + to_doc: Affine::scale_non_uniform(sx, sy), + ppi, + layers: 0, + notes: Notes::default(), + noted: vec![false; records.len()], + skipped: vec![false; records.len()], + skip_log: vec![], + spent: Cell::new(0), + }; + let layers = b.list(&items)?; + let Builder { mut doc, notes, .. } = b; + if !layers.is_empty() { + doc.layers = layers; + } + // Groups nest up to `MAX_DEPTH`, deeper than a document may: what is too deep merges into + // the group around it, with a warning. + let mut warnings = notes.warnings(); + doc.limit_depth_noting(&mut warnings); + Ok(Some((doc, warnings))) +} diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 84ac8203aa..93e7b61f17 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -1,7 +1,8 @@ //! Reading Photoshop documents (PSD, and PSB, the large document format) for File › Open and //! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers, //! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification" -//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Layers aren't read. +//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). File › Open reads the +//! layers with [`super::psdlayers`], which shares this reader. //! //! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its //! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw, @@ -16,7 +17,7 @@ use vectorcraft_color::cms::{Lab, lab::lab_to_srgb}; /// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Mode { +pub(super) enum Mode { Bitmap, Gray, Indexed, @@ -27,7 +28,7 @@ enum Mode { impl Mode { /// The channels holding colour (an alpha channel may follow them). - fn colors(self) -> usize { + pub(super) fn colors(self) -> usize { match self { Mode::Bitmap | Mode::Gray | Mode::Indexed => 1, Mode::Rgb | Mode::Lab => 3, @@ -46,68 +47,68 @@ pub fn is_psb(bytes: &[u8]) -> bool { is_psd(bytes) && bytes.get(4..6) == Some(&[0, 2]) } -const TRUNCATED: &str = "the PSD file is cut short"; +pub(super) const TRUNCATED: &str = "the PSD file is cut short"; const DAMAGED: &str = "the PSD file's header is damaged"; /// Big-endian reads through `b`, each checked against its end. -struct Reader<'a> { +pub(super) struct Reader<'a> { b: &'a [u8], at: usize, } impl<'a> Reader<'a> { - fn new(b: &'a [u8]) -> Self { + pub(super) fn new(b: &'a [u8]) -> Self { Self { b, at: 0 } } - fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + pub(super) fn take(&mut self, n: usize) -> Result<&'a [u8], String> { let s = self.at.checked_add(n).and_then(|end| self.b.get(self.at..end)).ok_or(TRUNCATED)?; self.at += n; Ok(s) } - fn array<const N: usize>(&mut self) -> Result<[u8; N], String> { + pub(super) fn array<const N: usize>(&mut self) -> Result<[u8; N], String> { self.take(N)?.try_into().map_err(|_| TRUNCATED.to_string()) } - fn u8(&mut self) -> Result<u8, String> { + pub(super) fn u8(&mut self) -> Result<u8, String> { self.array::<1>().map(|[v]| v) } - fn u16(&mut self) -> Result<u16, String> { + pub(super) fn u16(&mut self) -> Result<u16, String> { self.array().map(u16::from_be_bytes) } - fn u32(&mut self) -> Result<u32, String> { + pub(super) fn u32(&mut self) -> Result<u32, String> { self.array().map(u32::from_be_bytes) } /// A section length: 4 bytes in a PSD, 8 in a PSB. - fn length(&mut self, psb: bool) -> Result<usize, String> { + pub(super) fn length(&mut self, psb: bool) -> Result<usize, String> { let n = if psb { self.array().map(u64::from_be_bytes)? } else { u64::from(self.u32()?) }; usize::try_from(n).map_err(|_| TRUNCATED.to_string()) } /// A section: its length, then that many bytes. - fn section(&mut self, psb: bool) -> Result<&'a [u8], String> { + pub(super) fn section(&mut self, psb: bool) -> Result<&'a [u8], String> { let n = self.length(psb)?; self.take(n) } - fn rest(&self) -> &'a [u8] { + pub(super) fn rest(&self) -> &'a [u8] { self.b.get(self.at..).unwrap_or_default() } } /// The fixed-size header and the sections before the image data. -struct Header<'a> { - psb: bool, +pub(super) struct Header<'a> { + pub(super) psb: bool, channels: usize, - width: u32, - height: u32, - depth: u16, - mode: Mode, + pub(super) width: u32, + pub(super) height: u32, + pub(super) depth: u16, + pub(super) mode: Mode, /// Colour mode data: an indexed image's palette (256 reds, then greens, then blues). palette: &'a [u8], /// The image resources. resources: &'a [u8], /// The layer and mask information. - layers: &'a [u8], + pub(super) layers: &'a [u8], } -fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> { +pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> { if !is_psd(r.b) { return Err("not a PSD file".into()); } @@ -183,41 +184,45 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// count is negative: in the layer info, or for 16- and 32-bit documents (whose layer info is /// empty) in their `Lr16` / `Lr32` block. fn merged_alpha(layers: &[u8], psb: bool) -> bool { - let count_negative = |info: &[u8]| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0); + layer_info(layers, psb).is_some_and(|info| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0)) +} + +/// Do tagged blocks with this key give an 8-byte length in a PSB? +pub(super) fn long_key(key: &[u8; 4]) -> bool { + matches!(key, b"Lr16" | b"Lr32" | b"Layr" | b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD") +} + +/// The layer info: the layer count, the layer records and their channels. It is the first part of +/// the layer and mask information, or for 16- and 32-bit documents (whose first part is empty) the +/// `Lr16` / `Lr32` block after it. `None` when the file has neither. +pub(super) fn layer_info(layers: &[u8], psb: bool) -> Option<&[u8]> { let mut r = Reader::new(layers); - let Ok(info) = r.section(psb) else { return false }; + let info = r.section(psb).ok()?; if !info.is_empty() { - return count_negative(info); + return Some(info); } // The global layer mask info, then tagged blocks: signature, key, length (8 bytes for the // layer blocks of a PSB), data padded to 4 bytes. - if r.section(false).is_err() { - return false; - } + r.section(false).ok()?; while r.rest().len() >= 12 { - let (Ok(_), Ok(key)) = (r.take(4), r.array::<4>()) else { return false }; - let layer_block = matches!(&key, b"Lr16" | b"Lr32" | b"Layr"); - let long = layer_block || matches!(&key, b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD"); - let Ok(data) = r.section(psb && long) else { - return false; - }; - if layer_block { - return count_negative(data); - } - if r.take((4 - data.len() % 4) % 4).is_err() { - return false; + r.take(4).ok()?; + let key = r.array::<4>().ok()?; + let data = r.section(psb && long_key(&key)).ok()?; + if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { + return Some(data); } + r.take((4 - data.len() % 4) % 4).ok()?; } - false + None } /// The most bytes one channel row may take (a PSB at 32 bits). -fn row_bytes(width: usize, depth: u16) -> usize { +pub(super) fn row_bytes(width: usize, depth: u16) -> usize { if depth == 1 { width.div_ceil(8) } else { width * usize::from(depth / 8) } } /// Undo PackBits: `src` into `dst` (a row; a short or overlong run leaves the rest as it is). -fn unpack_bits(mut src: &[u8], dst: &mut [u8]) { +pub(super) fn unpack_bits(mut src: &[u8], dst: &mut [u8]) { let mut at = 0; while let Some((&n, rest)) = src.split_first() { src = rest; @@ -269,32 +274,77 @@ fn channel_data(data: &[u8], h: &Header<'_>, channels: usize, row: usize) -> Res } Ok(out) } - 2 | 3 => { - let mut out = Vec::new(); - flate2::read::ZlibDecoder::new(r.rest()) - .take(wanted as u64) - .read_to_end(&mut out) - .map_err(|e| format!("the PSD file's image data can't be read: {e}"))?; - if out.len() < wanted { - return Err(TRUNCATED.into()); - } - if method == 3 { - // Each row stores the difference from the sample before it. - match h.depth { - 8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))), - 16 => out.chunks_exact_mut(row).for_each(|r| { - let mut prev = 0u16; - for s in r.as_chunks_mut::<2>().0 { - prev = prev.wrapping_add(u16::from_be_bytes(*s)); - *s = prev.to_be_bytes(); - } - }), - _ => return Err("zipped 32-bit PSD image data with prediction can't be read".into()), + 2 | 3 => inflate(r.rest(), wanted, method == 3, h.depth, row), + m => Err(format!("the PSD file's image data uses an unknown compression ({m})")), + } +} + +/// `wanted` bytes of zipped image data, rows of `row` bytes; with `predicted`, each row stores the +/// difference from the sample before it. In 32-bit data a row stores the first bytes of its samples, +/// then their second bytes, and so on, and the differences run byte by byte along the whole row (as +/// psd-tools, MIT, reads it: <https://github.com/psd-tools/psd-tools>, `compression/__init__.py`). +fn inflate(src: &[u8], wanted: usize, predicted: bool, depth: u16, row: usize) -> Result<Vec<u8>, String> { + let mut out = Vec::new(); + flate2::read::ZlibDecoder::new(src) + .take(wanted as u64) + .read_to_end(&mut out) + .map_err(|e| format!("the PSD file's image data can't be read: {e}"))?; + if out.len() < wanted { + return Err(TRUNCATED.into()); + } + if predicted && row > 0 { + match depth { + 8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))), + 16 => out.chunks_exact_mut(row).for_each(|r| { + let mut prev = 0u16; + for s in r.as_chunks_mut::<2>().0 { + prev = prev.wrapping_add(u16::from_be_bytes(*s)); + *s = prev.to_be_bytes(); } + }), + 32 => { + let w = row / 4; + let mut planes = vec![0u8; row]; + for r in out.chunks_exact_mut(row) { + let mut prev = 0u8; + for (dst, &b) in planes.iter_mut().zip(r.iter()) { + prev = prev.wrapping_add(b); + *dst = prev; + } + for (x, s) in r.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (k, v) in s.iter_mut().enumerate() { + *v = planes.get(k * w + x).copied().unwrap_or(0); + } + } + } + } + // 1-bit. + _ => return Err("zipped 1-bit PSD image data with prediction can't be read".into()), + } + } + Ok(out) +} + +/// One channel of a layer: its compression method, then `rows` rows of `row` bytes (PackBits rows +/// after their byte counts, 4 bytes each in a PSB). +pub(super) fn layer_channel(data: &[u8], rows: usize, row: usize, psb: bool, depth: u16) -> Result<Vec<u8>, String> { + let mut r = Reader::new(data); + let method = r.u16()?; + let wanted = rows.checked_mul(row).ok_or(TRUNCATED)?; + match method { + 0 => r.take(wanted).map(<[u8]>::to_vec), + 1 => { + let size = if psb { 4 } else { 2 }; + let counts = r.take(rows.checked_mul(size).ok_or(TRUNCATED)?)?; + let mut out = vec![0; wanted]; + for (dst, n) in out.chunks_exact_mut(row.max(1)).zip(counts.chunks_exact(size)) { + let n = n.iter().fold(0usize, |n, &b| n << 8 | usize::from(b)); + unpack_bits(r.take(n)?, dst); } Ok(out) } - m => Err(format!("the PSD file's image data uses an unknown compression ({m})")), + 2 | 3 => inflate(r.rest(), wanted, method == 3, depth, row), + m => Err(format!("the PSD file's layer data uses an unknown compression ({m})")), } } @@ -304,7 +354,7 @@ fn srgb_encode(v: f32) -> f32 { } /// Sample `x` of a channel row, 0..1. -fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 { +pub(super) fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 { match depth { 1 => { // Bitmap: a set bit is black. @@ -321,10 +371,25 @@ fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 { } } -fn byte(v: f32) -> u8 { +pub(super) fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } +/// The sRGB color of a pixel whose color channels `v` gives (0..1, as stored), in `h`'s mode. +pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f32; 4]) -> [f32; 3]) -> [f32; 3] { + match h.mode { + Mode::Bitmap | Mode::Gray => [v(0); 3], + Mode::Indexed => { + let i = usize::from(byte(v(0))); + [0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0)) + } + Mode::Rgb => [v(0), v(1), v(2)], + // Inks are stored as 1 − amount. + Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))), + Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }), + } +} + /// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink /// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than /// `max_alloc` bytes. @@ -348,17 +413,7 @@ pub fn decode(bytes: &[u8], max_alloc: u64, cmyk: impl Fn([f32; 4]) -> [f32; 3]) let planes: Vec<&[u8]> = (0..channels).map(|c| data.get((c * rows + y) * row..(c * rows + y + 1) * row).unwrap_or_default()).collect(); for (x, px) in line.enumerate() { let v = |c: usize| planes.get(c).map_or(0.0, |p| sample(p, x, h.depth, linear && c < colors)); - let rgb = match h.mode { - Mode::Bitmap | Mode::Gray => [v(0); 3], - Mode::Indexed => { - let i = usize::from(byte(v(0))); - [0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0)) - } - Mode::Rgb => [v(0), v(1), v(2)], - // Inks are stored as 1 − amount. - Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))), - Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }), - }; + let rgb = to_rgb(&h, v, &cmyk); let a = if alpha { v(colors) } else { 1.0 }; // The merged image is stored on white: take the white back out. let straight = |c: f32| if a <= 0.0 { 0.0 } else { (c - (1.0 - a)) / a }; diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 9f4e5b0572..5d7783665b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -731,7 +731,7 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res // With the artboards' background colors, as the pages draw them. let art = super::export::with_artboard_fills(art, ¶ms, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?; let o = vectorcraft_eps::AiEditingOptions { - title: doc.title.clone(), + title: doc.info_title().to_owned(), created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time), }; let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?; @@ -870,8 +870,10 @@ impl SaveJob { _ => encode_all(doc, f.id, &self.params), } .map_err(|e| named_for_save(cmd, e))?; - // A legacy .ai file per artboard. - let per_artboard = f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?; + // A legacy .ai file per artboard, or the files the EPS encoder writes: one, or with Use + // Artboards and two or more artboards the central file at the path and a file per + // artboard beside it. + let per_artboard = f.id == "eps" || (f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?); if enc.files.len() != 1 && !per_artboard { return Err(bad(cmd, "Save writes one artboard: name one, or export several with document.export")); } @@ -883,7 +885,13 @@ impl SaveJob { /// folder?, warnings, files?: [{name, dataBase64}] (every file, when there are several), /// linked?: [{name, dataBase64}]}`; with one → `{path, format, bytes, warnings, files?: /// [path…], linked?: [path…]}`. - pub fn write(&self, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { + pub fn write(&self, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { + self.write_unless(|_| None, write) + } + + /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in + /// order: when `stop` returns a value, nothing is written and that value is returned. + pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> { let (plan, doc) = (&self.plan, &*self.doc); let mut enc = self.encode()?; let warnings = std::mem::take(&mut enc.warnings); @@ -897,6 +905,9 @@ impl SaveJob { return Ok(out); }; let files = enc.named(doc, path); + if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) { + return Ok(stopped); + } for (p, bytes) in &files { write(p, bytes)?; } @@ -1032,11 +1043,47 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> let plan = save_plan(s, mode, p)?; let job = save_job(s, plan)?; let uid = s.doc()?.uid; - let out = job.write_streamed(&mut super::write_file_with)?; + let mut out = job.write_streamed(&mut super::write_file_with)?; job.complete(s, uid); + leave_out_unreadable_save_paths(&mut out, str_param(p, "path")); Ok(out) } +/// The reply `out` of a save with the `path` param `given`, as the request being served may see it +/// ([`super::access::shown`]). A save without a path writes the document's own file: its `path` is +/// left out, and the `files` and `linked` written beside it are named by their file names, when they +/// are outside the read roots. The suggested `folder` of a reply without a path is left out when it +/// is outside them. Without roots in force `out` is unchanged. +pub fn leave_out_unreadable_save_paths(out: &mut Value, given: Option<&str>) { + use super::access::{shown, shown_path}; + + if crate::file_access::current().is_none() { + return; + } + let Some(o) = out.as_object_mut() else { return }; + if o.get("folder").and_then(Value::as_str).is_some_and(|f| !shown(f)) { + o.remove("folder"); + } + // Every path the reply names then is the one the client gave, or beside it. + if given.is_some_and(|g| !g.is_empty()) { + return; + } + if o.get("path").and_then(Value::as_str).is_some_and(|p| !shown(p)) { + o.remove("path"); + } + for key in ["files", "linked"] { + if let Some(Value::Array(rows)) = o.get_mut(key) { + for row in rows { + if let Value::String(p) = row + && !shown(p) + { + *row = json!(shown_path(p)); + } + } + } + } +} + fn can_revert(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; match (&st.path, st.is_dirty()) { @@ -1092,6 +1139,25 @@ fn format_options(s: &mut Session, p: &Value) -> Result<Value> { } } } + // An EPS save that named artboards without Use Artboards, or with it on, had it on (the + // encoder reads them so): it shows on, with those artboards as the range. + if f.id == "eps" + && let Some(m) = &saved + && m.get("useArtboards").and_then(Value::as_bool) != Some(false) + { + let range = m.get("range").and_then(Value::as_str).filter(|r| !r.trim().is_empty()); + let boards = m + .get("artboards") + .and_then(|a| serde_json::from_value::<Vec<usize>>(a.clone()).ok()) + .or_else(|| m.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).map(|i| vec![i])) + .filter(|b| !b.is_empty()); + if range.is_some() || boards.is_some() { + v["options"]["useArtboards"]["value"] = json!(true); + if let (None, Some(boards)) = (range, boards) { + v["options"]["range"]["value"] = json!(range_text(&boards)); + } + } + } v["saveFormats"] = SAVE_FORMATS.iter().filter_map(|id| format(id)).map(|f| json!({"id": f.id, "label": f.label, "extensions": f.extensions})).collect(); Ok(v) @@ -1104,7 +1170,7 @@ pub(super) fn specs() -> Vec<CommandSpec> { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused", has_doc, |s, p| save(s, SaveMode::Save, p) ), @@ -1158,7 +1224,7 @@ pub(super) fn specs() -> Vec<CommandSpec> { "Format Options", [], None, - "{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default", + "{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default (EPS: useArtboards is true when the last save named artboards without it, and range then names them)", always, format_options ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 56c0d808a5..b48aef68c3 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String { pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"]; /// The writable formats a format row can't name. -pub(crate) const UNWRITTEN_FORMATS: [&str; 5] = ["template", "txt", "dxf", "emf", "wmf"]; +pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"]; /// One format row: what to write, at which size, with which suffix, into which sub-folder. struct Row { @@ -644,12 +644,86 @@ impl Output { /// File → Export for Screens: [`export`] (over the settings of `exportPreset`, when given), with /// the params remembered in the document (`document.exportSettings`). pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> { + // A folder the client gave, as against the one its `exportPreset` keeps. + let given = p.get("folder").is_some(); let p = with_preset(s, p)?; - let r = export(s, &p)?; + let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) }; + let mut r = export(s, &p).map_err(|e| match hidden { + Some(folder) => leave_out_folder_from_error(e, folder), + None => e, + })?; remember(s, &p); + if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) { + leave_out_unreadable_folder(&mut r, folder); + } Ok(r) } +/// An error of an export into `folder`, a folder outside the read roots that the client did not +/// give: `folder` as the path the error is about names it by its own name +/// ([`super::access::shown_path`]), and the rest of the message stays. +fn leave_out_folder_from_error(e: EngineError, folder: &str) -> EngineError { + let name = super::access::shown_path(folder); + match e { + EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, &name)), + EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, &name) }, + e => e, + } +} + +/// `msg` with `folder` given as `name` where it begins a path the message is about: at the start +/// of `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or +/// after `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message +/// names stays whole, even one inside `folder`. +fn leave_out_folder_from_message(msg: &str, folder: &str, name: &str) -> String { + const BEFORE: [&str; 2] = [": ", "cannot resolve "]; + let mut out = String::with_capacity(msg.len()); + let mut rest = msg; + loop { + if let Some(after) = rest.strip_prefix(folder) + && after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' ')) + { + out.push_str(name); + rest = after; + } + let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break }; + out.push_str(&rest[..i + len]); + rest = &rest[i + len..]; + } + out.push_str(rest); + out +} + +/// The reply `r` of an export into `folder`, a folder the client did not give, as the request being +/// served may see it: when `folder` is outside the read roots ([`super::access::shown`]), the ZIP's +/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`), +/// as the reply of an export to a ZIP names them. +fn leave_out_unreadable_folder(r: &mut Value, folder: &str) { + if super::access::shown(folder) { + return; + } + let Some(o) = r.as_object_mut() else { return }; + o.remove("path"); + let inside = format!("{folder}/"); + if let Some(Value::Array(files)) = o.get_mut("files") { + for file in files { + // A ZIP's files are named relative to it already. + if let Some(name) = file.as_str().and_then(|path| path.strip_prefix(&inside)) { + *file = json!(name); + } + } + } +} + +/// Export settings kept in the document or a preset, as the request being served may see them: a +/// `folder` outside the read roots ([`super::access::shown`]) is left out. +fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> { + if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) { + settings.remove("folder"); + } + settings +} + // ---------- export presets ---------- /// A saved batch export: what to write and how to name and sort it, to use again @@ -727,7 +801,13 @@ pub fn preset_list(saved: &[ScreenExportPreset]) -> Value { } pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> { - Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) })) + let saved: Vec<ScreenExportPreset> = s + .prefs + .screen_export_presets + .iter() + .map(|p| ScreenExportPreset { name: p.name.clone(), settings: leave_out_unreadable_settings_folder(p.settings.clone()) }) + .collect(); + Ok(json!({ "presets": preset_list(&saved) })) } /// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would @@ -831,6 +911,8 @@ pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> { return Err(too_many()); } let count = presets.len(); + let presets: Vec<ScreenExportPreset> = + presets.into_iter().map(|p| ScreenExportPreset { settings: leave_out_unreadable_settings_folder(p.settings), ..p }).collect(); let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?; if text.len() > MAX_PRESET_FILE_BYTES { return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes"))); @@ -1388,12 +1470,31 @@ pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>) /// `document.exportSettings`: the Export for Screens settings the document last exported with. pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> { - Ok(json!({ "settings": s.doc()?.doc.export_settings })) + Ok(json!({ "settings": leave_out_unreadable_settings_folder(s.doc()?.doc.export_settings.clone()) })) } #[cfg(test)] mod tests { - use super::{Output, ScreenSize, safe_file_name}; + use super::{Output, ScreenSize, leave_out_folder_from_message, safe_file_name}; + + /// A hidden export folder is named by its name where a message is about it, and a root that + /// starts with the same text, or a longer path, stays whole. + #[test] + fn a_hidden_folder_is_named_by_its_name_in_a_message() { + let f = "/work/out"; + let cases = [ + ( + "automation path rejected: outside the write root /work/out/in: /work/out", + "automation path rejected: outside the write root /work/out/in: out", + ), + ("automation path rejected: cannot resolve /work/out: denied", "automation path rejected: cannot resolve out: denied"), + ("/work/out/2x/a.png: disk full", "out/2x/a.png: disk full"), + ("automation path rejected: outside the write root /a: /work/outer", "automation path rejected: outside the write root /a: /work/outer"), + ]; + for (msg, want) in cases { + assert_eq!(leave_out_folder_from_message(msg, f, "out"), want, "{msg}"); + } + } /// Files given one name are numbered in turn, each numbering going on from the last one (so /// thousands of them don't each try every number used before), and a file asking again for diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 6236d281e2..c90e077eb4 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -48,6 +48,19 @@ fn image_of(s: &Session) -> vectorcraft_doc::ImageObject { } } +/// A path outside a confined request's read roots shows as its file name, after the last `/` or `\` +/// on every platform; one that ends in no name shows as nothing. Without roots it shows whole. +#[test] +fn a_hidden_path_shows_as_its_file_name_on_every_platform() { + let windows = "C:\\Users\\someone\\art\\red.png"; + crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || { + for (path, name) in [("/home/someone/art/red.png", "red.png"), (windows, "red.png"), ("/home/someone/..", ""), ("C:\\Users\\someone\\", "")] { + assert_eq!(shown_path(path), name, "{path}"); + } + }); + assert_eq!(shown_path(windows), windows); +} + #[test] fn opens_every_readable_format() { let mut s = session(200.0, 100.0, 1); @@ -418,6 +431,7 @@ fn export_extensions_name_every_writable_format() { "eps", "emf", "wmf", + "plt", "tga", "psd" ] @@ -453,6 +467,7 @@ fn formats_query_lists_readers_writers_and_options() { "eps", "emf", "wmf", + "hpgl", "tga", "psd" ] diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index 05ca07019f..d5f5149bab 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -267,6 +267,66 @@ mod native { synth::container(&[("doc.dat", &doc, method)], Some(&png())) } + /// A version-12 document at 144 ppi holding a 100 px square filled with a red-to-blue conical + /// gradient centered at (50, 40) px, 40 px across: its unit +y points down the page, or up + /// (`mirror`). + fn conical_document(mirror: bool) -> Vec<u8> { + let stop = |id: u32, c: F| F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), c)]); + let positions = [[0.0f32, 0.5], [1.0, 0.5]].iter().map(|p| p.iter().flat_map(|v| v.to_le_bytes()).collect()).collect(); + let grad = F::Obj( + tag(b"Grad"), + vec![ + (tag(b"Cols"), F::Shared(vec![stop(23, rgba(1.0, 0.0, 0.0, 1.0)), stop(24, rgba(0.0, 0.0, 1.0, 1.0))])), + (tag(b"Posn"), F::Records(8, positions)), + ], + ); + let fill = F::Def(22, vec![tag(b"FilG")], vec![(tag(b"Type"), F::Enum(3, 0)), (tag(b"Grad"), grad)]); + let unit = F::F64s(vec![40.0, 0.0, 50.0, 0.0, if mirror { -40.0 } else { 40.0 }, 40.0]); + let gradient = F::Def(21, vec![tag(b"FDsc")], vec![(tag(b"FDeX"), unit), (tag(b"FDeF"), fill)]); + let square = F::Def( + 20, + vec![tag(b"ShpN")], + vec![ + (tag(b"Shpe"), F::Def(25, vec![tag(b"ShNR")], vec![])), + (tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 100.0, 100.0])), + (tag(b"BFFl"), F::Shared(vec![gradient])), + ], + ); + let spread = + F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 200.0])), (tag(b"Chld"), F::Shared(vec![square]))]); + let doc = synth::stream(&[ + (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(144.0))])), + (tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])), + ]); + synth::container(&[("doc.dat", &doc, Method::Stored)], Some(&png())) + } + + #[test] + fn conical_gradients_open_as_conic_gradients() { + use vectorcraft_color::{GradientKind, Paint}; + for mirror in [false, true] { + let mut s = Session::new(); + let r = open_bytes(&mut s, "conic.af", &conical_document(mirror), None).unwrap(); + assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("conical")), "{r}"); + let mut paint = None; + s.doc().unwrap().doc.walk(|n| { + if let Paint::Gradient(g) = n.appearance.fill_paint() { + paint = Some(g.clone()); + } + }); + let g = paint.expect("a gradient fill"); + assert_eq!(g.gradient.kind, GradientKind::Conic); + let geom = g.geom.unwrap(); + // At 144 ppi: centered at (25, 20) pt, 20 pt across, red where the sweep starts. + assert!(geom.start.distance(kurbo::Point::new(25.0, 20.0)) < 1e-9 && (geom.length() - 20.0).abs() < 1e-9, "{geom:?}"); + assert_eq!(geom.is_mirrored(), mirror, "{geom:?}"); + // A quarter turn on lies along the unit +y: below the center, or above it mirrored. + let quarter = kurbo::Point::new(25.0, if mirror { 10.0 } else { 30.0 }); + assert!((geom.param_at(GradientKind::Conic, quarter) - 0.25).abs() < 1e-9, "{geom:?}"); + assert_eq!(g.gradient.stops[0].color.to_hex(), "#ff0000"); + } + } + #[test] fn layers_artboards_curves_and_paints_open_as_editable_art() { for method in [Method::Stored, Method::Zlib, Method::Zstd] { diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs index 9a7684686a..371cdc05ab 100644 --- a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -109,23 +109,25 @@ fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() { } } +/// Does PostScript `t` paint the only red the document has, the first artboard's color? RGB, or +/// CMYK PostScript's (its values depend on the color conversion the platform offers, so only its +/// hue is checked). +fn red(t: &str) -> bool { + t.lines().any(|l| { + let mut w: Vec<&str> = l.split_whitespace().collect(); + let Some(op) = w.pop() else { return false }; + let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect(); + match (op, v.as_slice()) { + ("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1, + ("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1, + _ => false, + } + }) +} + #[test] fn eps_and_postscript_print_draw_the_color() { let mut s = session(); - // The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its - // values depend on the color conversion the platform offers, so only its hue is checked). - let red = |t: &str| { - t.lines().any(|l| { - let mut w: Vec<&str> = l.split_whitespace().collect(); - let Some(op) = w.pop() else { return false }; - let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect(); - match (op, v.as_slice()) { - ("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1, - ("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1, - _ => false, - } - }) - }; let eps = |s: &mut Session, more: Value| { String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned() }; @@ -138,6 +140,22 @@ fn eps_and_postscript_print_draw_the_color() { assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it"); } +/// EPS Save draws the color on an artboard's page: with Use Artboards, or on the first artboard +/// when no art shows. The box of the visible art, as Export's, has none. +#[test] +fn eps_save_draws_the_color_on_an_artboard_page() { + let mut s = session(); + let save = |s: &mut Session, more: Value| { + let options = with(json!({"previewFormat": "none", "thumbnails": false}), &more); + String::from_utf8_lossy(&b64(&s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap())).into_owned() + }; + assert!(!red(&save(&mut s, json!({}))), "the art's box"); + assert!(red(&save(&mut s, json!({"useArtboards": true, "range": "1"}))), "the artboard's page"); + s.execute("select.all", &json!({})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(red(&save(&mut s, json!({}))), "the first artboard when no art shows"); +} + #[test] fn export_for_screens_includes_the_fill_unless_unchecked() { let mut s = session(); diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 8497676836..54839edda4 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -84,6 +84,11 @@ fn the_cnc_preset_sets_the_options_that_are_not_given() { true ) ); + assert_eq!((o.include_images, o.include_hatches), (false, false), "CNC / CAM leaves out images and fill hatches"); + let given = dxf::options(&json!({"dxfPreset": "cnc", "includeImages": true, "includeHatches": true})).unwrap(); + assert_eq!((given.include_images, given.include_hatches), (true, true), "the options given override it"); + let custom = dxf::options(&json!({})).unwrap(); + assert_eq!((custom.include_images, custom.include_hatches), (true, true), "Custom keeps both"); assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default"); let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string(); assert!(e.contains("custom or cnc"), "{e}"); @@ -151,6 +156,44 @@ fn placed_images_come_back_as_linked_files() { let _ = std::fs::remove_dir_all(dir); } +/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill +/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves +/// out both, and the options given override it. +#[test] +fn placed_images_and_fill_hatches_can_be_left_out() { + let mut s = super::tests_svg::image_session(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + let counts = |r: &Value| { + let e = entities(&text(r)); + let n = |k: &str| e.iter().filter(|x| *x == k).count(); + (n("LWPOLYLINE"), n("HATCH"), n("IMAGE"), r.get("linked").and_then(Value::as_array).map_or(0, Vec::len)) + }; + let warned = |r: &Value, w: &str| r["warnings"].as_array().unwrap().iter().any(|x| x.as_str().is_some_and(|x| x.starts_with(w))); + let all = s.execute("document.export", &json!({"format": "dxf"})).unwrap(); + assert_eq!(counts(&all), (1, 1, 1, 1)); + let r = s.execute("document.export", &json!({"format": "dxf", "includeImages": false})).unwrap(); + assert_eq!(counts(&r), (1, 1, 0, 0)); + assert!(warned(&r, "placed images are left out") && !warned(&r, "fill hatches"), "{r}"); + let r = s.execute("document.exportDxf", &json!({"includeHatches": false})).unwrap(); + assert_eq!(counts(&r), (1, 0, 1, 1)); + assert!(warned(&r, "fill hatches are left out") && !warned(&r, "placed images"), "{r}"); + let r = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap(); + assert_eq!(counts(&r), (1, 0, 0, 0)); + let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc", "includeImages": true})).unwrap(); + assert_eq!(counts(&r), (1, 0, 1, 1)); + // With a path, no image file is written next to the drawing. + let dir = std::env::temp_dir().join(format!("vc-dxf-out-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("cut.dxf").to_string_lossy().to_string(); + let r = s.execute("document.exportDxf", &json!({"path": path, "dxfPreset": "cnc"})).unwrap(); + assert!(r.get("linked").is_none(), "{r}"); + let files: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect(); + assert_eq!(files, ["cut.dxf"]); + let _ = std::fs::remove_dir_all(dir); +} + /// Two placed images whose pixel data can't be decoded are left out of the drawing and get no /// linked file, and `warnings` holds the note raster exports give, once, without naming either /// image's key. @@ -181,6 +224,8 @@ fn bad_dxf_options_are_refused() { json!({"rasterFormat": "gif"}), json!({"preserve": "both"}), json!({"alterPaths": "yes"}), + json!({"includeImages": "no"}), + json!({"includeHatches": 0}), ] { let e = s.execute("document.exportDxf", &p).unwrap_err().to_string(); assert!(e.contains("DXF"), "{p}: {e}"); @@ -203,6 +248,8 @@ fn formats_list_dxf_and_what_can_not_be_written() { "scaleLineweights", "colors", "rasterFormat", + "includeImages", + "includeHatches", "preserve", "alterPaths", "outlineText", diff --git a/crates/engine/src/cmd/fileio/tests_eps.rs b/crates/engine/src/cmd/fileio/tests_eps.rs index 8e2c1d429a..db667e6ef2 100644 --- a/crates/engine/src/cmd/fileio/tests_eps.rs +++ b/crates/engine/src/cmd/fileio/tests_eps.rs @@ -218,6 +218,106 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() { assert!(l3.contains("/FlateDecode filter >> image")); } +/// The PNG thumbnail of an EPS file, decoded. +fn thumbnail_png(bytes: &[u8]) -> image::RgbaImage { + let png = vectorcraft_eps::thumbnail(bytes).expect("a thumbnail"); + image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8() +} + +/// The TIFF preview of an EPS file, decoded. +fn preview_tiff(bytes: &[u8]) -> image::RgbaImage { + let tiff = vectorcraft_eps::sections(bytes).unwrap().1.expect("a preview"); + image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8() +} + +/// The size of a thumbnail render of the rect an EPS file's preview shows (its bounding box). +fn thumbnail_size(bytes: &[u8]) -> (u32, u32) { + let b: Vec<f64> = dsc(&postscript(bytes), "BoundingBox").unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + let rect = vectorcraft_geom::Rect::new(b[0], b[1], b[2], b[3]); + let long = rect.width().max(rect.height()); + vectorcraft_render::raster_size(rect, if long > 128.0 { 128.0 / long } else { 1.0 }).unwrap() +} + +/// The thumbnail is the color preview made smaller, the area average of its pixels at the size a +/// 128 px render has, not a second render of the document; it shows the same picture as one. +#[test] +fn the_thumbnail_is_made_from_the_preview() { + let mut s = session(1000.0, 700.0, 1); + s.execute("paint.setFill", &json!({"color": "#2060c0"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 37.3, "y": 41.9, "width": 811.7, "height": 563.1})).unwrap(); + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": "tiffColor", "transparentPreview": false})).unwrap(); + let bytes = b64(&r); + let preview = preview_tiff(&bytes); + assert_eq!(preview.dimensions(), (1000, 700)); + let thumb = thumbnail_png(&bytes); + assert_eq!(thumb.dimensions(), (128, 90)); + // An opaque preview's straight pixels are its premultiplied ones. + let shown = vectorcraft_render::Rendered { width: 1000, height: 700, pixels: preview.into_raw() }; + assert!(thumb.as_raw() == &shown.area_resized(128, 90).unwrap().pixels, "the thumbnail isn't the preview made smaller"); + let doc = &s.doc().unwrap().doc; + let fresh = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(0.0, 0.0, 1000.0, 700.0), 0.128, true); + let mut diffs: Vec<u8> = thumb.as_raw().iter().zip(&fresh.pixels).map(|(a, b)| a.abs_diff(*b)).collect(); + diffs.sort_unstable(); + let mean = diffs.iter().map(|d| f64::from(*d)).sum::<f64>() / diffs.len() as f64; + let p95 = diffs[diffs.len() * 95 / 100]; + assert!(mean <= 8.0 && p95 <= 32, "mean {mean}, 95th percentile {p95}"); +} + +/// A thumbnail is opaque color on white whatever the preview: a transparent color preview's, and a +/// black-and-white preview's, which keeps the art's colors. +#[test] +fn thumbnails_of_transparent_and_black_and_white_previews_are_opaque_color() { + let mut s = session(400.0, 200.0, 1); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap(); + let doc = &s.doc().unwrap().doc; + let fresh = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 200.0), 0.32, true); + let red: [u8; 4] = fresh.pixels[(32 * 128 + 10) * 4..][..4].try_into().unwrap(); + for preview in ["tiffColor", "tiffBw"] { + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": preview})).unwrap(); + let thumb = thumbnail_png(&b64(&r)); + assert_eq!(thumb.dimensions(), (128, 64), "{preview}"); + assert_eq!(thumb.get_pixel(10, 32).0, red, "{preview}"); + assert_eq!(thumb.get_pixel(120, 32).0, [255, 255, 255, 255], "{preview}"); + assert!(thumb.pixels().all(|p| p[3] == 255), "{preview}"); + } +} + +/// A page that fits in a thumbnail gets its preview's own pixels, unresampled. +#[test] +fn a_small_page_s_thumbnail_is_its_preview() { + let mut s = session(100.0, 60.0, 1); + s.execute("shape.ellipse", &json!({"x": 10.5, "y": 7.25, "width": 70, "height": 41})).unwrap(); + let bytes = b64(&s.execute("document.exportEps", &json!({"useArtboards": true, "transparentPreview": false})).unwrap()); + let thumb = thumbnail_png(&bytes); + assert_eq!(thumb.dimensions(), (100, 60)); + assert!(thumb == preview_tiff(&bytes), "the thumbnail isn't the preview"); +} + +/// Every file has a thumbnail at the size a thumbnail render has, with any page shape, on Save +/// too and without a preview; with thumbnails off there is none. +#[test] +fn every_file_s_thumbnail_has_the_thumbnail_size() { + let mut s = session(333.3, 77.7, 2); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": 3.7, "y": 5.1, "width": 300, "height": 61.3})).unwrap(); + s.execute("shape.ellipse", &json!({"x": second + 1.0, "y": 2.0, "width": 20, "height": 70})).unwrap(); + for preview in ["tiffColor", "tiffBw", "none"] { + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "previewFormat": preview})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 3); + for f in files { + let bytes = b64(f); + assert_eq!(thumbnail_png(&bytes).dimensions(), thumbnail_size(&bytes), "{preview} {}", f["name"]); + } + } + assert_eq!(thumbnail_size(&b64(&s.execute("document.exportEps", &json!({"range": "1"})).unwrap())), (128, 30)); + let saved = b64(&s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap()); + assert_eq!(thumbnail_png(&saved).dimensions(), thumbnail_size(&saved)); + let r = s.execute("document.exportEps", &json!({"useArtboards": true, "thumbnails": false})).unwrap(); + assert!(r["files"].as_array().unwrap().iter().all(|f| vectorcraft_eps::thumbnail(&b64(f)).is_none())); +} + /// Two placed images whose pixel data can't be decoded are left out of the EPS, and `warnings` /// holds the note raster exports give, once, without naming either image's key. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs new file mode 100644 index 0000000000..f4767fd81d --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -0,0 +1,231 @@ +//! HP-GL plotter files through the commands: `document.open` by extension or by content, File › +//! Place as one group of paths, the dialogs' filters and the format list, files that aren't +//! HP-GL refused with a message, and `document.export` of one artboard, each or the art, with its +//! options checked. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// An inch-wide red square and a black diagonal, with the thinnest pen. +const PLOT: &[u8] = b"IN;SP2;PW0;PA0,0;PD1016,0,1016,1016,0,1016,0,0;PU;SP1;PD1016,1016;PU;"; + +#[test] +fn document_open_reads_a_plot_file() { + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "part.plt", "dataBase64": b64(PLOT)})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("hpgl"), Some("part.plt")), "{r}"); + let st = s.doc().unwrap(); + let board = st.doc.artboards[0].rect; + assert!((board.width() - 72.25).abs() < 1e-9 && (board.height() - 72.25).abs() < 1e-9, "{board:?}"); + let mut paths = vec![]; + st.doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 2); + // Opened as artwork: Save asks for a name. + assert!(st.path.is_none()); + + // A plot file opens by its content in any of its names, and under a name no format reads. + for name in ["drawing.prn", "PART.HPGL", "part.hgl", "part.hpg"] { + let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(PLOT)})).unwrap(); + assert_eq!(r["format"].as_str(), Some("hpgl"), "{name}: {r}"); + } +} + +#[test] +fn file_place_places_a_plot_file_as_one_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let p = json!({"name": "part.plt", "dataBase64": b64(PLOT), "thumbnail": 16}); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["format"], "hpgl", "{info}"); + assert!((info["width"].as_f64().unwrap() - 72.25).abs() < 1e-9, "{info}"); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("hpgl"), Some(1)), "{r}"); + let doc = &s.doc().unwrap().doc; + let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Group { children, clip, .. } = &group.kind else { panic!("a group, got {:?}", group.kind) }; + assert_eq!((children.len(), *clip), (2, false), "the art's bounds, not clipped"); +} + +#[test] +fn files_that_are_not_hpgl_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let before = s.doc().unwrap().doc.artboards[0].rect.size(); + let script = b"set terminal png\nplot sin(x)\n"; + let e = s.execute("document.open", &json!({"name": "graph.plt", "dataBase64": b64(script)})).expect_err("refused"); + assert!(e.to_string().contains("not an HP-GL file"), "{e}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), before); + assert!(s.execute("file.place", &json!({"name": "graph.plt", "dataBase64": b64(script)})).is_err()); + // Text that isn't a plot opens by its name, not as HP-GL. + assert!(detect("notes.txt", b"IN THE BEGINNING").is_none_or(|f| f.id != "hpgl")); + // Only a plot file's own names, and names no other format reads, are read by their content: + // text, other formats' files and the formats named as unsupported (a DWG drawing starts with + // `AC` and digits) aren't, even when they start like a plot. + for name in ["notes.txt", "notes.svg", "picture.tga", "drawing.dxf", "site.dwg", "old.pct"] { + for bytes in [&b"IN"[..], b"in 5;", b"AC1032\0\0", PLOT] { + assert!(detect(name, bytes).is_none_or(|f| f.id != "hpgl"), "{name}: {:?}", String::from_utf8_lossy(bytes)); + } + } + let text = s.execute("file.place", &json!({"name": "notes.txt", "dataBase64": b64(b"IN 5; PA 10;")})).unwrap(); + assert_eq!(text["format"], "txt", "{text}"); +} + +/// A plot file named as one opens when its first instruction is one a plot file seldom starts with; +/// under another name it isn't taken for HP-GL. +#[test] +fn a_plot_file_by_its_name_may_start_with_any_instruction() { + let plot = b"SI0.2,0.3;SP1;PA0,0;PD1016,0;"; + let r = Session::new().execute("document.open", &json!({"name": "part.plt", "dataBase64": b64(plot)})).unwrap(); + assert_eq!(r["format"].as_str(), Some("hpgl"), "{r}"); + assert!(detect("drawing.prn", plot).is_none_or(|f| f.id != "hpgl")); +} + +#[test] +fn the_dialogs_and_the_format_list_name_hpgl() { + let exts = ["plt", "hpgl", "hgl", "hpg"]; + for e in exts { + assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}"); + assert_eq!(format_for_name(&format!("a.{e}")).map(|f| f.id), Some("hpgl"), "{e}"); + } + let filter = ("HP-GL", &exts[..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = Session::new().execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "hpgl").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false))); + for o in ["useArtboards", "hpglVersion", "curveTolerance", "pens", "origin", "sortPaths", "insideFirst"] { + assert!(f["options"].get(o).is_some(), "{o}: {f}"); + } + assert_eq!(writable_format(None, Some("x/part.plt")).unwrap().id, "hpgl"); + assert_eq!(writable_format(None, Some("x/part.hpgl")).unwrap().id, "hpgl"); +} + +fn bytes(v: &Value) -> Vec<u8> { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// Two 100 pt artboards side by side, a 30 pt square on each, the second one red. +fn two_boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let red = s.execute("shape.rectangle", &json!({"x": second + 10.0, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [red], "color": "#ff0000"})).unwrap(); + s +} + +#[test] +fn export_writes_a_plot_of_one_artboard_or_each() { + let mut s = two_boards(); + let r = s.execute("document.export", &json!({"format": "hpgl"})).unwrap(); + assert_eq!(r["format"], "hpgl"); + // The first artboard's square, 1016 units to the inch from its bottom-left corner. + assert_eq!(String::from_utf8(bytes(&r)).unwrap(), "IN;PU;SP1;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;"); + let second = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl", "artboard": 1})).unwrap())).unwrap(); + assert_eq!(second, "IN;PU;SP1;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;", "its own square, its own pen 1"); + assert_eq!(bytes(&s.execute("document.serialize", &json!({"format": "hpgl"})).unwrap()), bytes(&r)); + let r = s.execute("document.export", &json!({"format": "hpgl", "useArtboards": true})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 2); + assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.plt"), "{files:?}"); + // One pen numbering for every file: the red square is pen 2 in the second. + assert_eq!(String::from_utf8(bytes(&files[1])).unwrap(), "IN;PU;SP2;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;"); + // The bounds of the art: both squares, the second pen red, read back as two paths. + let art = bytes(&s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false, "hpglVersion": "hpgl2"})).unwrap()); + assert!(art.starts_with(b"IN;NP4;PC1,0,0,0;PC2,255,0,0;"), "{:?}", String::from_utf8_lossy(&art)); + let back = Session::new().execute("document.open", &json!({"name": "art.plt", "dataBase64": b64(&art)})).unwrap(); + assert_eq!(back["format"], "hpgl", "{back}"); + // One file holds one artboard. + assert!(s.execute("document.export", &json!({"format": "hpgl", "artboards": [0, 1]})).is_err()); +} + +/// A plot read back opens with the same squares: as wide as the art drew them, a point at most +/// apart from the 30 pt sides plus the 0.35 mm pen. +#[test] +fn a_plot_reads_back_as_its_art() { + let mut s = two_boards(); + let plot = bytes(&s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).unwrap()); + let mut back = Session::new(); + back.execute("document.open", &json!({"name": "art.plt", "dataBase64": b64(&plot)})).unwrap(); + let doc = &back.doc().unwrap().doc; + let mut paths = 0; + doc.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(paths, 2); + let board = doc.artboards[0].rect; + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + let pen = 0.35 * 72.0 / 25.4; + assert!((board.width() - (second + 30.0 + pen)).abs() < 0.1, "{board:?}"); + assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}"); +} + +#[test] +fn export_options_are_checked() { + let mut s = two_boards(); + let refused = |s: &mut Session, p: Value| s.execute("document.export", &p).expect_err("refused").to_string(); + let cases = [ + (json!({"format": "hpgl", "hpglVersion": "hpgl3"}), "`hpglVersion` must be one of hpgl, hpgl2"), + (json!({"format": "hpgl", "hpglVersion": 2}), "`hpglVersion` must be a string"), + (json!({"format": "hpgl", "curveTolerance": 0}), "`curveTolerance` must be between 0.01 and 10 (got 0)"), + (json!({"format": "hpgl", "curveTolerance": "fine"}), "`curveTolerance` must be a number"), + (json!({"format": "hpgl", "pens": []}), "`pens` must be an array of 1 to 255 #rrggbb colors"), + (json!({"format": "hpgl", "pens": ["#ff0000", "red"]}), "`pens` must be an array of 1 to 255 #rrggbb colors"), + (json!({"format": "hpgl", "pens": "#ff0000"}), "`pens` must be an array of 1 to 255 #rrggbb colors"), + (json!({"format": "hpgl", "origin": "top"}), "`origin` must be one of bottomLeft, center"), + (json!({"format": "hpgl", "sortPaths": "yes"}), "`sortPaths` must be true or false"), + (json!({"format": "hpgl", "insideFirst": 1}), "`insideFirst` must be true or false"), + ]; + for (p, want) in cases { + let e = refused(&mut s, p.clone()); + assert!(e.contains(want), "{p}: {e}"); + } + let many: Vec<String> = (0..256).map(|i| format!("#{:02x}0000", i % 256)).collect(); + assert!(refused(&mut s, json!({"format": "hpgl", "pens": many})).contains("`pens`")); + // Given options take effect: the center as the origin, a pen table (black is pen 2), and the + // square starting at its corner nearest the origin. + let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true}); + let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap(); + assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;"); +} + +/// `insideFirst` draws the square inside the other one first, though it was made last. +#[test] +fn inside_first_draws_the_inner_square_first() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 20, "height": 20})).unwrap(); + let starts = |s: &mut Session, p: Value| { + let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap(); + (plot.find("PU141,1270;").unwrap(), plot.find("PU423,988;").unwrap()) + }; + let (outer, inner) = starts(&mut s, json!({"format": "hpgl"})); + assert!(outer < inner); + let (outer, inner) = starts(&mut s, json!({"format": "hpgl", "insideFirst": true})); + assert!(inner < outer); +} + +/// Export Selection plots the selected square alone (the red one, made last), from the +/// bottom-left corner of its bounds. +#[test] +fn export_selection_writes_a_plot_of_the_selection() { + let mut s = two_boards(); + let r = s.execute("document.exportSelection", &json!({"format": "hpgl"})).unwrap(); + assert_eq!(r["format"], "hpgl"); + let plot = String::from_utf8(bytes(&r)).unwrap(); + assert_eq!(plot.matches("PD").count(), 1, "{plot}"); + assert!(plot.starts_with("IN;PU;SP1;PU7,430;PD"), "{plot}"); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs new file mode 100644 index 0000000000..31f670d7ff --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -0,0 +1,1017 @@ +//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and +//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers +//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export +//! read back, and damaged files read without a panic. + +use serde_json::{Value, json}; +use vectorcraft_color::BlendMode; +use vectorcraft_doc::{Node, NodeKind}; + +use super::*; + +/// One layer record of a synthetic file. +#[derive(Clone)] +struct L { + name: &'static str, + /// Top, left, bottom, right. + rect: [i32; 4], + /// Red, green, blue and alpha, the same for every pixel. + rgba: [u8; 4], + blend: &'static [u8; 4], + opacity: u8, + clipped: bool, + hidden: bool, + divider: Option<u32>, + /// Rect, default color, flags and the mask's pixels. + mask: Option<([i32; 4], u8, u8, Vec<u8>)>, + /// Extra tagged blocks. + blocks: Vec<([u8; 4], Vec<u8>)>, + /// Zipped channels: with prediction when `true`. + zip: Option<bool>, + /// The record lists no channels, whatever its rect. + bare: bool, + /// The Pascal name's bytes, with no Unicode name block. + legacy: Option<&'static [u8]>, +} + +fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L { + L { + name, + rect, + rgba, + blend: b"norm", + opacity: 255, + clipped: false, + hidden: false, + divider: None, + mask: None, + blocks: vec![], + zip: None, + bare: false, + legacy: None, + } +} + +fn group_end() -> L { + L { divider: Some(3), ..layer("</Layer group>", [0; 4], [0; 4]) } +} + +fn group(name: &'static str, blend: &'static [u8; 4]) -> L { + L { divider: Some(1), blend, ..layer(name, [0; 4], [0; 4]) } +} + +/// A tagged block, its length padded to even. +fn block(key: &[u8; 4], data: &[u8], psb: bool) -> Vec<u8> { + let mut data = data.to_vec(); + data.resize(data.len().next_multiple_of(2), 0); + let mut b = b"8BIM".to_vec(); + b.extend(key); + if psb && matches!(key, b"Lr16" | b"Lr32") { + b.extend((data.len() as u64).to_be_bytes()); + } else { + b.extend((data.len() as u32).to_be_bytes()); + } + b.extend(data); + b +} + +/// One row of a zipped channel with prediction: each sample stored as the difference from the one +/// before it, and in 32 bits the row's first bytes, then its second bytes and so on, each byte the +/// difference from the byte before it. +fn predict(row: &[u8], depth: u16) -> Vec<u8> { + let bytewise = |b: &[u8]| -> Vec<u8> { b.iter().scan(0u8, |prev, &v| Some(v.wrapping_sub(std::mem::replace(prev, v)))).collect() }; + match depth { + 16 => { + let mut prev = 0u16; + row.chunks(2) + .flat_map(|s| { + let v = u16::from_be_bytes([s[0], s[1]]); + v.wrapping_sub(std::mem::replace(&mut prev, v)).to_be_bytes() + }) + .collect() + } + 32 => bytewise(&(0..4).flat_map(|k| row.chunks(4).map(move |s| s[k])).collect::<Vec<_>>()), + _ => bytewise(row), + } +} + +/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped +/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. +fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option<bool>) -> Vec<u8> { + let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }; + let row: Vec<u8> = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect(); + if let Some(predicted) = zip { + let rows = n.checked_div(width).unwrap_or(0); + let one = if predicted { predict(&row, depth) } else { row }; + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + for _ in 0..rows { + std::io::Write::write_all(&mut z, &one).unwrap(); + } + let mut d = vec![0, if predicted { 3 } else { 2 }]; + d.extend(z.finish().unwrap()); + return d; + } + if !rle || n == 0 { + let mut d = vec![0, 0]; + d.extend(std::iter::repeat_n(sample.as_slice(), n).flatten()); + return d; + } + // Each row as literal runs of at most 128 bytes. + let mut packed = vec![]; + for run in row.chunks(128) { + packed.push((run.len() - 1) as u8); + packed.extend(run); + } + let rows = n / width; + let mut d = vec![0, 1]; + for _ in 0..rows { + if psb { + d.extend((packed.len() as u32).to_be_bytes()); + } else { + d.extend((packed.len() as u16).to_be_bytes()); + } + } + for _ in 0..rows { + d.extend(&packed); + } + d +} + +/// The layer info: the count (negative: the merged image has transparency), the records, then +/// their channels. +fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> { + let mut records: Vec<u8> = vec![]; + let mut data: Vec<u8> = vec![]; + for l in layers { + let [t, lf, b, r] = l.rect; + let (w, h) = ((r - lf).max(0) as usize, (b - t).max(0) as usize); + let mut channels: Vec<(i16, Vec<u8>)> = [(-1, l.rgba[3]), (0, l.rgba[0]), (1, l.rgba[1]), (2, l.rgba[2])] + .iter() + .filter(|_| !l.bare) + .map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip))) + .collect(); + let mut mask = vec![]; + if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { + let mut d = vec![0, 0]; + for &p in pixels { + d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + } + channels.push((-2, d)); + for v in [mt, ml, mb, mr] { + mask.extend(v.to_be_bytes()); + } + mask.extend([*default, *flags, 0, 0]); + } + for v in l.rect { + records.extend(v.to_be_bytes()); + } + records.extend((channels.len() as u16).to_be_bytes()); + for (id, d) in &channels { + records.extend(id.to_be_bytes()); + if psb { + records.extend((d.len() as u64).to_be_bytes()); + } else { + records.extend((d.len() as u32).to_be_bytes()); + } + data.extend(d); + } + records.extend(b"8BIM"); + records.extend(l.blend); + records.extend([l.opacity, u8::from(l.clipped), 0x08 | if l.hidden { 2 } else { 0 }, 0]); + let mut extra = (mask.len() as u32).to_be_bytes().to_vec(); + extra.extend(mask); + extra.extend(0u32.to_be_bytes()); + let ascii = l.legacy.unwrap_or(l.name.as_bytes()); + extra.push(ascii.len() as u8); + extra.extend(ascii); + // The Pascal string padded to a multiple of 4 (what comes before it is too). + extra.resize(extra.len().next_multiple_of(4), 0); + if l.legacy.is_none() { + let units: Vec<u16> = l.name.encode_utf16().collect(); + let mut luni = (units.len() as u32).to_be_bytes().to_vec(); + luni.extend(units.iter().flat_map(|u| u.to_be_bytes())); + extra.extend(block(b"luni", &luni, psb)); + } + if let Some(kind) = l.divider { + extra.extend(block(b"lsct", &[&kind.to_be_bytes()[..], b"8BIM", l.blend].concat(), psb)); + } + for (key, d) in &l.blocks { + extra.extend(block(key, d, psb)); + } + records.extend((extra.len() as u32).to_be_bytes()); + records.extend(extra); + } + let mut info = (-(layers.len() as i16)).to_be_bytes().to_vec(); + info.extend(records); + info.extend(data); + info.resize(info.len().next_multiple_of(2), 0); + info +} + +/// An RGB document of `w` × `h` pixels at 72 ppi holding `layers` (bottom first). 16- and 32-bit +/// documents keep their layers in an `Lr16` or `Lr32` block. +fn file(w: u32, h: u32, layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> { + let info = layer_info(layers, depth, rle, psb); + let length = |n: usize, out: &mut Vec<u8>| { + if psb { + out.extend((n as u64).to_be_bytes()); + } else { + out.extend((n as u32).to_be_bytes()); + } + }; + let mut section = vec![]; + if depth == 8 { + length(info.len(), &mut section); + section.extend(info); + section.extend(0u32.to_be_bytes()); + } else { + length(0, &mut section); + section.extend(0u32.to_be_bytes()); + section.extend(block(if depth == 32 { b"Lr32" } else { b"Lr16" }, &info, psb)); + } + let mut f = b"8BPS".to_vec(); + f.extend(if psb { 2u16 } else { 1 }.to_be_bytes()); + f.extend([0; 6]); + f.extend(4u16.to_be_bytes()); + f.extend(h.to_be_bytes()); + f.extend(w.to_be_bytes()); + f.extend(depth.to_be_bytes()); + f.extend(3u16.to_be_bytes()); + f.extend(0u32.to_be_bytes()); + f.extend(0u32.to_be_bytes()); + length(section.len(), &mut f); + f.extend(section); + // The merged image: raw, mid gray, opaque. + f.extend([0, 0]); + let n = (w * h) as usize * usize::from(depth / 8); + f.extend(std::iter::repeat_n(128, n * 3)); + f.extend(std::iter::repeat_n(255, n)); + f +} + +/// The warning for one hidden layer left out. +const HIDDEN_1: &str = "1 layer was left out (hidden layers and the layers clipped to them)"; + +fn open(f: &[u8], p: Value) -> (Session, Value) { + let mut s = Session::new(); + let r = s.execute("document.open", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f)}), p)).unwrap(); + (s, r) +} + +fn name(n: &Node) -> &str { + n.name.as_deref().unwrap_or("") +} + +/// The layer's one image, named as the layer: its place (points) and its pixels. +fn image_of(s: &Session, l: &Node) -> ((f64, f64), image::RgbaImage) { + let Some([c]) = l.children().map(Vec::as_slice) else { panic!("{} holds {:?}", name(l), l.children().map(Vec::len)) }; + assert_eq!(name(c), name(l)); + pixels_of(s, c) +} + +/// An image's place (points) and its pixels. +fn pixels_of(s: &Session, c: &Node) -> ((f64, f64), image::RgbaImage) { + let NodeKind::Image(img) = &c.kind else { panic!("{} isn't an image", name(c)) }; + let blob = &s.doc().unwrap().doc.images[&img.key]; + let px = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + assert_eq!((px.width(), px.height()), (img.width, img.height)); + let o = img.xf * kurbo::Point::ZERO; + ((o.x, o.y), px) +} + +/// Bottom, a pass-through group of a multiply layer at 50 % and a hidden layer, a screen group, and +/// a layer at 40 % fill opacity. +fn stack() -> Vec<L> { + let mut fill = layer("Faded", [1, 1, 3, 3], [0, 0, 255, 255]); + fill.blocks.push((*b"iOpa", vec![102])); + vec![ + layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), + group_end(), + L { blend: b"mul ", opacity: 128, ..layer("Inner A", [0, 0, 4, 4], [0, 255, 0, 255]) }, + L { hidden: true, ..layer("Inner B", [4, 4, 8, 8], [0, 0, 255, 255]) }, + group("Folder", b"pass"), + group_end(), + layer("Lit", [2, 2, 6, 6], [10, 20, 30, 128]), + group("Screens", b"scrn"), + fill, + ] +} + +#[test] +fn layers_open_as_layers_with_their_names_visibility_opacity_and_blend_modes() { + let (s, r) = open(&file(8, 8, &stack(), 8, false, false), json!({})); + assert_eq!((&r["format"], &r["warnings"]), (&json!("psd"), &json!([HIDDEN_1])), "{r}"); + let d = &s.doc().unwrap().doc; + assert!((d.artboards[0].rect.width() - 8.0).abs() < 1e-9 && (d.artboards[0].rect.height() - 8.0).abs() < 1e-9); + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom", "Folder", "Screens", "Faded"], "bottom first"); + // The bottom layer's image covers the canvas in its color. + let ((x, y), px) = image_of(&s, &d.layers[0]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((0.0, 0.0), (8, 8), [255, 0, 0, 255])); + // A pass-through group: a layer of sublayers that blend with what is below; its hidden layer + // is left out. + let folder = &d.layers[1]; + assert!(matches!(folder.kind, NodeKind::Layer { .. }) && !folder.isolate && folder.blend == BlendMode::Normal); + let inner: Vec<&str> = folder.children().unwrap().iter().map(|c| name(c)).collect(); + assert_eq!(inner, ["Inner A"]); + let a = &folder.children().unwrap()[0]; + assert!(a.blend == BlendMode::Multiply && (a.opacity - 128.0 / 255.0).abs() < 1e-6 && a.visible); + // Another group mode: isolated, in its mode; a layer keeps its transparency and place. + let screens = &d.layers[2]; + assert!(screens.isolate && screens.blend == BlendMode::Screen); + let ((x, y), px) = image_of(&s, &screens.children().unwrap()[0]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((2.0, 2.0), (4, 4), [10, 20, 30, 128])); + // Fill opacity multiplies the opacity. + assert!((d.layers[3].opacity - 102.0 / 255.0).abs() < 1e-6, "{}", d.layers[3].opacity); + // Hidden layers come in hidden when asked for. + let (s, r) = open(&file(8, 8, &stack(), 8, false, false), json!({"hiddenLayers": true})); + assert_eq!(r["warnings"], json!([]), "{r}"); + let folder = &s.doc().unwrap().doc.layers[1]; + let inner: Vec<(&str, bool)> = folder.children().unwrap().iter().map(|c| (name(c), c.visible)).collect(); + assert_eq!(inner, [("Inner A", true), ("Inner B", false)]); + // `layers: false` opens the merged image, as before. + let (s, r) = open(&file(8, 8, &stack(), 8, false, false), json!({"layers": false})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.len(), d.layers[0].children().map(Vec::len)), (1, Some(1)), "{r}"); + assert_eq!(pixels_of(&s, &d.layers[0].children().unwrap()[0]).1.get_pixel(0, 0).0, [128, 128, 128, 255]); + let bad = Session::new().execute("document.open", &json!({"name": "a.psd", "dataBase64": "AAAA", "hiddenLayers": "yes"})); + assert!(bad.unwrap_err().to_string().contains("hiddenLayers must be true or false")); +} + +#[test] +fn sixteen_bit_packbits_and_psb_layers_read() { + for (depth, rle, psb) in [(16, false, false), (8, true, false), (8, true, true), (16, true, true)] { + let (s, r) = open(&file(8, 8, &stack(), depth, rle, psb), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom", "Folder", "Screens", "Faded"], "{depth} {rle} {psb}: {r}"); + let px = image_of(&s, &d.layers[2].children().unwrap()[0]).1; + assert_eq!(px.get_pixel(1, 1).0, [10, 20, 30, 128], "{depth} {rle} {psb}"); + } +} + +/// Zipped channels, with and without prediction, at 8, 16 and 32 bits (32-bit colors are linear, +/// so the test uses 0 and 1, which sRGB's curve keeps). +#[test] +fn zipped_and_32_bit_layers_read() { + for depth in [8, 16, 32] { + for zip in [None, Some(false), Some(true)] { + if depth != 32 && zip.is_none() { + continue; + } + let layers = [L { zip, ..layer("Back", [0, 0, 4, 4], [0, 0, 255, 255]) }, L { zip, ..layer("Front", [1, 1, 3, 4], [255, 0, 255, 128]) }]; + let (s, r) = open(&file(4, 4, &layers, depth, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Back", "Front"], "{depth} {zip:?}: {r}"); + let ((x, y), px) = image_of(&s, &d.layers[1]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(2, 1).0), ((1.0, 1.0), (3, 2), [255, 0, 255, 128]), "{depth} {zip:?}"); + } + } +} + +/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman. +#[test] +fn names_without_a_unicode_name_read_as_mac_roman() { + let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({})); + assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}"); +} + +#[test] +fn layer_masks_become_opacity_masks() { + let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]); + masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255])); + let mut shown = layer("Shown outside", [0, 0, 8, 8], [0, 0, 0, 255]); + shown.mask = Some(([0, 0, 1, 2], 255, 0, vec![0, 0])); + let mut off = layer("Off", [0, 0, 8, 8], [0, 0, 0, 255]); + off.mask = Some(([0, 0, 1, 1], 0, 2, vec![0])); + // Flag bit 2: the mask's values and its default color are read inverted. + let mut inverted = layer("Inverted", [0, 0, 8, 8], [0, 0, 0, 255]); + inverted.mask = Some(([0, 0, 1, 2], 0, 4, vec![255, 64])); + let (s, _) = open(&file(8, 8, &[masked, shown, off, inverted], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let mask = |i: usize| d.layers[i].extras().mask.as_deref().expect("a mask"); + let m = mask(0); + assert!(m.clip && !m.disabled, "outside a mask with default 0 is hidden"); + let ((x, y), px) = pixels_of(&s, &m.art); + assert_eq!(((x, y), px.dimensions()), ((2.0, 2.0), (2, 2))); + assert_eq!([px.get_pixel(0, 0).0, px.get_pixel(1, 0).0, px.get_pixel(0, 1).0], [[255, 255, 255, 255], [128, 128, 128, 255], [0, 0, 0, 255]]); + assert!(!mask(1).clip, "outside a mask with default 255 shows"); + assert!(mask(2).disabled, "a disabled mask is kept, switched off"); + let m = mask(3); + assert!(!m.clip, "an inverted default of 0 shows outside the mask"); + let px = pixels_of(&s, &m.art).1; + assert_eq!([px.get_pixel(0, 0).0, px.get_pixel(1, 0).0], [[0, 0, 0, 255], [191, 191, 191, 255]]); +} + +#[test] +fn clipped_layers_merge_into_the_layer_below() { + let base = L { opacity: 200, ..layer("Base", [4, 4, 8, 8], [255, 255, 0, 255]) }; + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 8, 6], [0, 0, 255, 255]) }; + let hidden = L { clipped: true, hidden: true, ..layer("Gone", [0, 0, 8, 8], [0, 255, 0, 255]) }; + let (s, r) = + open(&file(8, 8, &[layer("Under", [0, 0, 2, 2], [1, 2, 3, 255]), base, clipped, hidden], 8, false, false), json!({"hiddenLayers": true})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Under", "Base + Clipped"], "{r}"); + assert_eq!(r["warnings"], json!([HIDDEN_1]), "a hidden clipped layer is left out: {r}"); + // The base keeps its place, transparency and opacity; the clipped layer shows only on it. + let merged = &d.layers[1]; + assert!((merged.opacity - 200.0 / 255.0).abs() < 1e-6); + let ((x, y), px) = image_of(&s, merged); + assert_eq!(((x, y), px.dimensions()), ((4.0, 4.0), (4, 4))); + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(3, 3).0), ([0, 0, 255, 255], [255, 255, 0, 255])); + // A base's layer mask stays the merged layer's opacity mask, over the unmasked pixels. + let mut masked = layer("Masked", [0, 0, 4, 4], [255, 255, 0, 255]); + masked.mask = Some(([0, 0, 1, 1], 0, 0, vec![255])); + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }; + let (s, r) = open(&file(4, 4, &[masked, clipped], 8, false, false), json!({})); + let merged = &s.doc().unwrap().doc.layers[0]; + assert_eq!(name(merged), "Masked + Clipped", "{r}"); + assert!(merged.extras().mask.as_deref().is_some_and(|m| m.clip && !m.disabled), "{r}"); + let px = image_of(&s, merged).1; + assert_eq!((px.dimensions(), px.get_pixel(3, 3).0), ((4, 4), [0, 0, 255, 255])); + // A hidden base would need the merge: even with hidden layers asked for, it is left out with + // the layers clipped to it. + let hidden_base = L { hidden: true, ..layer("Hidden base", [0, 0, 4, 4], [255, 255, 0, 255]) }; + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }; + let layers = [layer("Under", [0, 0, 2, 2], [1, 2, 3, 255]), hidden_base, clipped, layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])]; + for hidden in [false, true] { + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let names: Vec<&str> = s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Under", "Over"], "{hidden}: {r}"); + assert_eq!(r["warnings"], json!(["2 layers were left out (hidden layers and the layers clipped to them)"]), "{hidden}: {r}"); + } +} + +/// A masked base merged with its clipped layers, then with a layer in a mode VectorCraft lacks, +/// still hides what its mask hides. +#[test] +fn a_merged_base_keeps_its_mask_in_a_later_merge() { + let mut masked = layer("Masked", [0, 0, 4, 4], [255, 0, 0, 255]); + masked.mask = Some(([0, 0, 1, 1], 0, 0, vec![255])); + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }; + let dodge = L { blend: b"lddg", ..layer("Dodge", [3, 3, 4, 4], [0, 0, 0, 255]) }; + let layers = [layer("Bottom", [0, 0, 4, 4], [0, 255, 0, 255]), masked, clipped, dodge]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(name(&d.layers[0]), "Bottom + Masked + Clipped + Dodge", "{r}"); + let px = image_of(&s, &d.layers[0]).1; + // Inside the mask the clipped layer shows; outside it, the layer below. + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(2, 2).0), ([0, 0, 255, 255], [0, 255, 0, 255])); +} + +#[test] +fn layers_in_modes_vectorcraft_lacks_merge_with_the_layers_below() { + let dodge = L { blend: b"lddg", ..layer("Dodge", [0, 0, 2, 2], [100, 100, 100, 255]) }; + let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 8, 8], [0, 0, 0, 255]) }; + let layers = [layer("Bottom", [0, 0, 8, 8], [100, 50, 0, 255]), hidden, dodge, layer("Top", [6, 6, 8, 8], [0, 0, 0, 255])]; + let (s, r) = open(&file(8, 8, &layers, 8, false, false), json!({"hiddenLayers": true})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom + Dodge", "Top"], "hidden layers a merge takes in are left out: {r}"); + let (_, px) = image_of(&s, &d.layers[0]); + // Linear Dodge adds: 100 + 100, 50 + 100, 0 + 100. + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(5, 5).0), ([200, 150, 100, 255], [100, 50, 0, 255])); + assert!(r["warnings"].to_string().contains("Linear Dodge"), "{r}"); + // Darker Color keeps the color whose channels add up to less: (0, 0, 200) over (100, 50, 0) + // has the larger total but the lower luminance, so the base stays. + let darker = L { blend: b"dkCl", ..layer("Darker", [0, 0, 2, 2], [0, 0, 200, 255]) }; + let (s, _) = open(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [100, 50, 0, 255]), darker], 8, false, false), json!({})); + let (_, px) = image_of(&s, &s.doc().unwrap().doc.layers[0]); + assert_eq!(px.get_pixel(0, 0).0, [100, 50, 0, 255]); + // A hidden layer in such a mode would need the merge: left out, hidden layers asked for or not. + let hidden_dodge = L { hidden: true, blend: b"lddg", ..layer("Hidden dodge", [0, 0, 2, 2], [100, 100, 100, 255]) }; + let (s, r) = open(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [100, 50, 0, 255]), hidden_dodge], 8, false, false), json!({"hiddenLayers": true})); + let names: Vec<&str> = s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect(); + assert_eq!((names, &r["warnings"]), (vec!["Bottom"], &json!([HIDDEN_1])), "{r}"); +} + +/// A merge whose canvases would need more memory than allowed leaves the layer in the Normal mode, +/// with a warning. +#[test] +fn a_merge_past_the_memory_allowed_leaves_the_layer_normal() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [layer("Bottom", [0, 0, 2, 2], [100, 50, 0, 255]), L { blend: b"lddg", ..layer("Dodge", [2, 2, 4, 4], [100, 100, 100, 255]) }]; + let f = file(4, 4, &layers, 8, false, false); + // Each 2 × 2 layer fits 128 bytes (16 a pixel), and so does the first canvas of the merge with + // the layer beside it; the 4 × 4 canvas of both doesn't. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Bottom", BlendMode::Normal), ("Dodge", BlendMode::Normal)]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + // With room for it, the merge is made. + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Dodge"]); + // A merge onto a canvas that already covers the layer holds both: two 4 × 4 canvases take 512 + // bytes, past 300, although the canvas of the two 1 × 1 layers below fits (288 bytes). + let layers = [ + layer("Bottom", [0, 0, 1, 1], [100, 50, 0, 255]), + layer("Corner", [3, 3, 4, 4], [0, 50, 100, 255]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 4, 4], [100, 100, 100, 255]) }, + ]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom", "Corner", "Dodge"]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Corner + Dodge"]); + // A group below whose layers each fit, but whose canvas (4 × 4 with both 1 × 1 layers held, 288 + // bytes) doesn't fit 100: the layers stay, and the layer comes in Normal. + let layers = [ + group_end(), + layer("Left", [0, 0, 1, 1], [100, 50, 0, 255]), + layer("Right", [3, 3, 4, 4], [0, 50, 100, 255]), + group("Pair", b"norm"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [100, 100, 100, 255]) }, + ]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 100, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Pair", BlendMode::Normal), ("Dodge", BlendMode::Normal)]); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Left", "Right"]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Pair + Dodge"]); + // A layer below whose pixels fit (128 bytes) but whose canvas (16 bytes a pixel, 256) doesn't + // fit 200: the same. + let layers = [layer("Big", [0, 0, 4, 4], [100, 50, 0, 255]), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [100, 100, 100, 255]) }]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 200, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Big", BlendMode::Normal), ("Dodge", BlendMode::Normal)]); + assert_eq!(warnings, ["1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed"]); + // A clipped layer whose merge doesn't fit (the base's canvas and its transparency, 20 bytes a + // pixel, beside the clipped layer's canvas, 16: 576 bytes, past 300) comes in unclipped. + let layers = [layer("Base", [0, 0, 4, 4], [255, 0, 0, 255]), L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 0, 255, 255]) }]; + let f = file(4, 4, &layers, 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base", "Clipped"]); + assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]); + let (doc, _) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Clipped"]); +} + +/// A merge that can't be made counts nothing that the merges inside it counted: here the merge +/// in a group at half opacity fails inside the outer merge's attempt (the copy of what is below the +/// group takes the room) and succeeds when the group comes in. +#[test] +fn a_merge_that_cant_be_made_counts_only_itself() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + layer("Under", [0, 0, 2, 2], [100, 50, 0, 255]), + group_end(), + layer("Inner", [0, 0, 2, 2], [10, 10, 10, 255]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 2, 2], [20, 20, 20, 255]) }, + L { opacity: 128, ..group("Pass", b"pass") }, + L { blend: b"diss", ..layer("Top", [0, 0, 2, 2], [0, 0, 0, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(2, 2, &layers, 8, false, false), false, 150, cms).unwrap().unwrap(); + let got: Vec<(&str, BlendMode)> = doc.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Under", BlendMode::Normal), ("Pass", BlendMode::Normal), ("Top", BlendMode::Normal)]); + assert_eq!(doc.layers[1].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner + Dodge"]); + assert_eq!( + warnings, + [ + "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them", + "1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + ] + ); +} + +/// Layers in modes VectorCraft lacks, one after another, merge onto the canvas the first merge made +/// without copying it: 300 of them over a 64 × 64 canvas (64 KiB) open within an allowance that a +/// copy for each would pass. Merges that need a copy of that canvas each, past the allowance, open +/// the merged image instead. +#[test] +fn merges_onto_a_merge_reuse_its_canvas() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let dodge = |rect: [i32; 4]| L { blend: b"lddg", ..layer("d", rect, [1, 1, 1, 255]) }; + let mut layers = vec![layer("Bottom", [0, 0, 1, 1], [0, 0, 0, 255]), dodge([63, 63, 64, 64])]; + layers.extend((0..300).map(|_| dodge([1, 1, 2, 2]))); + let (doc, warnings) = psdlayers::import(&file(64, 64, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!((doc.layers.len(), warnings.len()), (1, 1), "{warnings:?}"); + assert!(name(&doc.layers[0]).starts_with("Bottom + d + d") && name(&doc.layers[0]).matches(" + d").count() == 301); + // A Normal layer between each pair: every merge copies the 64 KiB canvas, and 150 of them pass + // eight times the allowance of 1 MiB. + let mut layers = vec![layer("Bottom", [0, 0, 1, 1], [0, 0, 0, 255]), dodge([63, 63, 64, 64])]; + for _ in 0..150 { + layers.extend([layer("n", [1, 1, 2, 2], [1, 1, 1, 255]), dodge([2, 2, 3, 3])]); + } + let e = psdlayers::import(&file(64, 64, &layers, 8, false, false), false, 1 << 20, cms).err(); + assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); +} + +/// A Dissolve layer at half opacity merges as pixels of its own color or of the color below, +/// about half of each, and none in between. +#[test] +fn dissolve_layers_merge_as_opaque_or_transparent_pixels() { + let dissolve = L { blend: b"diss", opacity: 128, ..layer("Dissolve", [0, 0, 16, 16], [255, 0, 0, 255]) }; + let layers = [layer("Bottom", [0, 0, 16, 16], [255, 255, 255, 255]), dissolve]; + let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom + Dissolve"], "{r}"); + let (_, px) = image_of(&s, &d.layers[0]); + let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count(); + let white = px.pixels().filter(|p| p.0 == [255, 255, 255, 255]).count(); + assert_eq!(red + white, 256, "every pixel is the layer's color or the color below"); + assert!((96..=160).contains(&red), "{red} of 256 pixels are the layer's"); + // A second Dissolve layer at half opacity over the first has its own pattern: about a quarter + // of the pixels still show the first. + let blue = L { blend: b"diss", opacity: 128, ..layer("Blue", [0, 0, 16, 16], [0, 0, 255, 255]) }; + let layers = [layers[0].clone(), layers[1].clone(), blue]; + let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({})); + let (_, px) = image_of(&s, &s.doc().unwrap().doc.layers[0]); + let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count(); + assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}"); +} + +#[test] +fn what_doesnt_come_in_is_said() { + let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); + text.blocks.push((*b"TySh", vec![0; 4])); + let mut adjust = layer("Levels", [0, 0, 0, 0], [0; 4]); + adjust.blocks.push((*b"levl", vec![0; 4])); + let mut fx = layer("Shadowed", [0, 0, 2, 2], [0, 0, 0, 255]); + fx.blocks.push((*b"lfx2", effects(true, true))); + fx.blocks.push((*b"knko", vec![1, 0, 0, 0])); + // Effects with the master switch off, or none switched on, aren't counted. + let mut fx_off = layer("Switched off", [0, 0, 1, 1], [0, 0, 0, 255]); + fx_off.blocks.push((*b"lfx2", effects(false, true))); + let mut fx_none = layer("None on", [0, 0, 1, 1], [0, 0, 0, 255]); + fx_none.blocks.push((*b"lfx2", effects(true, false))); + // An adjustment layer clipped to the layer below draws nothing, and is still counted. + let mut clipped_adjust = L { clipped: true, ..layer("Curves", [0, 0, 0, 0], [0; 4]) }; + clipped_adjust.blocks.push((*b"curv", vec![0; 4])); + let mut solid = layer("Fill", [0, 0, 0, 0], [0; 4]); + let mut soco = vec![0; 8]; + for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] { + soco.extend(key); + soco.extend(v.to_be_bytes()); + } + solid.blocks.push((*b"SoCo", soco.clone())); + // A shape layer: a solid color fill with a vector mask and the shape's pixels stored. + let mut shape = layer("Shape", [1, 1, 3, 2], [255, 0, 51, 255]); + shape.blocks.push((*b"SoCo", soco.clone())); + shape.blocks.push((*b"vmsk", vec![0; 8])); + // One with its vector mask only, no pixels: not drawn, rather than its color over the canvas, + // and the layer clipped to it isn't either. + let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]); + outline.blocks.push((*b"SoCo", soco)); + outline.blocks.push((*b"vsms", vec![0; 8])); + let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) }; + let layers = [solid, text, clipped_adjust, adjust, fx, fx_off, fx_none, shape, outline, on_outline]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Fill", "Words", "Shadowed", "Switched off", "None on", "Shape"], "an adjustment layer draws nothing"); + assert_eq!(image_of(&s, &d.layers[0]).1.get_pixel(3, 3).0, [255, 0, 51, 255], "a solid color fill covers the canvas"); + let ((x, y), px) = image_of(&s, &d.layers[5]); + assert_eq!(((x, y), px.dimensions()), ((1.0, 1.0), (1, 2)), "a shape layer comes in as the pixels it stores"); + let w = r["warnings"].to_string(); + for said in [ + "1 type layer came in as pixels", + "2 adjustment layers were not applied", + "1 fill layer was not drawn", + "the layer effects of 1 layer weren't drawn", + "the vector masks of 2 layers", + "the knockout of 1 layer wasn't applied", + "1 layer clipped to a fill layer that wasn't drawn was left out", + ] { + assert!(w.contains(said), "{said}: {w}"); + } +} + +/// An effects descriptor (`lfx2`) with its master switch and one effect's `enab` set: each key after +/// its length (0 for a 4-character key), then `bool` and a byte. +fn effects(master: bool, enabled: bool) -> Vec<u8> { + let mut d = vec![0; 8]; + d.extend(14u32.to_be_bytes()); + d.extend(b"masterFXSwitchbool"); + d.push(u8::from(master)); + d.extend(0u32.to_be_bytes()); + d.extend(b"enabbool"); + d.push(u8::from(enabled)); + d +} + +/// A layer's fill opacity fades only its own pixels when layers are clipped to it: they still show +/// in its shape, and the merged layer keeps the layer's opacity. +#[test] +fn a_clipping_base_fill_opacity_fades_only_its_own_pixels() { + for (fill, size, corner) in [(0u8, (4, 2), None), (128, (4, 4), Some([255, 0, 0, 128]))] { + let mut base = L { opacity: 200, ..layer("Base", [0, 0, 4, 4], [255, 0, 0, 255]) }; + base.blocks.push((*b"iOpa", vec![fill])); + let photo = L { clipped: true, ..layer("Photo", [0, 0, 2, 4], [0, 0, 255, 255]) }; + let (s, r) = open(&file(4, 4, &[base, photo], 8, false, false), json!({})); + let merged = &s.doc().unwrap().doc.layers[0]; + assert_eq!(name(merged), "Base + Photo", "{r}"); + assert!((merged.opacity - 200.0 / 255.0).abs() < 1e-6, "{fill}: {}", merged.opacity); + let ((x, y), px) = image_of(&s, merged); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((0.0, 0.0), size, [0, 0, 255, 255]), "{fill}"); + if let Some(c) = corner { + assert!(px.get_pixel(3, 3).0.iter().zip(c).all(|(&a, b)| a.abs_diff(b) <= 1), "{fill}: {:?}", px.get_pixel(3, 3)); + } + } +} + +/// Layers clipped to an adjustment layer show over the whole canvas of the file, through the +/// adjustment layer's mask. +#[test] +fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() { + let mut curves = layer("Curves", [0, 0, 0, 0], [0; 4]); + curves.blocks.push((*b"curv", vec![0; 4])); + curves.mask = Some(([0, 0, 1, 1], 255, 0, vec![0])); + let photo = L { clipped: true, ..layer("Photo", [-1, -1, 2, 5], [0, 0, 255, 255]) }; + let (s, r) = open(&file(4, 4, &[layer("Under", [0, 0, 4, 4], [255, 0, 0, 255]), curves, photo], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Under", "Curves + Photo"], "{r}"); + // Cut to the canvas: 4 × 2 at its corner. + let ((x, y), px) = image_of(&s, &d.layers[1]); + assert_eq!(((x, y), px.dimensions(), px.get_pixel(1, 1).0), ((0.0, 0.0), (4, 2), [0, 0, 255, 255])); + assert!(d.layers[1].extras().mask.is_some(), "the adjustment layer's mask stays"); + assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}"); +} + +/// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public +/// descriptions: <https://helpx.adobe.com/photoshop/desktop/repair-retouch/adjust-light-tone/blending-mode-descriptions.html> +/// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and +/// <https://en.wikipedia.org/wiki/Blend_modes> (Linear Burn, Linear Dodge, Linear Light, Subtract, +/// Divide). Color Dodge, Color Burn and Difference keep their mode. +#[test] +fn every_mode_vectorcraft_lacks_merges_by_its_formula() { + let b = [200u8, 100, 30]; + let s = [60u8, 180, 128]; + let burn = |b: f64, c: f64| if c <= 0.0 { if b >= 1.0 { 1.0 } else { 0.0 } } else { 1.0 - ((1.0 - b) / c).min(1.0) }; + let dodge = |b: f64, c: f64| if c >= 1.0 { if b <= 0.0 { 0.0 } else { 1.0 } } else { (b / (1.0 - c)).min(1.0) }; + let each = |f: &dyn Fn(f64, f64) -> f64| -> [u8; 3] { + [0, 1, 2].map(|i| (f(f64::from(b[i]) / 255.0, f64::from(s[i]) / 255.0).clamp(0.0, 1.0) * 255.0).round() as u8) + }; + let total = |c: [u8; 3]| c.iter().map(|&v| u32::from(v)).sum::<u32>(); + let cases: [(&[u8; 4], [u8; 3]); 10] = [ + (b"lbrn", each(&|b, s| b + s - 1.0)), + (b"lddg", each(&|b, s| b + s)), + (b"vLit", each(&|b, s| if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) })), + (b"lLit", each(&|b, s| b + 2.0 * s - 1.0)), + (b"pLit", each(&|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) })), + (b"hMix", each(&|b, s| if (b + s) * 255.0 >= 254.999 { 1.0 } else { 0.0 })), + (b"fsub", each(&|b, s| b - s)), + (b"fdiv", each(&|b, s| if s <= 0.0 { 1.0 } else { b / s })), + (b"dkCl", if total(s) < total(b) { s } else { b }), + (b"lgCl", if total(s) > total(b) { s } else { b }), + ]; + for (key, want) in cases { + let top = L { blend: key, ..layer("Top", [0, 0, 1, 1], [s[0], s[1], s[2], 255]) }; + let (st, r) = open(&file(1, 1, &[layer("Bottom", [0, 0, 1, 1], [b[0], b[1], b[2], 255]), top], 8, false, false), json!({})); + let d = &st.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Top"], "{key:?}: {r}"); + let got = image_of(&st, &d.layers[0]).1.get_pixel(0, 0).0; + assert!( + got[..3].iter().zip(want).all(|(&g, w)| g.abs_diff(w) <= 1) && got[3] == 255, + "{}: {got:?}, want {want:?}", + String::from_utf8_lossy(key) + ); + } + for (key, mode) in [(b"div ", BlendMode::ColorDodge), (b"idiv", BlendMode::ColorBurn), (b"diff", BlendMode::Difference)] { + let top = L { blend: key, ..layer("Top", [0, 0, 1, 1], [s[0], s[1], s[2], 255]) }; + let (st, r) = open(&file(1, 1, &[layer("Bottom", [0, 0, 1, 1], [b[0], b[1], b[2], 255]), top], 8, false, false), json!({})); + let d = &st.doc().unwrap().doc; + let got: Vec<(&str, BlendMode)> = d.layers.iter().map(|l| (name(l), l.blend)).collect(); + assert_eq!(got, [("Bottom", BlendMode::Normal), ("Top", mode)], "{r}"); + } +} + +/// A descriptor's numbers: each key (a 4-character key after a length of 0, a longer one after its +/// length), then `doub` and the value, or for `H `, `UntF`, `#Ang` and the value. +fn descriptor(values: &[(&[u8], f64)]) -> Vec<u8> { + let mut d = vec![0; 8]; + for (key, v) in values { + d.extend(if key.len() == 4 { 0u32 } else { key.len() as u32 }.to_be_bytes()); + d.extend(*key); + d.extend(if *key == b"H " { &b"UntF#Ang"[..] } else { b"doub" }); + d.extend(v.to_be_bytes()); + } + d +} + +/// Solid color fill layers that store no pixels come in as their color in every color model a +/// descriptor uses; one whose color can't be read, and a gradient fill that stores no pixels, are +/// counted; a gradient fill that stores pixels comes in as them. +#[test] +fn solid_color_fills_read_every_color_model() { + let fill = |name: &'static str, values: &[(&[u8], f64)]| { + let mut l = layer(name, [0, 0, 0, 0], [0; 4]); + l.blocks.push((*b"SoCo", descriptor(values))); + l + }; + let mut gradient = layer("Gradient", [0, 0, 0, 0], [0; 4]); + gradient.blocks.push((*b"GdFl", vec![0; 8])); + let mut gradient_shape = layer("Gradient shape", [1, 1, 2, 2], [7, 8, 9, 255]); + gradient_shape.blocks.push((*b"GdFl", vec![0; 8])); + // Bounds, but no channels: it stores no pixels either. + let mut pattern = L { bare: true, ..layer("Pattern", [0, 0, 4, 4], [0; 4]) }; + pattern.blocks.push((*b"PtFl", vec![0; 8])); + let layers = [ + fill("Float", &[(b"redFloat", 0.0), (b"greenFloat", 0.0), (b"blueFloat", 1.0)]), + fill("Cmyk", &[(b"Cyn ", 0.0), (b"Mgnt", 100.0), (b"Ylw ", 100.0), (b"Blck", 0.0)]), + fill("Gray", &[(b"Gry ", 25.0)]), + fill("Lab", &[(b"Lmnc", 100.0), (b"A ", 0.0), (b"B ", 0.0)]), + fill("Hsb", &[(b"H ", 120.0), (b"Strt", 100.0), (b"Brgh", 100.0)]), + fill("Unread", &[(b"Bk ", 1.0)]), + gradient, + gradient_shape, + pattern, + ]; + // A naive CMYK conversion, so that the colors don't depend on the color settings. + let naive = |c: [f32; 4]| [0, 1, 2].map(|i| (1.0 - c[i]) * (1.0 - c[3])); + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, naive).unwrap().unwrap(); + let names: Vec<&str> = doc.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Float", "Cmyk", "Gray", "Lab", "Hsb", "Gradient shape"]); + let mut s = Session::new(); + s.add_document(doc, None); + let d = &s.doc().unwrap().doc; + let colors: Vec<[u8; 4]> = d.layers[..5].iter().map(|l| image_of(&s, l).1.get_pixel(2, 2).0).collect(); + assert_eq!(colors[..3], [[0, 0, 255, 255], [255, 0, 0, 255], [191, 191, 191, 255]]); + assert!(colors[3].iter().all(|&v| v >= 253), "Lab 100, 0, 0 is white: {:?}", colors[3]); + assert_eq!(colors[4], [0, 255, 0, 255]); + assert_eq!(image_of(&s, &d.layers[5]).1.get_pixel(0, 0).0, [7, 8, 9, 255]); + assert_eq!(warnings, ["3 fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)"]); +} + +/// VectorCraft's own PSD export opens with the layers it wrote: groups as layers of sublayers, +/// hidden ones hidden, with their opacity and blend mode. +#[test] +fn psd_exports_open_with_their_layers() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 60, "height": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 40})).unwrap(); + s.execute("layer.new", &json!({"name": "Blue"})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap(); + s.execute("layer.new", &json!({"name": "Off"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let off = s.doc().unwrap().doc.layers.last().unwrap().id; + s.execute("layer.setProps", &json!({"id": off.0, "visible": false})).unwrap(); + for (options, top) in [ + (json!({"hiddenLayers": true}), vec![("Layer 1", true), ("Blue", true), ("Off", false)]), + (json!({"maxEditability": true}), vec![("Layer 1", true), ("Blue", true)]), + ] { + let r = s.execute("document.export", &merge(json!({"format": "psd"}), options.clone())).unwrap(); + let f = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let (back, r) = open(&f, json!({"hiddenLayers": true})); + let d = &back.doc().unwrap().doc; + let got: Vec<(&str, bool)> = d.layers.iter().map(|l| (name(l), l.visible)).collect(); + assert_eq!(got, top, "{options}: {r}"); + if options["maxEditability"] == true { + // Each layer a group: its objects become sublayers, the rectangle's opacity and blend mode + // on its own. + let blue = d.layers[1].children().unwrap(); + assert_eq!(blue.len(), 1, "{options}"); + assert!(blue[0].blend == BlendMode::Multiply && (blue[0].opacity - 0.5).abs() < 0.01, "{options}"); + } + } +} + +#[test] +fn files_without_layers_or_with_damaged_layers_open_as_their_merged_image() { + // No layer records: the merged image, without a warning. + let flat = { + let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false); + // The layer and mask section emptied: 4 length bytes of 0, after the header and two + // empty sections. + let at = 26 + 8; + let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize; + f.splice(at..at + 4 + len, 0u32.to_be_bytes()); + f + }; + let (_, r) = open(&flat, json!({})); + assert_eq!(r["warnings"], json!([]), "{r}"); + // Layer info of just the count (negative: the merged image has transparency) has no layers. + let count_only = { + let mut f = flat.clone(); + let at = 26 + 8; + f.splice(at..at + 4, [&10u32.to_be_bytes()[..], &2u32.to_be_bytes(), &(-1i16).to_be_bytes(), &[0, 0, 0, 0]].concat()); + f + }; + let (s, r) = open(&count_only, json!({})); + assert_eq!((&r["warnings"], s.doc().unwrap().doc.layers[0].children().map(Vec::len)), (&json!([]), Some(1)), "{r}"); + // A channel cut short: the merged image, with a warning. + let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap(); + cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes()); + let (s, r) = open(&cut, json!({})); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().map(Vec::len), Some(1)); + // Groups nested past the limit. + let mut deep: Vec<L> = (0..=psdlayers::MAX_DEPTH).map(|_| group_end()).collect(); + deep.push(layer("x", [0, 0, 1, 1], [0, 0, 0, 255])); + let (_, r) = open(&file(2, 2, &deep, 8, false, false), json!({})); + assert!(r["warnings"][0].as_str().unwrap().contains("nested too deeply"), "{r}"); + // Groups within the limit but deeper than a document may nest: the deepest merge into the + // group around them, with the warning. + let mut deep: Vec<L> = (0..40).map(|_| group_end()).collect(); + deep.push(layer("x", [0, 0, 1, 1], [0, 0, 0, 255])); + deep.extend((0..40).map(|_| group("g", b"norm"))); + let (s, r) = open(&file(2, 2, &deep, 8, false, false), json!({})); + assert_eq!(r["warnings"], json!([vectorcraft_doc::depth::merged_note()]), "{r}"); + fn depth(n: &Node) -> usize { + 1 + n.children().map_or(0, |c| c.iter().map(|c| depth(c)).max().unwrap_or(0)) + } + assert!(s.doc().unwrap().doc.layers.iter().map(|l| depth(l)).max().unwrap() <= vectorcraft_doc::MAX_DEPTH); +} + +/// A record whose layer mask or name is cut short opens the merged image with a warning, rather +/// than a layer without its mask or name. +#[test] +fn records_with_a_damaged_mask_or_name_open_as_the_merged_image() { + let good = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false); + // The record's extra data: an empty mask section, empty blending ranges, then the name. + let at = good.windows(10).position(|w| w == [0, 0, 0, 0, 0, 0, 0, 0, 1, b'x']).unwrap(); + // A mask section of 4 bytes, too short for a mask's place, default color and flags. + let mut short_mask = good.clone(); + short_mask[at + 3] = 4; + // A name longer than the record's extra data. + let mut long_name = good.clone(); + long_name[at + 8] = 0xff; + for f in [short_mask, long_name] { + let (s, r) = open(&f, json!({})); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().map(Vec::len), Some(1), "{r}"); + } +} + +#[test] +fn damaged_layers_never_panic() { + let mut masked = layer("Masked", [0, 0, 3, 3], [1, 2, 3, 255]); + masked.mask = Some(([1, 1, 2, 2], 0, 0, vec![200])); + let layers = [ + layer("A", [0, 0, 3, 3], [255, 0, 0, 255]), + group_end(), + masked, + L { clipped: true, ..layer("C", [0, 0, 3, 3], [0, 0, 255, 255]) }, + L { blend: b"lbrn", ..layer("D", [0, 0, 2, 2], [9, 9, 9, 255]) }, + group("G", b"pass"), + ]; + for (rle, psb) in [(false, false), (true, true)] { + let good = file(3, 3, &layers, 8, rle, psb); + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some()); + for i in 0..good.len() { + for v in [0, 1, 0x7f, 0x80, 0xff] { + let mut f = good.clone(); + f[i] = v; + let _ = psdlayers::import(&f, true, 1 << 30, cms); + } + } + for n in 0..good.len() { + let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + } + // A layer past the memory allowed is refused, not read. + assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large")); + } + // Many layers that each fit the memory allowed for one image, but not all together (8 bytes a + // pixel to read an 8 × 8 layer; 4 a pixel decoded, against 8 times the allowance). + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let many: Vec<L> = (0..20).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 255])).collect(); + assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some()); + let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err(); + assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); +} + +/// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers +/// blending onto what is below the group, as they do without the merge. +#[test] +fn merges_keep_pass_through_groups_blending_with_what_is_below() { + let layers = [ + layer("Bottom", [0, 0, 2, 2], [100, 200, 50, 255]), + group_end(), + L { blend: b"mul ", ..layer("Multiply", [0, 0, 2, 2], [128, 128, 128, 255]) }, + group("Pass", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(2, 2, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + assert_eq!(names, ["Bottom + Pass + Dodge"], "{r}"); + // 100, 200 and 50 times 128/255. + assert_eq!(image_of(&s, &d.layers[0]).1.get_pixel(1, 1).0, [50, 100, 25, 255]); + // At half opacity, or with a layer mask, the group's layers still blend with what is below + // it, and the result fades back toward it: halfway from (100, 200, 50) to (50, 100, 25). + let mut masked = group("Pass", b"pass"); + masked.mask = Some(([0, 0, 2, 2], 0, 0, vec![128, 128, 128, 128])); + for top in [L { opacity: 128, ..group("Pass", b"pass") }, masked] { + let mut layers = layers.clone(); + layers[3] = top; + let (s, r) = open(&file(2, 2, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Bottom + Pass + Dodge"], "{r}"); + let px = image_of(&s, &d.layers[0]).1.get_pixel(1, 1).0; + assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index d411496b02..08a46f0e10 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -141,6 +141,31 @@ fn packbits_zip_and_psb_files_read() { zip.extend(z.finish().unwrap()); let px = pixels(&psd(1, 1, (3, 1), 16, 1, &[], &[], &[], &zip)); assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [16, 32, 48]); + // Zipped with prediction, 32 bits: the row's first bytes, then its second bytes and so on, + // each byte stored as the difference from the byte before it. + let samples = [0.0f32, 1.0, 0.0].map(f32::to_be_bytes); + let planes: Vec<u8> = (0..4).flat_map(|k| samples.iter().map(move |s| s[k])).collect(); + let deltas: Vec<u8> = planes.iter().scan(0u8, |prev, &b| Some(b.wrapping_sub(std::mem::replace(prev, b)))).collect(); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &deltas).unwrap(); + let mut zip = vec![0, 3]; + zip.extend(z.finish().unwrap()); + let px = pixels(&psd(1, 1, (3, 1), 32, 1, &[], &[], &[], &zip)); + assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [0, 255, 0]); + // The same layout as another implementation writes it: psd-tools 1.26.1 (MIT, + // <https://github.com/psd-tools/psd-tools>), `compression.compress(data, + // Compression.ZIP_WITH_PREDICTION, 3, 2, 32)` of the samples 0, 1, 0.25 and 0.5, 0.125, 1, + // reads as the same samples stored raw. + let theirs = [ + 0x78, 0x9c, 0x63, 0xb0, 0xff, 0x7f, 0xa8, 0x81, 0xa1, 0x81, 0x01, 0x04, 0xec, 0xff, 0x33, 0x1e, 0x64, 0x68, 0x80, 0xb0, 0x01, 0x59, 0xd1, + 0x06, 0x01, + ]; + let mut zip = vec![0, 3]; + zip.extend(theirs); + let samples: Vec<u8> = [0.0f32, 1.0, 0.25, 0.5, 0.125, 1.0].iter().flat_map(|v| v.to_be_bytes()).collect(); + let stored = pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &raw(&[&samples]))); + assert_eq!(pixels(&psd(1, 1, (3, 2), 32, 1, &[], &[], &[], &zip)), stored); + assert_eq!(stored.iter().map(|p| p[0]).collect::<Vec<_>>()[..2], [0, 255]); } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index b0dcd368ec..86ee164998 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -667,6 +667,118 @@ fn a_numbered_file_is_written_into_the_first_rows_folder() { assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder"); } +/// An export into the folder an export preset keeps, for a client whose read roots don't hold that +/// folder: the reply leaves out the ZIP's path and names the files relative to the folder. A folder +/// inside the read roots, and one the client gives, stay whole. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_presets_folder_outside_the_read_root_is_left_out_of_the_reply() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("preset-roots"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap(); + let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| confine(roots.as_ref(), || export(s, p)); + + let r = run(&mut s, &write_only, json!({"exportPreset": "Kept"})); + assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}"); + assert!(out.join("1x/Artboard-1.png").is_file()); + let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true})); + assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}"); + assert!(!r.to_string().contains(&folder), "{r}"); + // Inside the read roots, or given by the client: whole. + assert_eq!(run(&mut s, &both, json!({"exportPreset": "Kept"}))["files"], json!([format!("{folder}/1x/Artboard-1.png")])); + let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true})); + assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}"); +} + +/// An export into the folder an export preset keeps, refused because that folder is outside the +/// client's read and write roots: the error names the folder by its name only. A folder the client +/// gives stays whole in the error. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_refused_export_into_a_presets_folder_outside_the_read_root_names_it_by_its_name() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("preset-refused"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png"}], "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let mut run = |p: Value| confine(confined.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap_err().to_string(); + + let e = run(json!({"exportPreset": "Kept"})); + assert!(e.contains("outside the write root") && e.contains("kept-out") && !e.contains(&folder), "{e}"); + let e = run(json!({"exportPreset": "Kept", "folder": folder})); + assert!(e.contains(&folder), "{e}"); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing written"); + // A preset folder that holds the write root: the root stays whole in the error. + let parent = tmp.0.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "png"}], "folder": parent}); + s.execute("document.exportPresets.save", &json!({"name": "Parent", "settings": settings})).unwrap(); + let e = confine(confined.as_ref(), || s.execute("document.exportForScreens", &json!({"exportPreset": "Parent"}))).unwrap_err().to_string(); + let root = inside.display().to_string(); + let name = tmp.0.file_name().unwrap().to_string_lossy().into_owned(); + assert!(e.contains(&format!("root {root}: {name}")), "{e}"); +} + +/// The export settings the document keeps and the saved presets, read by a client whose read roots +/// don't hold their folder: `document.exportSettings`, `document.exportPresets.list` and +/// `document.exportPresets.export` (as data and as a file) leave out that folder and keep the rest. +/// Inside the read roots the folder stays. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn kept_settings_leave_out_a_folder_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + + let mut s = session(1); + let tmp = Folder::new("settings-roots"); + let (inside, out) = (tmp.0.join("in"), tmp.0.join("out")); + for f in [&inside, &out] { + std::fs::create_dir_all(f).unwrap(); + } + let folder = out.to_string_lossy().replace('\\', "/"); + let settings = json!({"formats": [{"format": "svg"}], "folder": folder}); + s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap(); + export(&mut s, json!({"exportPreset": "Kept"})); + let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[inside.as_path()]).unwrap(); + let ask = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, cmd: &str, p: Value| { + confine(roots.as_ref(), || s.execute(cmd, &p).unwrap()) + }; + let saved = |list: &Value| list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Kept").unwrap()["settings"].clone(); + + let r = ask(&mut s, &confined, "document.exportSettings", json!({})); + assert_eq!((r["settings"].get("folder"), &r["settings"]["formats"]), (None, &json!([{"format": "svg"}])), "{r}"); + let r = ask(&mut s, &confined, "document.exportPresets.list", json!({})); + assert_eq!(saved(&r), json!({"formats": [{"format": "svg"}]}), "{r}"); + let r = ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"]})); + let data = r["data"].as_str().unwrap(); + assert!(!data.contains(&folder) && data.contains("svg"), "{data}"); + let file = inside.join("kept.vcexportpresets"); + let path = file.to_string_lossy().replace('\\', "/"); + ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"], "path": path})); + assert!(!std::fs::read_to_string(&file).unwrap().contains(&folder)); + + // Inside the read roots: whole. + assert_eq!(ask(&mut s, &both, "document.exportSettings", json!({}))["settings"]["folder"], json!(folder)); + assert_eq!(saved(&ask(&mut s, &both, "document.exportPresets.list", json!({})))["folder"], json!(folder)); + assert!(ask(&mut s, &both, "document.exportPresets.export", json!({"names": ["Kept"]}))["data"].as_str().unwrap().contains(&folder)); +} + #[test] fn format_settings_apply_to_their_rows_and_rows_win() { let mut s = session(1); diff --git a/crates/engine/src/cmd/findfiles/tests.rs b/crates/engine/src/cmd/findfiles/tests.rs index ec3ce57e3a..bf51ebdac7 100644 --- a/crates/engine/src/cmd/findfiles/tests.rs +++ b/crates/engine/src/cmd/findfiles/tests.rs @@ -183,6 +183,16 @@ fn a_picked_folder_inside_other_apps_folders_is_refused() { assert!(p.error().is_some_and(|e| e.ends_with("is not a folder")), "{p:?}"); let p = search(&root, "missing", Limits::default(), 1, &[]); assert!(p.error().is_some_and(|e| e.starts_with(&root.join("missing").display().to_string())), "{p:?}"); + // Each failure has the same reason without the folder's path. + let briefs = [ + ("missing", "the folder can't be read"), + ("file.ttf", "the path isn't a folder"), + ("refused", "VectorCraft doesn't search other apps' or the system's folders"), + ("Users/Public/x", "VectorCraft doesn't search the Shared or Public folder in Users"), + ]; + for (picked, why) in briefs { + assert_eq!(search(&root, picked, Limits::default(), 1, &[]).failure(), Some(why), "{picked}"); + } } #[test] @@ -362,7 +372,7 @@ fn a_picked_folder_that_cant_be_listed_fails_the_search() { let p = search(&root, "locked", Limits::default(), 2, &["y.ttf"]); std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); if enforced { - assert!(matches!(&p.end, Some(End::Failed(e)) if e.contains("locked")), "{p:?}"); + assert!(matches!(&p.end, Some(End::Failed(e, "the folder can't be listed")) if e.contains("locked")), "{p:?}"); } else { assert_eq!(found(&root, &p), ["locked/y.ttf"]); } diff --git a/crates/engine/src/cmd/findfiles/walk.rs b/crates/engine/src/cmd/findfiles/walk.rs index 8d35515717..ae05a04838 100644 --- a/crates/engine/src/cmd/findfiles/walk.rs +++ b/crates/engine/src/cmd/findfiles/walk.rs @@ -23,6 +23,13 @@ const CHECK_EVERY: u64 = 1024; /// How a search ends when every walker thread stopped on a bug. const INTERNAL: &str = "every search thread stopped on an internal error (please report this bug)"; +/// Why a search couldn't start, without the folder's path ([`Progress::failure`]). +const UNREADABLE: &str = "the folder can't be read"; +const NOT_A_FOLDER: &str = "the path isn't a folder"; +const SHARED: &str = "VectorCraft doesn't search the Shared or Public folder in Users"; +const APPS: &str = "VectorCraft doesn't search other apps' or the system's folders"; +const UNLISTED: &str = "the folder can't be listed"; + /// What a search looks for. pub trait Visitor: Send + Sync { /// Whether the regular file named `name` is to be read: asked of the files a folder lists until @@ -77,8 +84,9 @@ pub enum End { /// reached their [`Limits`]. Folders deeper than [`Limits::depth`] are skipped and an item /// keeps at most [`Limits::per_item`] files, without ending the search. Limit, - /// It couldn't start: the folder can't be read, isn't a folder or isn't one to search. - Failed(String), + /// It couldn't start: the folder can't be read, isn't a folder or isn't one to search. Why, + /// and the same without the folder's path. + Failed(String, &'static str), } /// Where a search stands ([`Search::progress`]). @@ -114,7 +122,7 @@ impl Progress { None => "searching", Some(End::Done | End::Found) => "done", Some(End::Stopped | End::Time | End::Limit) => "stopped", - Some(End::Failed(_)) => "failed", + Some(End::Failed(..)) => "failed", } } @@ -131,10 +139,38 @@ impl Progress { /// Why a failed search failed. pub fn error(&self) -> Option<&str> { match &self.end { - Some(End::Failed(e)) => Some(e), + Some(End::Failed(e, _)) => Some(e), _ => None, } } + + /// Why a failed search failed, without the folder's path. + pub fn failure(&self) -> Option<&'static str> { + match &self.end { + Some(End::Failed(_, why)) => Some(why), + _ => None, + } + } + + /// Keep what the caller asking now may read under its read roots ([`crate::file_access::current`]), + /// for a reply to it: the files found inside them. Returns the folder searched (`given` until a + /// walker checked it) and why the search failed, when that folder lies inside them too; + /// otherwise no folder and why without its path ([`Self::failure`]). Without read roots in + /// force, everything is kept. + pub fn keep_readable(&mut self, given: &str) -> (Option<String>, Option<String>) { + let folder = if self.folder.as_os_str().is_empty() { given.to_string() } else { self.folder.to_string_lossy().into_owned() }; + if crate::file_access::current().is_none() { + return (Some(folder), self.error().map(str::to_string)); + } + // A path that isn't valid text is never shown: its lossy form names another file. + let readable = |p: &Path| p.to_str().is_some_and(|p| crate::file_access::check_read(p).is_ok()); + self.hits.retain(|(path, _)| readable(path)); + if readable(Path::new(given)) && (self.folder.as_os_str().is_empty() || readable(&self.folder)) { + (Some(folder), self.error().map(str::to_string)) + } else { + (None, self.failure().map(str::to_string)) + } + } } /// Walker threads shared out among searches: all of them together run at most `cap` threads. @@ -306,7 +342,7 @@ pub(crate) fn start_in( return Err("the search couldn't start: try again in a moment".into()); } if w.alive == 0 && w.end.is_none() { - shared.finish(&mut w, End::Failed(INTERNAL.into())); + shared.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)); } } Ok(Search { shared }) @@ -401,13 +437,13 @@ impl Shared { fn prepare(&self, root: &Path) { let rules = self.rules.get_or_init(|| self.given.clone().unwrap_or_else(Rules::system)); let path = root.display(); - let checked = match std::fs::canonicalize(root) { - Err(e) => Err(format!("{path}: {e}")), - Ok(folder) if !folder.is_dir() => Err(format!("{path} is not a folder")), + let (checked, brief) = match std::fs::canonicalize(root) { + Err(e) => (Err(format!("{path}: {e}")), UNREADABLE), + Ok(folder) if !folder.is_dir() => (Err(format!("{path} is not a folder")), NOT_A_FOLDER), Ok(folder) => match rules.refusal(&folder) { - None => Ok(folder), - Some(Refusal::Shared) => Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")), - Some(Refusal::Apps) => Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")), + None => (Ok(folder), INTERNAL), + Some(Refusal::Shared) => (Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")), SHARED), + Some(Refusal::Apps) => (Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")), APPS), }, }; let mut w = self.lock(); @@ -416,7 +452,7 @@ impl Shared { w.folder = folder.clone(); w.stack.push((folder, 0)); } - Err(e) => self.finish(&mut w, End::Failed(e)), + Err(e) => self.finish(&mut w, End::Failed(e, brief)), } } @@ -430,7 +466,7 @@ impl Shared { let mut w = self.lock(); // The picked folder itself: the search can't run, and says why. if depth == 0 { - self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display()))); + self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display()), UNLISTED)); } else { w.unreadable += 1; w.folders += 1; @@ -610,7 +646,7 @@ fn walker(s: &Shared) { if done.is_err() { let mut w = s.lock(); match job { - Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into())), + Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)), Job::List(..) => w.unreadable += 1, } } @@ -640,7 +676,7 @@ impl Drop for Alive { let mut w = self.0.lock(); w.alive = w.alive.saturating_sub(1); if w.alive == 0 && w.end.is_none() { - self.0.finish(&mut w, End::Failed(INTERNAL.into())); + self.0.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)); } drop(w); self.0.pool.release(1); diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index f950f8c1da..02b4097684 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -1,7 +1,10 @@ //! Object → Flatten Transparency: transparent art becomes opaque art that looks the same. //! -//! The targets (`ids` or the selection) split into groups of overlapping objects. Groups without -//! transparency stay as they are (their type and strokes are outlined on request). The others are +//! The targets (`ids` or the selection) split into groups: each object with transparency with the +//! objects it overlaps, and the objects without transparency whose stacking order with a member +//! would change when the group takes its topmost object's place. Objects without transparency +//! that overlap only others without it stay as they are (their type and strokes are outlined on +//! request), as do groups without transparency. The others are //! cut into atomic regions: the faces of the planar arrangement of every fill, outlined stroke and //! clipping path in them ([`po::regions`]). The same paints cover each whole region, so its colour //! is exact: those paints composited as the renderer composites them ([`Composer`], blend modes by diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index eacd124052..cf7bdb7baa 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -99,17 +99,77 @@ pub(super) fn masked(n: &Node) -> bool { n.extras().mask.as_ref().is_some_and(|m| !m.disabled) } -/// Where `n` can paint: its visual bounds grown by its effects (and a margin for antialiasing). -pub(super) fn reach(n: &Node) -> Option<Rect> { +/// Where `n` paints: its visual bounds grown by its effects. +pub(super) fn painted(n: &Node) -> Option<Rect> { if !n.visible { return None; } let b = match n.children() { - Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| reach(c)).reduce(|a, b| a.union(b))?, + Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| painted(c)).reduce(|a, b| a.union(b))?, _ => n.visual_bounds()?, }; let fx = n.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(effects::outset(&n.appearance.effects, b), f64::max); - Some(b.inflate(fx + 1.0, fx + 1.0)) + Some(b.inflate(fx, fx)) +} + +/// Where `n` can paint: where it paints ([`painted`]) and a margin of 1 pt for antialiasing, +/// once, however deep its groups nest. +pub(super) fn reach(n: &Node) -> Option<Rect> { + painted(n).map(|b| b.inflate(1.0, 1.0)) +} + +type Cancelled = vectorcraft_doc::cancel::Cancelled; + +/// Whether `b` has finite coordinates and isn't inside out. +pub(super) fn finite(b: &Rect) -> bool { + [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1 +} + +/// Whether boxes `a` and `b` overlap or touch. +fn touch(a: &Rect, b: &Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Indices joined into sets, each set knowing whether it holds an object with transparency. +struct Sets { + parent: Vec<usize>, + seeded: Vec<bool>, +} + +impl Sets { + fn find(&mut self, mut i: usize) -> usize { + while self.parent[i] != i { + self.parent[i] = self.parent[self.parent[i]]; + i = self.parent[i]; + } + i + } + + /// Joins the sets of `a` and `b`: → the set they are now, named by its lowest index. + fn join(&mut self, a: usize, b: usize) -> usize { + let (a, b) = (self.find(a), self.find(b)); + let (lo, hi) = (a.min(b), a.max(b)); + self.parent[hi] = lo; + self.seeded[lo] |= self.seeded[hi]; + lo + } + + /// The sets, each in index order, by their first index. + fn groups(&mut self) -> Vec<Vec<usize>> { + let mut groups: Vec<Vec<usize>> = vec![]; + let mut slot: Vec<Option<usize>> = vec![None; self.parent.len()]; + for i in 0..self.parent.len() { + let r = self.find(i); + match slot[r] { + Some(g) => groups[g].push(i), + None => { + slot[r] = Some(groups.len()); + groups.push(vec![i]); + } + } + } + groups + } } /// Indices of `bounds` grouped by overlap (transitively), each group in index order. Boxes that @@ -121,16 +181,15 @@ pub(super) fn reach(n: &Node) -> Option<Rect> { /// horizontal extent, would otherwise compare every pair). An open box inside a later box of /// its group, ending no further right, is closed early: whatever overlaps it overlaps that box. /// Fails only when cancelled ([`vectorcraft_doc::cancel`]). -pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, vectorcraft_doc::cancel::Cancelled> { - fn find(p: &mut [usize], mut i: usize) -> usize { - while p[i] != i { - p[i] = p[p[i]]; - i = p[i]; - } - i - } - let mut parent: Vec<usize> = (0..bounds.len()).collect(); - let finite = |b: &Rect| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1; +pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> { + Ok(sweep(bounds, None)?.groups()) +} + +/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is +/// see-through, and an open box is closed early only inside a later see-through box. +fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> { + let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() }; + let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]); let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect(); let n = boxes.len(); // Each box's place in the tree: by top (then index). @@ -190,29 +249,140 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, ve stack.push((2 * node + 1, mid, hi)); stack.push((2 * node, lo, mid)); } + // Whatever overlaps a box inside this one overlaps this one, and joins it when this one is + // see-through. + let shadows = see_through.is_none_or(|s| s[boxes[k].0]); for &o in &met { - let (a, c) = (find(&mut parent, boxes[k].0), find(&mut parent, boxes[o].0)); - parent[a.max(c)] = a.min(c); + if joins(boxes[k].0, boxes[o].0) { + sets.join(boxes[k].0, boxes[o].0); + } let ob = boxes[o].1; - if ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { + if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { set(&mut low, leaf[o], f64::NEG_INFINITY); } } set(&mut low, leaf[k], b.y1); } - let mut groups: Vec<Vec<usize>> = vec![]; - let mut slot: Vec<Option<usize>> = vec![None; bounds.len()]; - for i in 0..bounds.len() { - let r = find(&mut parent, i); - match slot[r] { - Some(g) => groups[g].push(i), - None => { - slot[r] = Some(groups.len()); - groups.push(vec![i]); + Ok(sets) +} + +/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box +/// touches. +struct Blocks { + order: Vec<usize>, + boxes: Vec<Option<Rect>>, + around: Vec<Rect>, +} + +impl Blocks { + const SIZE: usize = 32; + + /// The finite boxes of `boxes`, in vertical strips by their centers and in blocks down each + /// strip. + fn new(boxes: &[Option<Rect>]) -> Self { + let boxes: Vec<Option<Rect>> = boxes.iter().map(|b| b.filter(finite)).collect(); + let mut order: Vec<usize> = (0..boxes.len()).filter(|&i| boxes[i].is_some()).collect(); + let center = |i: usize| boxes[i].map_or_else(Default::default, |b| b.center()); + order.sort_by(|&a, &b| center(a).x.total_cmp(¢er(b).x)); + let strip = ((order.len() as f64 / Self::SIZE as f64).sqrt().ceil() as usize).max(1) * Self::SIZE; + for s in order.chunks_mut(strip) { + s.sort_by(|&a, &b| center(a).y.total_cmp(¢er(b).y)); + } + let around = order.chunks(Self::SIZE).filter_map(|c| c.iter().filter_map(|&i| boxes[i]).reduce(|a, b| a.union(b))).collect(); + Self { order, boxes, around } + } + + /// Puts the indices of the boxes that touch `q` in `out`. `work` counts the boxes looked at; + /// fails only when cancelled. + fn touching(&self, q: &Rect, out: &mut Vec<usize>, work: &mut usize) -> Result<(), Cancelled> { + out.clear(); + for (b, around) in self.around.iter().enumerate() { + *work += 1; + if work.is_multiple_of(4096) { + vectorcraft_doc::cancel::check()?; + } + if !touch(around, q) { + continue; + } + for &i in &self.order[b * Self::SIZE..((b + 1) * Self::SIZE).min(self.order.len())] { + *work += 1; + if self.boxes[i].is_some_and(|r| touch(&r, q)) { + out.push(i); + } } } + Ok(()) } - Ok(groups) +} + +/// Objects (in paint order) grouped for flattening, each group in paint order and the groups by +/// their first object; a group takes the place of its topmost object. `reach` is where each +/// object can paint ([`reach`]), `painted` where it paints ([`painted`]), and `see_through` whether +/// it has transparency. An object whose box is missing or not finite is a group of its own. +/// +/// An object joins every see-through object its reach touches. An object without transparency +/// that touches only others without transparency stays a group of its own, unless a group would +/// change its stacking order with it: it joins (and groups join each other) where its reach +/// touches a member's and moving the members to their group's top would put the two the other way +/// round. With a `fringe` (how far a group's image can reach past +/// its art and cover what is under it), an object or group under a group's top whose painted box +/// that far around a member's touches joins it too. Fails only when cancelled +/// ([`vectorcraft_doc::cancel`]). +pub(super) fn flatten_groups( + reach: &[Option<Rect>], + painted: &[Option<Rect>], + see_through: &[bool], + fringe: f64, +) -> Result<Vec<Vec<usize>>, Cancelled> { + let n = reach.len(); + let mut sets = sweep(reach, Some(see_through))?; + let mut members: Vec<Vec<usize>> = vec![vec![]; n]; + for i in 0..n { + let r = sets.find(i); + members[r].push(i); + } + // The topmost object of each set (by its name). + let mut top: Vec<usize> = (0..n).map(|r| members[r].last().copied().unwrap_or(r)).collect(); + let index = Blocks::new(reach); + // Each member of a set with transparency is looked at. + let mut work: Vec<usize> = vec![]; + for i in 0..n { + let r = sets.find(i); + if sets.seeded[r] { + work.push(i); + } + } + let (mut near, mut looked) = (vec![], 0usize); + while let Some(i) = work.pop() { + let Some(q) = reach[i].filter(finite) else { continue }; + // Painted boxes within the fringe have reaches within it too. + index.touching(&q.inflate(fringe, fringe), &mut near, &mut looked)?; + for &k in &near { + let (ri, rk) = (sets.find(i), sets.find(k)); + if ri == rk { + continue; + } + let (ti, tk) = (top[ri], top[rk]); + let crossed = reach[k].is_some_and(|b| touch(&q, &b)) && (i < k) != (ti < tk); + let covered = fringe > 0.0 && tk < ti && painted[i].zip(painted[k]).is_some_and(|(a, b)| touch(&a.inflate(fringe, fringe), &b)); + if !crossed && !covered { + continue; + } + // The members of a set whose top moves are looked at again, from there. + let t = ti.max(tk); + if ti != t { + work.extend_from_slice(&members[ri]); + } + if tk != t { + work.extend_from_slice(&members[rk]); + } + let r = sets.join(ri, rk); + let moved = std::mem::take(&mut members[if r == ri { rk } else { ri }]); + members[r].extend(moved); + top[r] = t; + } + } + Ok(sets.groups()) } #[cfg(test)] @@ -292,4 +462,153 @@ mod tests { let odd = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(f64::NAN, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 20.0, 20.0))]; assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]); } + + /// A filled rectangle, unstroked. + fn filled(id: u64, r: Rect) -> Node { + let look = vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), + vectorcraft_color::Paint::None, + 0.0, + ); + Node::path(vectorcraft_doc::NodeId(id), vectorcraft_geom::shapes::rectangle(r), look) + } + + /// The antialiasing margin goes around the outermost group once, not once per group. + #[test] + fn reach_adds_its_margin_once_however_deep_the_groups() { + let r = Rect::new(10.0, 20.0, 30.0, 50.0); + let inner = Node::group(vectorcraft_doc::NodeId(2), vec![Arc::new(filled(1, r))]); + let outer = Node::group(vectorcraft_doc::NodeId(3), vec![Arc::new(inner)]); + assert_eq!(painted(&outer), Some(r)); + assert_eq!(reach(&outer), Some(r.inflate(1.0, 1.0))); + assert_eq!(reach(&filled(1, r)), reach(&outer)); + } + + /// The group of each object, the topmost object of each group and whether it is see-through. + fn sets_of(groups: &[Vec<usize>], n: usize, see_through: &[bool]) -> (Vec<usize>, Vec<usize>, Vec<bool>) { + let mut of = vec![usize::MAX; n]; + for (g, ids) in groups.iter().enumerate() { + for &i in ids { + of[i] = g; + } + } + let top = groups.iter().map(|g| *g.last().unwrap()).collect(); + let seeded = groups.iter().map(|g| g.iter().any(|&i| see_through[i])).collect(); + (of, top, seeded) + } + + /// What [`flatten_groups`] must give: every object in one group, in paint order, the groups by + /// their first object; see-through objects with all that their reach touches; groups without + /// transparency of one object; no two objects that paint over each other the other way round + /// once each group takes its top's place; nothing within `fringe` of a member of a group under + /// that group's top. + fn check(reach: &[Option<Rect>], painted: &[Option<Rect>], see: &[bool], fringe: f64, groups: &[Vec<usize>], what: &str) { + let n = reach.len(); + let mut all: Vec<usize> = groups.iter().flatten().copied().collect(); + all.sort_unstable(); + assert_eq!(all, (0..n).collect::<Vec<_>>(), "{what}: every object once"); + assert!(groups.iter().all(|g| g.is_sorted()) && groups.windows(2).all(|w| w[0][0] < w[1][0]), "{what}: in order"); + let (of, top, seeded) = sets_of(groups, n, see); + for (g, ids) in groups.iter().enumerate() { + assert!(seeded[g] || ids.len() == 1, "{what}: {ids:?} has no transparency"); + } + for i in 0..n { + for j in 0..n { + if i == j || of[i] == of[j] { + continue; + } + let (gi, gj) = (of[i], of[j]); + if let (Some(a), Some(b)) = (reach[i], reach[j]) { + assert!(!(touch(&a, &b) && (see[i] || see[j])), "{what}: {i} and {j} touch, one see-through"); + if seeded[gi] && touch(&a, &b) { + assert_eq!(i < j, top[gi] < top[gj], "{what}: {i} and {j} change places"); + } + } + let (Some(a), Some(b)) = (painted[i], painted[j]) else { continue }; + if seeded[gi] && fringe > 0.0 && touch(&a.inflate(fringe, fringe), &b) { + assert!(top[gj] > top[gi], "{what}: {j} under the image of {i}'s group"); + } + } + } + } + + /// Boxes of many sizes, some see-through, group as they must, with and without a fringe. + #[test] + fn flatten_groups_keep_stacking_order_and_leave_opaque_art_alone() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..60 { + let n = 4 + round; + let painted: Vec<Option<Rect>> = (0..n) + .map(|i| { + if i % 13 == 5 { + return None; + } + let (x, y) = (next(120.0).round(), next(120.0).round()); + Some(Rect::new(x, y, x + next(25.0).round(), y + next(25.0).round())) + }) + .collect(); + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.15).collect(); + for fringe in [0.0, 0.7] { + let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap(); + check(&reach, &painted, &see, fringe, &groups, &format!("round {round}, fringe {fringe}")); + } + } + } + + /// A row of opaque boxes whose reaches touch, with see-through ones at its ends and far from + /// it: only the boxes next to a see-through one join it. + #[test] + fn an_opaque_row_stays_apart_from_the_see_through_boxes_at_its_ends() { + let n = 200; + // 10 pt boxes 1.5 pt apart: their 1 pt reaches overlap. + let painted: Vec<Option<Rect>> = (0..n).map(|i| Some(Rect::new(11.5 * i as f64, 0.0, 11.5 * i as f64 + 10.0, 10.0))).collect(); + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + let mut see = vec![false; n]; + see[0] = true; + see[n - 1] = true; + let groups = flatten_groups(&reach, &painted, &see, 0.0).unwrap(); + check(&reach, &painted, &see, 0.0, &groups, "row"); + assert_eq!(groups[0], vec![0, 1]); + assert_eq!(groups.last(), Some(&vec![n - 2, n - 1])); + assert_eq!(groups.len(), n - 2); + // Without transparency every box is a group of its own. + assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n); + } + + /// An opaque box between a member and its group's top that paints over the member joins, and + /// so on along a chain; one under the member stays, but for one within the fringe. + #[test] + fn boxes_the_group_would_cross_join_it() { + // In paint order: D under A, A, B over A, C over B, then the see-through T over A. + let d = Rect::new(40.0, 80.0, 65.0, 120.0); + let a = Rect::new(60.0, 50.0, 105.0, 90.0); + let b = Rect::new(20.0, 20.0, 65.0, 55.0); + let c = Rect::new(0.0, 0.0, 25.0, 25.0); + let t = Rect::new(100.0, 50.0, 140.0, 90.0); + let painted = [Some(d), Some(a), Some(b), Some(c), Some(t)]; + let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + let see = [false, false, false, false, true]; + let groups = flatten_groups(&reach, &painted, &see, 0.0).unwrap(); + assert_eq!(groups, vec![vec![0], vec![1, 2, 3, 4]]); + // C away from B: it stays. + let far = [Some(d), Some(a), Some(b), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(t)]; + let reach_far: Vec<Option<Rect>> = far.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + assert_eq!(flatten_groups(&reach_far, &far, &see, 0.0).unwrap(), vec![vec![0], vec![1, 2, 4], vec![3]]); + // B 0.5 pt above A, not overlapping it: their antialiased edges can share pixels, so B joins. + let gap = [Some(d), Some(a), Some(Rect::new(20.0, 20.0, 65.0, 49.5)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(t)]; + let reach_gap: Vec<Option<Rect>> = gap.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + assert_eq!(flatten_groups(&reach_gap, &gap, &see, 0.0).unwrap(), vec![vec![0], vec![1, 2, 4], vec![3]]); + // D a little left of A, under it: the fringe takes it in. + let near = [Some(Rect::new(40.0, 80.0, 59.8, 120.0)), Some(a), Some(b), Some(c), Some(t)]; + let reach_near: Vec<Option<Rect>> = near.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + assert_eq!(flatten_groups(&reach_near, &near, &see, 0.0).unwrap()[0], vec![0]); + assert_eq!(flatten_groups(&reach_near, &near, &see, 0.24).unwrap(), vec![vec![0, 1, 2, 3, 4]]); + } } diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 409db3f1b2..ef8425b362 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -1,4 +1,4 @@ -use super::analysis::{Scratch, has_effects, masked, outlined_text, overlapping, reach}; +use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach}; use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE}; use super::options::FlattenOptions; use super::{ @@ -115,7 +115,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). vectorcraft_doc::cancel::check()?; - let mut queue = overlapping(&reaches)?; + let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?; queue.reverse(); while let Some(g) = queue.pop() { vectorcraft_doc::cancel::check()?; @@ -196,6 +196,46 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: Ok(out) } +/// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the +/// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object. +/// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is +/// inside a clip group or clipping layer: [`inside_and_under`] and [`place_of`] then decide where +/// they go. +fn groups( + src: &Document, + roots: &[NodeId], + plain: &[Node], + reaches: &[Option<Rect>], + see_through: &[bool], + o: &FlattenOptions, +) -> Result<Vec<Vec<usize>>> { + // An image clipped to its regions, opaque over white, reaches a pixel past them; a group's + // image is no larger than the art it overlaps, so its pixels are no wider than this. + let opaque_edge = o.no_transparency.is_some() && o.clip_complex_regions && !o.preserve_alpha; + let ppi = o.line_art_ppi.min(o.gradient_ppi).max(1.0); + let extent = |ids: &mut dyn Iterator<Item = usize>| ids.filter_map(|i| reaches[i].filter(finite)).reduce(|a, b| a.union(b)).unwrap_or_default(); + // Where the widest such pixel is wider than the margins of two reaches, objects that close + // overlap too. + let widest = if opaque_edge { 1.0 / raster_scale(extent(&mut (0..reaches.len())), ppi) } else { 0.0 }; + let grow = ((widest - 2.0) / 2.0).max(0.0); + let near: Vec<Option<Rect>> = reaches.iter().map(|b| b.map(|b| b.inflate(grow, grow))).collect(); + let mut out = vec![]; + for g in overlapping(if grow > 0.0 { &near } else { reaches })? { + let clipped = || clips_count() && g.iter().any(|&i| !clip_ancestors(src, roots[i]).is_empty()); + if g.len() < 2 || !g.iter().any(|&i| see_through[i]) || clipped() { + out.push(g); + continue; + } + let fringe = if opaque_edge { 1.0 / raster_scale(extent(&mut g.iter().copied()), ppi) } else { 0.0 }; + let local = |v: &[Option<Rect>]| g.iter().map(|&i| v[i]).collect::<Vec<_>>(); + let painted: Vec<Option<Rect>> = g.iter().map(|&i| painted(&plain[i])).collect(); + let see: Vec<bool> = g.iter().map(|&i| see_through[i]).collect(); + out.extend(flatten_groups(&local(reaches), &painted, &see, fringe)?.into_iter().map(|l| l.into_iter().map(|k| g[k]).collect::<Vec<_>>())); + } + out.sort_by_key(|g| g.first().copied()); + Ok(out) +} + /// `plain` (object `id` of `src` as plain art) inside a clip group for each clip group and /// clipping layer around `id`, innermost first, each clipped by that group's or layer's clipping /// path. `plain` itself when nothing around it clips. With `fills` (clipping paths, and an area), @@ -482,11 +522,7 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool /// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs. /// Fails when the image can't be encoded. fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option<PathData>, o: &FlattenOptions) -> Result<Raster> { - let mut scale = ppi / 72.0; - scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt()); - // No side longer than the renderer draws: the image grows by a pixel on each side and is - // rounded up to whole pixels below. - scale = scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0)); + let scale = raster_scale(rect, ppi); let px = 1.0 / scale; let rect = rect.inflate(px, px); let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c)); @@ -559,6 +595,14 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip }) } +/// Pixels per point of an image of `rect` at `ppi`: lower when the image would be larger than +/// [`MAX_PIXELS`], or have a side longer than the renderer draws (the image grows by a pixel on +/// each side and is rounded up to whole pixels). +fn raster_scale(rect: Rect, ppi: f64) -> f64 { + let scale = (ppi / 72.0).min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt()); + scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0)) +} + /// `n` at full opacity with Normal blending throughout (objects, fills and strokes). pub(super) fn opaque(n: &mut Node) { n.opacity = 1.0; @@ -621,7 +665,7 @@ pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Opt let mut roots = vec![]; for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) { let children = l.children().map_or(&[][..], Vec::as_slice); - roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible).map(|c| c.id)); + roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id)); } let plan = plan(doc, &roots, o, true)?; if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) { @@ -640,6 +684,8 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan // The groups replace their objects in one pass at the end. When an object is listed twice or // lies inside another listed one, each group replaces its objects as it is made instead. let one_pass = separate(d, &plan.flat.iter().flat_map(|f| f.roots.iter().copied()).collect::<Vec<_>>()); + // A sublayer that becomes flat art gives its ruler guides to the layer that held it. + let guides = held_guides(d, plan.flat.iter().flat_map(|f| f.roots.iter().copied())); for f in plan.flat { // A group always has objects. let Some(top) = place_of(d, &f.roots) else { continue }; @@ -703,6 +749,9 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan if !flat.is_empty() { d.insert_beside(flat, true)?; } + for (layer, guide) in guides { + d.insert(Some(layer), usize::MAX, guide)?; + } let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] }; for mut id in plan.kept { if o.text_to_outlines { @@ -747,6 +796,23 @@ fn place_of(d: &Document, roots: &[NodeId]) -> Option<NodeId> { Some(place.map_or(top, |(r, _)| *r)) } +/// The ruler guides of each of `roots` that is a sublayer (in its sublayers too), with the layer +/// that holds it, in order. Other objects hold none. +fn held_guides(d: &Document, roots: impl IntoIterator<Item = NodeId>) -> Vec<(NodeId, Node)> { + let mut out = vec![]; + for id in roots { + let (Some(n), Some(parent)) = (d.node(id), d.parent_of(id)) else { continue }; + if n.holds_ruler_guides() { + n.walk(&mut |c| { + if c.is_ruler_guide() { + out.push((parent, c.clone())); + } + }); + } + } + out +} + /// An image of `r` (in a clip group when it is clipped). fn raster_node(d: &mut Document, r: Raster) -> Node { let key = unique_key(d, "flattened"); @@ -829,3 +895,68 @@ fn drop_overprints(n: &mut Node) { } } } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + use crate::Session; + + #[test] + fn a_flattened_sublayer_gives_its_ruler_guides_to_its_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute("transparency.set", &json!({"ids": [r], "opacity": 50})).unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 5.0, artboard: None }); + let g = d.insert(Some(sub), usize::MAX, g).unwrap(); + let flat = flatten_document(&s.doc().unwrap().doc, &FlattenOptions::default()).unwrap().unwrap(); + assert!(flat.node(sub).is_none(), "the sublayer became flat art"); + assert!(flat.node(g).is_some_and(Node::is_ruler_guide), "its guide is kept"); + assert_eq!(flat.parent_of(g), Some(layer)); + assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g)); + } + + /// In a file without transparency with Clip Complex Regions on, art under a group's opaque + /// image within one of its pixels joins the group, also where a long image is made at a lower + /// resolution and its pixels are wider than at the preset's. + #[test] + fn art_under_the_edge_of_a_long_opaque_image_joins_its_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 31000, "height": 100})).unwrap(); + let rect = |s: &mut Session, x: f64, w: f64| { + let id = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": w, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [id]})).unwrap(); + NodeId(id) + }; + // 0.5 pt left of A: wider than a pixel at 300 ppi, narrower than one of a 30,000 pt image. + let d = rect(&mut s, 40.0, 19.5); + let a = rect(&mut s, 60.0, 40.0); + let t = rect(&mut s, 95.0, 30_000.0); + s.execute("transparency.set", &json!({"ids": [t.0], "opacity": 50})).unwrap(); + let o = FlattenOptions { no_transparency: Some(Default::default()), clip_complex_regions: true, ..FlattenOptions::default() }; + let doc = &s.doc().unwrap().doc; + let long = plan(doc, &[d, a, t], &o, false).unwrap(); + assert!(long.kept.is_empty(), "{:?}", long.kept); + assert_eq!(long.flat.iter().map(|f| f.roots.clone()).collect::<Vec<_>>(), vec![vec![d, a, t]]); + // Short, the image has 300 ppi pixels: D stays. + let short = rect(&mut s, 95.0, 40.0); + s.execute("transparency.set", &json!({"ids": [short.0], "opacity": 50})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(plan(doc, &[d, a, short], &o, false).unwrap().kept, vec![d]); + // 100,000 pt long, its pixels are over 3 pt wide: art 3 pt away, whose reach doesn't touch + // A's, joins too. + let far = rect(&mut s, 40.0, 17.0); + let longer = rect(&mut s, 95.0, 100_000.0); + s.execute("transparency.set", &json!({"ids": [longer.0], "opacity": 50})).unwrap(); + let doc = &s.doc().unwrap().doc; + let p = plan(doc, &[far, a, longer], &o, false).unwrap(); + assert!(p.kept.is_empty(), "{:?}", p.kept); + assert_eq!(p.flat.iter().map(|f| f.roots.clone()).collect::<Vec<_>>(), vec![vec![far, a, longer]]); + } +} diff --git a/crates/engine/src/cmd/flatten/report.rs b/crates/engine/src/cmd/flatten/report.rs index 3cac1ffe86..41b08b7a05 100644 --- a/crates/engine/src/cmd/flatten/report.rs +++ b/crates/engine/src/cmd/flatten/report.rs @@ -12,7 +12,9 @@ pub(super) fn target_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> { let mut ids = vec![]; for id in targets(s, p)? { match d.node(id) { - Some(n) if n.is_layer() => ids.extend(n.children().into_iter().flatten().map(|c| c.id)), + // Ruler guides are not art: they stay where they are. + Some(n) if n.is_layer() => ids.extend(n.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).map(|c| c.id)), + Some(n) if n.is_ruler_guide() => {} Some(_) => ids.push(id), None => {} } diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index 309347985c..0ccf1ab94a 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> { "Find Font Files", [], None, - "{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", + "{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links). With automation read roots, a reply leaves out the files found outside the caller's roots, and the folder when it is outside them (error then gives the reason without the path); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", always, find ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add Font Files", [], None, - "{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: the names Name.otf, Name 2.otf … Name 99.otf are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is kept; then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}", + "{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: the names Name.otf, Name 2.otf … Name 99.otf are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is kept; then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install. With automation read roots, folder is null when the Fonts folder is outside them, and a to or file path outside them is given as its file name; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}", always, add ), @@ -275,7 +275,9 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { /// Where the session's last search stands (`text.findFontFiles` without `folder`). fn state(s: &Session) -> Value { let Some(f) = &s.font_search else { return json!({ "state": "idle", "fonts": [] }) }; - let p = f.search.progress(); + let mut p = f.search.progress(); + // Only what the caller asking now may read: a search another caller started can hold more. + let (folder, error) = p.keep_readable(&f.folder); let mut files: Vec<Vec<String>> = vec![vec![]; f.fonts.len()]; for (path, items) in &p.hits { for i in items { @@ -293,16 +295,18 @@ fn state(s: &Session) -> Value { json!({ "family": font.family, "style": font.style, "status": font.status.as_str(), "files": files }) }) .collect(); - let folder = if p.folder.as_os_str().is_empty() { f.folder.clone() } else { p.folder.to_string_lossy().into_owned() }; let mut out = json!({ - "id": f.id, "state": p.state(), "folder": folder, "fonts": fonts, + "id": f.id, "state": p.state(), "fonts": fonts, "searched": { "folders": p.folders, "files": p.files, "fontFiles": p.read }, "skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0, }); + if let Some(folder) = folder { + out["folder"] = json!(folder); + } if let Some(why) = p.stopped() { out["stopped"] = json!(why); } - if let Some(e) = p.error() { + if let Some(e) = error { out["error"] = json!(e); } out @@ -348,12 +352,16 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // VectorCraft's own Fonts folder: no automation root applies to it. crate::file_access::unconfined(|| super::fileio::create_dir(&dir.to_string_lossy()))?; let report = copy_into(&files, dir); - let pairs = |v: &[(PathBuf, PathBuf)]| { - v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": to.to_string_lossy() })).collect::<Vec<_>>() + // The caller sees the Fonts folder and the copies in it only where its read roots reach. + let readable = |p: &Path| crate::file_access::current().is_none() || p.to_str().is_some_and(|p| crate::file_access::check_read(p).is_ok()); + let shown = |p: &Path| -> String { + let shown = if readable(p) { Some(p.as_os_str()) } else { p.file_name() }; + shown.map(|s| s.to_string_lossy().into_owned()).unwrap_or_default() }; + let pairs = |v: &[(PathBuf, PathBuf)]| v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": shown(to) })).collect::<Vec<_>>(); let mut out = json!({ - "folder": dir.to_string_lossy(), "copied": pairs(&report.copied), "kept": pairs(&report.kept), - "skipped": report.skipped.iter().map(|(file, why)| json!({ "file": file.to_string_lossy(), "reason": why })).collect::<Vec<_>>(), + "folder": readable(dir).then(|| dir.to_string_lossy()), "copied": pairs(&report.copied), "kept": pairs(&report.kept), + "skipped": report.skipped.iter().map(|(file, why)| json!({ "file": shown(file), "reason": why })).collect::<Vec<_>>(), }); if !report.copied.is_empty() || !report.kept.is_empty() { // The fonts are cataloged and type set in them redraws, as Refresh Font List does it. diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8a3485c499..9003e325a9 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial: the extent ellipse's height / width; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)", has_doc, set_gradient_geom ), @@ -118,7 +118,7 @@ type Parsed<T> = std::result::Result<T, String>; /// Parse a kind name. fn parse_kind(k: &str) -> Parsed<GradientKind> { - GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, freeform)")) + GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform)")) } /// The `method` param of `p`, if given: how the colours between the stops mix. @@ -274,9 +274,16 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> { gp.angle = f64_or(g, "angle", 0.0); gp.swatch = str_param(g, "swatch").map(str::to_string); let geom = GeomEdit::parse(g)?; + let aspect = geom.aspect.map(|a| aspect_for(kind, a)).transpose()?; + if matches!(kind, GradientKind::Conic | GradientKind::Diamond) { + no_focal(&geom)?; + } if let Some((start, end)) = geom.vector { - let mut g = GradientGeom { start, end, aspect: geom.aspect.unwrap_or(1.0), focal: None }; - g.set_focal(geom.focal.flatten()); + let mut g = GradientGeom { start, end, aspect: aspect.unwrap_or(1.0), focal: None }; + // Only a radial gradient has a focal point (as `paint.setGradientGeom` keeps it). + if kind == GradientKind::Radial { + g.set_focal(geom.focal.flatten()); + } gp.angle = g.angle_deg(); gp.geom = Some(g); } @@ -286,13 +293,36 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> { Ok(gp) } -/// The `aspect` param (a percentage) as a ratio. +/// The `aspect` param (a percentage) as a ratio of 0.005 to 327.67, its sign kept: a negative one +/// mirrors a conic gradient's sweep ([`aspect_for`]). fn aspect_param(p: &Value) -> Parsed<Option<f64>> { p.get("aspect") - .map(|v| v.as_f64().map(|a| (a / 100.0).clamp(0.005, 327.67)).ok_or_else(|| "`aspect` must be a number (%)".to_string())) + .map(|v| { + v.as_f64() + .filter(|a| a.is_finite()) + .map(|a| (a.abs() / 100.0).clamp(0.005, 327.67).copysign(a)) + .ok_or_else(|| "`aspect` must be a number (%)".to_string()) + }) .transpose() } +/// Aspect ratio `a` ([`aspect_param`]) for a gradient of `kind`: a negative one mirrors a conic's +/// sweep, and is an error for the other kinds. +fn aspect_for(kind: GradientKind, a: f64) -> Parsed<f64> { + if a < 0.0 && kind != GradientKind::Conic { + return Err("a negative `aspect` applies to conic gradients".into()); + } + Ok(a) +} + +/// An error when `e` gives a focal point: a conic or diamond gradient has none (`null` is allowed). +fn no_focal(e: &GeomEdit) -> Parsed<()> { + match e.focal { + Some(Some(_)) => Err("`focal` applies to radial gradients".into()), + _ => Ok(()), + } +} + /// `paint` without the placement it had on the art it came from (a swatch, or the default paint /// for new art): a placed gradient keeps its angle and fits each object it lands on (freeform /// points are placed afresh, coloured along the stops, which follow the points' colours). @@ -400,7 +430,7 @@ fn apply_gradient_edit_in_model( if let Some(g) = &mut gp.geom { let r = a.to_radians(); let dir = vectorcraft_geom::Vec2::new(r.cos(), -r.sin()); - if gp.gradient.kind == GradientKind::Radial { + if gp.gradient.kind.is_centered() { g.end = g.start + dir * g.length(); } else { let c = g.start.midpoint(g.end); @@ -411,6 +441,7 @@ fn apply_gradient_edit_in_model( } } if let Some(asp) = aspect_param(p)? { + let asp = aspect_for(gp.gradient.kind, asp)?; if gp.geom.is_none() && let Some(b) = bounds { @@ -472,7 +503,20 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> { let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?; // Validate against the defaults first so bad params fail without touching the document. let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() }; - let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(p, &default_paint, &stored), None, &|_| true, model) + // A negative aspect for selected conic gradients gives a default of another kind its size. + let default_kind = str_param(p, "kind").and_then(GradientKind::parse).or(match &default_paint { + Paint::Gradient(g) => Some(g.gradient.kind), + _ => None, + }); + let for_default = match p.get("aspect").and_then(Value::as_f64) { + Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => { + let mut q = p.clone(); + q["aspect"] = json!(-a); + std::borrow::Cow::Owned(q) + } + _ => std::borrow::Cow::Borrowed(p), + }; + let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model) .map_err(|e| bad(C, e))?; let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| { @@ -599,11 +643,23 @@ impl GeomEdit { /// `cur` with the vector, aspect and focal point of `e` (given in the document). `to_doc` maps /// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits -/// an unplaced gradient, so what the document shows carries over where `e` keeps it. -fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>, model: Option<vectorcraft_color::cms::Model>) -> Option<Paint> { - let from_doc = invert(to_doc)?; +/// an unplaced gradient, so what the document shows carries over where `e` keeps it. An error +/// when `e` gives what the gradient's kind can't take (a negative aspect other than a conic's, or +/// a conic's or diamond's focal point). +fn vector_paint( + cur: &Paint, + e: &GeomEdit, + to_doc: Affine, + bounds: Option<Rect>, + model: Option<vectorcraft_color::cms::Model>, +) -> Parsed<Option<Paint>> { let mut gp = gradient_for_edit(cur, model); let kind = gp.gradient.kind; + let edit_aspect = e.aspect.map(|a| aspect_for(kind, a)).transpose()?; + if matches!(kind, GradientKind::Conic | GradientKind::Diamond) { + no_focal(e)?; + } + let Some(from_doc) = invert(to_doc) else { return Ok(None) }; let map = |mut g: GradientGeom, a: Affine| { if a != Affine::IDENTITY { g.transform(a, kind); @@ -611,8 +667,8 @@ fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>, g }; let shown = gp.geom.or_else(|| bounds.map(|b| gp.resolve(b))).map(|g| map(g, to_doc)); - let (start, end) = e.vector.or_else(|| shown.map(|g| (g.start, g.end)))?; - let aspect = e.aspect.or_else(|| shown.map(|g| g.aspect)).unwrap_or(1.0); + let Some((start, end)) = e.vector.or_else(|| shown.map(|g| (g.start, g.end))) else { return Ok(None) }; + let aspect = edit_aspect.or_else(|| shown.map(|g| g.aspect)).unwrap_or(1.0); let mut geom = GradientGeom { start, end, aspect, focal: None }; match (e.focal, shown) { _ if kind != GradientKind::Radial => {} @@ -623,7 +679,7 @@ fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>, let geom = map(geom, from_doc); gp.angle = geom.angle_deg(); gp.geom = Some(geom); - Some(Paint::Gradient(Box::new(gp))) + Ok(Some(Paint::Gradient(Box::new(gp)))) } fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> { @@ -658,14 +714,15 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> { run_stroke_weight(&mut r.style); } let (paint, b) = run_paint_mut(r, stroke, lb); - if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model) { + if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model).map_err(|e| bad(C, e))? { *paint = np; } } return Ok(()); } let b = item_paint_bounds(n, index, !stroke); - if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b, model) { + let cur = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None); + if let Some(np) = vector_paint(cur, &edit, Affine::IDENTITY, b, model).map_err(|e| bad(C, e))? { n.appearance.set_paint_at(index, !stroke, np); } Ok(()) diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index 2f69a9df39..d27809fa78 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -109,6 +109,40 @@ fn unlinked(g: &Gradient) -> Gradient { g } +/// Give each saved preset in `saved` a name no built-in preset or earlier saved one has (any case): +/// a clash becomes the first free "<name> N", N from 2. Returns the renames as (old, new). +pub(crate) fn rename_clashing_presets(saved: &mut [GradientPreset]) -> Vec<(String, String)> { + if saved.is_empty() { + return vec![]; + } + let builtin: std::collections::HashSet<String> = builtin_presets().map(|e| e.name.to_ascii_lowercase()).collect(); + let mut taken: std::collections::HashSet<String> = + builtin.iter().cloned().chain(saved.iter().map(|p| p.name.trim().to_ascii_lowercase())).collect(); + let mut kept = std::collections::HashSet::new(); + // The next suffix to try for each name, so many presets with one name take linear time. + let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new(); + let mut renamed = vec![]; + for p in saved { + let key = p.name.trim().to_ascii_lowercase(); + if !builtin.contains(&key) && kept.insert(key.clone()) { + continue; + } + let base = p.name.trim(); + let n = next.entry(key).or_insert(2); + let name = loop { + let candidate = format!("{base} {n}"); + *n += 1; + if !taken.contains(&candidate.to_ascii_lowercase()) { + break candidate; + } + }; + taken.insert(name.to_ascii_lowercase()); + kept.insert(name.to_ascii_lowercase()); + renamed.push((std::mem::replace(&mut p.name, name.clone()), name)); + } + renamed +} + impl Session { /// The Gradient panel's presets: the built-in ones by library, then the saved ones. pub fn gradient_presets(&self) -> Vec<GradientPresetEntry> { diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f4b6c90c13..2c42494160 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -17,7 +17,9 @@ use vectorcraft_doc::{ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; use super::typecmd::refresh_bounds; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, f64_or, f64_req, has_doc, has_selection, named_id, ok, str_param}; +use super::{ + CommandSpec, EngineError, Result, Session, bad, cmd, f64_req, has_doc, has_selection, named_id, number_or, ok, str_param, switch_or, text_param, +}; mod axis; mod columns; diff --git a/crates/engine/src/cmd/graph/axis.rs b/crates/engine/src/cmd/graph/axis.rs index 47858d3951..b805efb432 100644 --- a/crates/engine/src/cmd/graph/axis.rs +++ b/crates/engine/src/cmd/graph/axis.rs @@ -1,4 +1,4 @@ -use super::{GraphSpec, Value}; +use super::{GraphSpec, Result, Value, bad}; pub(super) const LABEL_SIZE: f64 = 9.0; @@ -22,6 +22,16 @@ pub(super) fn count_param(p: &Value, key: &str, max: u64) -> Option<usize> { usize::try_from(n.min(max)).ok() } +/// [`count_param`], or `None` when `p` leaves `key` out or gives null. A negative number is an error, and so is any +/// other value, such as `"5"`. +pub(super) fn count_given(p: &Value, key: &str, max: u64, cmd: &str) -> Result<Option<usize>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) if !v.is_number() => Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), + Some(_) => count_param(p, key, max).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be 0 or more"))), + } +} + /// A "nice" axis: (min, max, step). pub(super) fn nice_axis(lo: f64, hi: f64, ticks: usize) -> (f64, f64, f64) { let (lo, hi) = if (hi - lo).abs() < 1e-12 { (lo.min(0.0), lo.max(0.0) + 1.0) } else { (lo, hi) }; diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 5df961ee38..7084fe19f6 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Graph", [], None, - "{type: column|stackedColumn|bar|stackedBar|line|area|scatter|pie|radar, x, y, width, height, series?: [..], categories?: [..], rows?: [[number|null]], csv?} → {id}; an empty CSV cell or a null is a blank value, a number in straight quotes is a label", + "{type: column|stackedColumn|bar|stackedBar|line|area|scatter|pie|radar, x, y, width, height, series?: [..], categories?: [..], rows?: [[number|null]], csv?} → {id}; an empty CSV cell or a null is a blank value, a number in straight quotes is a label; a `type` that is not a string, a `width` or `height` that is not a number, and data of the wrong type (as `graph.setData` reads it) are refused", has_doc, create ), @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Data…", ["Object", "Graph"], None, - "{id?, series?, categories?, rows?, csv?: first row = series labels (first cell empty); then one row per category: label; values…; an empty cell or a null is a blank value; a quoted number a label; a `|` in a label a line break, transpose?: true swaps rows and columns (Transpose row/column), switchXY?: true swaps each scatter series' y and x columns (Switch x/y)} replace the graph's data; no data → the current {csv, series, categories, rows}", + "{id?, series?, categories?, rows?, csv?: first row = series labels (first cell empty); then one row per category: label; values…; an empty cell or a null is a blank value; a quoted number a label; a `|` in a label a line break, transpose?: true swaps rows and columns (Transpose row/column), switchXY?: true swaps each scatter series' y and x columns (Switch x/y)} replace the graph's data; a `csv` that is not a string, `series` or `categories` that are not lists, `rows` that are not lists of numbers and nulls, or a `transpose` or `switchXY` that is not true or false is refused and the graph stays as it was; no data → the current {csv, series, categories, rows}", has_selection, set_data ), @@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> { "Type…", ["Object", "Graph"], None, - "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?, axisMax?, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); no options → the current ones", + "{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones", has_selection, set_type ), diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index f4eb3ef83c..f7f672325e 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -1,6 +1,6 @@ use super::edit::{regenerate, spec_of, target}; use super::series::{switch_xy, transpose}; -use super::{Document, EngineError, GraphKind, GraphSpec, NodeId, Result, Session, Value, bad, bool_or, json, str_param}; +use super::{Document, EngineError, GraphKind, GraphSpec, NodeId, Result, Session, Value, bad, json, switch_or, text_param}; // ---------- data ---------- @@ -101,7 +101,7 @@ pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0))); }; let mut spec = current.clone(); - apply_data(&mut spec, &json!({ "csv": csv })); + apply_data(&mut spec, &json!({ "csv": csv }), "graph.applyCsv")?; keep_right_series(&mut spec); if spec == *current { return Ok(()); @@ -115,34 +115,58 @@ fn keep_right_series(g: &mut GraphSpec) { g.right_series.retain(|i| *i < count); } -pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool { +/// Apply the data `p` gives (`csv`, `series`, `categories`, `rows`) to `g`; true when it gave any. A null is read as a +/// key left out. A `csv` that is not a string, a `series` or `categories` that is not a list, and `rows` that are not +/// lists of numbers and nulls are errors, and `g` is left as it was. +pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool> { + let list = |key: &str| -> Result<Option<&Vec<Value>>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) => Ok(Some(a)), + Some(v) => Err(bad(cmd, format!("`{key}` must be a list, not {v}"))), + } + }; + let csv = text_param(p, "csv", cmd)?; + let strings = |a: &Vec<Value>| a.iter().map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).collect::<Vec<_>>(); + let series = list("series")?.map(strings); + let categories = list("categories")?.map(strings); + // A null is a blank cell. + let rows = list("rows")? + .map(|rows| { + rows.iter() + .map(|r| { + let bad_row = || bad(cmd, format!("`rows` must be lists of numbers or nulls, not {r}")); + r.as_array() + .ok_or_else(bad_row)? + .iter() + .map(|v| if v.is_null() { Ok(None) } else { v.as_f64().map(|v| Some(v).filter(|v| v.is_finite())).ok_or_else(bad_row) }) + .collect::<Result<Vec<_>>>() + }) + .collect::<Result<Vec<_>>>() + }) + .transpose()?; let mut changed = false; - if let Some(csv) = str_param(p, "csv") { + if let Some(csv) = csv { let (s, c, r) = parse_csv(csv); g.series = s; g.categories = c; g.set_cells(r); changed = true; } - let strings = - |v: &Value| v.as_array().map(|a| a.iter().map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).collect::<Vec<_>>()); - if let Some(s) = p.get("series").and_then(strings) { + if let Some(s) = series { g.series = s; changed = true; } - if let Some(c) = p.get("categories").and_then(strings) { + if let Some(c) = categories { g.categories = c; changed = true; } - if let Some(rows) = p.get("rows").and_then(Value::as_array) { - // `null` (or anything that isn't a finite number) is a blank cell. - g.set_cells( - rows.iter().map(|r| r.as_array().map(|a| a.iter().map(|v| v.as_f64().filter(|v| v.is_finite())).collect()).unwrap_or_default()).collect(), - ); + if let Some(rows) = rows { + g.set_cells(rows); changed = true; } drop_empty_rows(g); - changed + Ok(changed) } /// Drop rows with neither a value nor a label; a label-only row stays, its values blank. Each kept row keeps its own @@ -184,13 +208,13 @@ pub(super) fn set_data(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "graph.setData"; let id = target(s, p, C)?; let mut spec = spec_of(s, id)?; - let flip = bool_or(p, "transpose", false); - let swap = bool_or(p, "switchXY", false); + let flip = switch_or(p, "transpose", false, C)?; + let swap = switch_or(p, "switchXY", false, C)?; if swap && spec.kind != GraphKind::Scatter { return Err(bad(C, "Switch x/y is for scatter graphs")); } // Transpose and Switch x/y act after any new data in the same call. - let changed = apply_data(&mut spec, p); + let changed = apply_data(&mut spec, p, C)?; if flip { // The categories become series: at most as many as a graph has series. if spec.cells().len() > vectorcraft_doc::MAX_GRAPH_SERIES { diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index c33be78d5a..c7f6d52ea8 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -1,12 +1,22 @@ -use super::axis::{MAX_TICK_MARKS, count_param, one_line}; +use super::axis::{MAX_TICK_MARKS, count_given, one_line}; use super::data::apply_data; use super::generate::{children_bounds, generate}; use super::series::{picked_series, reselect_series}; use super::{ - Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, bool_or, f64_or, - f64_req, json, named_id, str_param, + Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, f64_req, json, + named_id, number_or, switch_or, text_param, }; +/// An axis bound `p` gives for `key`: `None` when left out, `Some(None)` for null (calculated from the data), or the +/// number. Any other value, such as `"10"`, is an error. +fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> { + match p.get(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(v) => v.as_f64().map(|x| Some(Some(x))).ok_or_else(|| bad(cmd, format!("`{key}` must be a number or null, not {v}"))), + } +} + /// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last /// generation, which is recorded in the spec's `placed` bounds). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { @@ -33,12 +43,14 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "graph.create"; - let kind = - str_param(p, "type").map(|t| GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))).transpose()?.unwrap_or_default(); + let kind = text_param(p, "type", C)? + .map(|t| GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))) + .transpose()? + .unwrap_or_default(); let (x, y) = (f64_req(p, "x", C)?, f64_req(p, "y", C)?); - let (w, h) = (f64_or(p, "width", 200.0).abs().max(1.0), f64_or(p, "height", 150.0).abs().max(1.0)); + let (w, h) = (number_or(p, "width", 200.0, C)?.abs().max(1.0), number_or(p, "height", 150.0, C)?.abs().max(1.0)); let mut spec = GraphSpec { kind, rect: Rect::new(x, y, x + w, y + h), ..GraphSpec::default() }; - if !apply_data(&mut spec, p) { + if !apply_data(&mut spec, p, C)? { // Starter data so the new graph shows something (edit it with Object → Graph → Data…). spec.series = vec!["Series 1".into(), "Series 2".into()]; spec.categories = vec!["A".into(), "B".into(), "C".into(), "D".into()]; @@ -150,7 +162,8 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { spec.right_series.retain(|i| *i < count); spec.right_series.sort_unstable(); spec.right_series.dedup(); - if p.get("seriesIndexes").is_some() && str_param(p, "type").is_none() && str_param(p, "valueAxis").is_none() { + let (new_type, new_axis) = (text_param(p, "type", C)?, text_param(p, "valueAxis", C)?); + if p.get("seriesIndexes").is_some() && new_type.is_none() && new_axis.is_none() { return Err(bad(C, "`seriesIndexes` needs a `type` or a `valueAxis`")); } let picked = picked_series(s, p, id, count, C)?; @@ -196,7 +209,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { } // Series picked with Group Selection stay selected through the regeneration (their groups are new nodes). let reselect: Vec<u32> = if p.get("seriesIndexes").is_none() { picked.iter().filter_map(|i| u32::try_from(*i).ok()).collect() } else { vec![] }; - if let Some(t) = str_param(p, "type") { + if let Some(t) = new_type { let kind = GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))?; if picked.is_empty() { spec.kind = kind; @@ -215,7 +228,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { } } } - if let Some(v) = str_param(p, "valueAxis") { + if let Some(v) = new_axis { let side = ValueAxisSide::parse(v).ok_or_else(|| bad(C, format!("unknown value axis `{v}` (left, right or both)")))?; if picked.is_empty() { spec.value_axis = side; @@ -231,54 +244,58 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { } } } - spec.separate_scales = bool_or(p, "separateScales", spec.separate_scales); + spec.separate_scales = switch_or(p, "separateScales", spec.separate_scales, C)?; for (key, slot) in [ ("tickLength", &mut spec.tick_length), ("rightTickLength", &mut spec.right_tick_length), ("categoryTickLength", &mut spec.category_tick_length), ] { - if let Some(v) = str_param(p, key) { + if let Some(v) = text_param(p, key, C)? { *slot = TickLength::parse(v).ok_or_else(|| bad(C, format!("unknown {key} `{v}` (none, short or full)")))?; } } for (key, slot) in [("tickMarks", &mut spec.tick_marks), ("rightTickMarks", &mut spec.right_tick_marks), ("categoryTickMarks", &mut spec.category_tick_marks)] { - *slot = count_param(p, key, MAX_TICK_MARKS as u64).map_or(*slot, |n| n.max(1)); + *slot = count_given(p, key, MAX_TICK_MARKS as u64, C)?.map_or(*slot, |n| n.max(1)); } - spec.ticks_between_labels = bool_or(p, "ticksBetweenLabels", spec.ticks_between_labels); - if let Some(v) = str_param(p, "piePosition") { + spec.ticks_between_labels = switch_or(p, "ticksBetweenLabels", spec.ticks_between_labels, C)?; + if let Some(v) = text_param(p, "piePosition", C)? { spec.pie_position = vectorcraft_doc::PiePosition::parse(v).ok_or_else(|| bad(C, format!("unknown piePosition `{v}` (even, ratio or stacked)")))?; } - if let Some(v) = str_param(p, "pieSort") { + if let Some(v) = text_param(p, "pieSort", C)? { spec.pie_sort = vectorcraft_doc::PieSort::parse(v).ok_or_else(|| bad(C, format!("unknown pieSort `{v}` (none, all or first)")))?; } for (key, slot) in [("prefix", &mut spec.prefix), ("suffix", &mut spec.suffix), ("rightPrefix", &mut spec.right_prefix), ("rightSuffix", &mut spec.right_suffix)] { - if let Some(v) = str_param(p, key) { + if let Some(v) = text_param(p, key, C)? { // A label, not a paragraph: one line, at most MAX_AFFIX characters. *slot = one_line(v); } } - spec.right_ticks = count_param(p, "rightTicks", 100).unwrap_or(spec.right_ticks); - if let Some(v) = p.get("rightAxisMin") { - spec.right_axis_min = v.as_f64(); + spec.right_ticks = count_given(p, "rightTicks", 100, C)?.unwrap_or(spec.right_ticks); + for (key, slot) in [ + ("rightAxisMin", &mut spec.right_axis_min), + ("rightAxisMax", &mut spec.right_axis_max), + ("axisMin", &mut spec.axis_min), + ("axisMax", &mut spec.axis_max), + ] { + if let Some(v) = bound_param(p, key, C)? { + *slot = v; + } } - if let Some(v) = p.get("rightAxisMax") { - spec.right_axis_max = v.as_f64(); - } - spec.column_width = f64_or(p, "columnWidth", spec.column_width).clamp(1.0, 1000.0); - spec.cluster_width = f64_or(p, "clusterWidth", spec.cluster_width).clamp(1.0, 1000.0); - spec.legend = bool_or(p, "legend", spec.legend); - spec.drop_shadow = bool_or(p, "dropShadow", spec.drop_shadow); - spec.first_row_in_front = bool_or(p, "firstRowInFront", spec.first_row_in_front); - spec.first_column_in_front = bool_or(p, "firstColumnInFront", spec.first_column_in_front); - spec.filled_lines = bool_or(p, "filledLines", spec.filled_lines); - spec.legend_across_top = bool_or(p, "legendAcrossTop", spec.legend_across_top); + spec.column_width = number_or(p, "columnWidth", spec.column_width, C)?.clamp(1.0, 1000.0); + spec.cluster_width = number_or(p, "clusterWidth", spec.cluster_width, C)?.clamp(1.0, 1000.0); + spec.legend = switch_or(p, "legend", spec.legend, C)?; + spec.drop_shadow = switch_or(p, "dropShadow", spec.drop_shadow, C)?; + spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?; + spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?; + spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?; + spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?; // After `legend`, which the Graph Type dialog sends too. - if let Some(v) = str_param(p, "pieLegend") { + if let Some(v) = text_param(p, "pieLegend", C)? { (spec.legend, spec.pie_legend_in_wedges) = match v.to_ascii_lowercase().as_str() { "none" => (false, false), "standard" => (true, false), @@ -286,16 +303,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> { _ => return Err(bad(C, format!("unknown pieLegend `{v}` (none, standard or wedges)"))), }; } - spec.mark_points = bool_or(p, "markPoints", spec.mark_points); - spec.connect_points = bool_or(p, "connectPoints", spec.connect_points); - spec.edge_to_edge = bool_or(p, "edgeToEdge", spec.edge_to_edge); - spec.ticks = count_param(p, "ticks", 100).unwrap_or(spec.ticks); - if let Some(v) = p.get("axisMin") { - spec.axis_min = v.as_f64(); - } - if let Some(v) = p.get("axisMax") { - spec.axis_max = v.as_f64(); - } + spec.mark_points = switch_or(p, "markPoints", spec.mark_points, C)?; + spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?; + spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?; + spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks); let label = format!("{} Graph", spec.kind.label()); s.edit("Graph Type", |d, sel| { regenerate(d, id, spec)?; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index efcd043208..aef1918a6d 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -2638,9 +2638,12 @@ fn counts_come_back_from_the_dialog_as_floats_and_are_capped() { s.execute("graph.setType", &json!({"tickMarks": 3.0, "ticks": 4.0, "categoryTickMarks": 2.6})).unwrap(); let g = spec(&s, id); assert_eq!((g.tick_marks, g.ticks, g.category_tick_marks), (3, 4, 3)); - s.execute("graph.setType", &json!({"categoryTickMarks": 0, "rightTickMarks": 1e300, "rightTicks": -2.0})).unwrap(); + s.execute("graph.setType", &json!({"categoryTickMarks": 0, "rightTickMarks": 1e300})).unwrap(); let g = spec(&s, id); assert_eq!((g.category_tick_marks, g.right_tick_marks, g.right_ticks), (1, 20, 0)); + // A negative count is refused. + s.execute("graph.setType", &json!({"rightTicks": -2.0})).unwrap_err(); + assert_eq!(spec(&s, id).right_ticks, 0); // A file's values come back as drawn. let mut fields = s.execute("graph.setType", &json!({})).unwrap(); assert_eq!(fields["rightTickMarks"], 20); @@ -4498,3 +4501,93 @@ fn a_legend_label_with_kept_negative_space_before_stays_below_the_entry_above_it let (first, next) = (bounds("2024"), bounds("20\n25")); assert!(next.y0 >= first.y1, "the second legend label starts below the first one: {first:?} {next:?}"); } + +/// A graph command given a value of the wrong type refuses it, naming the key, and leaves the graph and the undo +/// history as they were; a null axis bound still goes back to the calculated value. +#[test] +fn graph_commands_refuse_params_of_the_wrong_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "line"); + s.execute("graph.setType", &json!({"id": id.0, "axisMin": 0, "axisMax": 10})).unwrap(); + let spec = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().extras().graph.as_deref().cloned().unwrap(); + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + let (before, steps) = (spec(&s), undo_len(&s)); + let refused = |s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str| { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{cmd} {p}: {e}"); + }; + for (key, v, msg) in [ + ("axisMin", json!("10"), "`axisMin` must be a number or null, not \"10\""), + ("axisMax", json!(true), "`axisMax` must be a number or null"), + ("rightAxisMin", json!([1]), "`rightAxisMin` must be a number or null"), + ("rightAxisMax", json!({}), "`rightAxisMax` must be a number or null"), + ("columnWidth", json!("50"), "`columnWidth` must be a number, not \"50\""), + ("clusterWidth", json!(false), "`clusterWidth` must be a number"), + ("ticks", json!("5"), "`ticks` must be a number, not \"5\""), + ("ticks", json!(-2), "`ticks` must be 0 or more"), + ("rightTicks", json!("5"), "`rightTicks` must be a number"), + ("tickMarks", json!("2"), "`tickMarks` must be a number"), + ("rightTickMarks", json!(-1), "`rightTickMarks` must be 0 or more"), + ("categoryTickMarks", json!(true), "`categoryTickMarks` must be a number"), + ("legend", json!("false"), "`legend` must be true or false"), + ("markPoints", json!(0), "`markPoints` must be true or false"), + ("connectPoints", json!("no"), "`connectPoints` must be true or false"), + ("edgeToEdge", json!(1), "`edgeToEdge` must be true or false"), + ("separateScales", json!("true"), "`separateScales` must be true or false"), + ("ticksBetweenLabels", json!(1), "`ticksBetweenLabels` must be true or false"), + ("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"), + ("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"), + ("filledLines", json!("on"), "`filledLines` must be true or false"), + ("dropShadow", json!(1), "`dropShadow` must be true or false"), + ("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"), + ("type", json!(5), "`type` must be a string"), + ("valueAxis", json!(true), "`valueAxis` must be a string"), + ("tickLength", json!(1), "`tickLength` must be a string"), + ("rightTickLength", json!(1), "`rightTickLength` must be a string"), + ("categoryTickLength", json!(1), "`categoryTickLength` must be a string"), + ("prefix", json!(1), "`prefix` must be a string"), + ("suffix", json!(true), "`suffix` must be a string"), + ("rightPrefix", json!([]), "`rightPrefix` must be a string"), + ("rightSuffix", json!(2), "`rightSuffix` must be a string"), + ("pieLegend", json!(1), "`pieLegend` must be a string"), + ("piePosition", json!(1), "`piePosition` must be a string"), + ("pieSort", json!(1), "`pieSort` must be a string"), + ] { + refused(&mut s, "graph.setType", json!({"id": id.0, key: v}), msg); + } + for (key, v, msg) in [ + ("csv", json!(5), "`csv` must be a string"), + ("series", json!("a"), "`series` must be a list, not \"a\""), + ("categories", json!({}), "`categories` must be a list"), + ("rows", json!("1,2"), "`rows` must be a list"), + ("rows", json!([1, 2]), "`rows` must be lists of numbers or nulls, not 1"), + ("rows", json!([[1, "2"]]), "`rows` must be lists of numbers or nulls"), + ("transpose", json!("true"), "`transpose` must be true or false"), + ("switchXY", json!(1), "`switchXY` must be true or false"), + ] { + refused(&mut s, "graph.setData", json!({"id": id.0, key: v}), msg); + } + assert_eq!(spec(&s), before); + assert_eq!(undo_len(&s), steps); + let count = |s: &Session| s.doc().unwrap().doc.node_count(); + let objects = count(&s); + for (key, v, msg) in [ + ("type", json!(1), "`type` must be a string"), + ("width", json!("300"), "`width` must be a number, not \"300\""), + ("height", json!(true), "`height` must be a number"), + ("csv", json!(1), "`csv` must be a string"), + ("rows", json!([[true]]), "`rows` must be lists of numbers or nulls"), + ] { + let mut p = json!({"type": "column", "x": 0, "y": 0, "width": 100, "height": 100}); + p[key] = v; + refused(&mut s, "graph.create", p, msg); + } + assert_eq!((count(&s), undo_len(&s)), (objects, steps)); + // A null is a key left out, except for an axis bound, where it goes back to the calculated value. + s.execute("graph.setType", &json!({"id": id.0, "legend": null, "ticks": null, "prefix": null, "axisMin": null})).unwrap(); + assert_eq!(spec(&s).axis_min, None); + assert_eq!(spec(&s).axis_max, Some(10.0)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, null], [2, 3]], "series": null, "transpose": null})).unwrap(); + assert_eq!(spec(&s).cells(), vec![vec![Some(1.0), None], vec![Some(2.0), Some(3.0)]]); +} diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index bd6afd4663..b54e92932c 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -11,7 +11,7 @@ use vectorcraft_doc::Node; use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes}; use super::edit::selected_roots; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, color_value, f64_or, has_selection, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param}; pub fn specs() -> Vec<CommandSpec> { vec![cmd!( @@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -27,28 +27,28 @@ pub fn specs() -> Vec<CommandSpec> { fn halftone(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.vectorHalftone"; - let shape = match str_param(p, "shape") { + let shape = match text_param(p, "shape", C)? { Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?, None => DotShape::Circle, }; - let frequency = f64_or(p, "frequency", 20.0); + let frequency = number_or(p, "frequency", 20.0, C)?; if !(1.0..=300.0).contains(&frequency) { return Err(bad(C, "frequency must be between 1 and 300 lines per inch")); } - let angle = f64_or(p, "angle", 45.0); + let angle = number_or(p, "angle", 45.0, C)?; if !angle.is_finite() { return Err(bad(C, "invalid angle")); } - let mono = match str_param(p, "mode").unwrap_or("mono") { + let mono = match text_param(p, "mode", C)?.unwrap_or("mono") { "mono" => true, "cmyk" => false, other => return Err(bad(C, format!("unknown mode `{other}` (mono|cmyk)"))), }; let color = match p.get("color") { + None | Some(Value::Null) => Color::BLACK, Some(v) => color_value(v).ok_or_else(|| bad(C, "invalid color"))?, - None => Color::BLACK, }; - let (invert, clip, keep) = (bool_or(p, "invert", false), bool_or(p, "clip", true), bool_or(p, "keepOriginal", false)); + let (invert, clip, keep) = (switch_or(p, "invert", false, C)?, switch_or(p, "clip", true, C)?, switch_or(p, "keepOriginal", false, C)?); let ht = Halftone { shape, frequency, angle, mono, color, from_art: false, invert, clip }; let roots = selected_roots(s)?; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 07571ad320..593d325460 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -15,7 +15,7 @@ use vectorcraft_geom::{Affine, Rect}; use super::{ CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc, - has_selection, id_param, ids_param, index, ok, str_param, switch_or, + has_selection, ids_param, index, object_param, ok, str_param, switch_or, }; use crate::EngineError; @@ -243,7 +243,8 @@ pub(crate) fn accepts(d: &Document, parent: Option<NodeId>, n: &Node) -> bool { None => n.is_layer(), Some(p) => match d.node(p).map(|x| &x.kind) { Some(NodeKind::Layer { .. }) => true, - Some(NodeKind::Group { .. }) => !n.is_layer(), + // A ruler guide stays directly in a layer or sublayer. + Some(NodeKind::Group { .. }) => !n.is_layer() && !n.is_ruler_guide(), _ => false, }, } @@ -425,7 +426,7 @@ fn paste_remembers_layers(s: &mut Session, p: &Value) -> Result<Value> { /// The Layers panel's target circle. fn target(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.target"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let st = s.doc()?; let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; if !st.doc.is_editable(id) { @@ -478,8 +479,12 @@ fn clip_toggle(s: &mut Session, p: &Value) -> Result<Value> { super::object::release_clip(d, id); return Ok(false); } - let top = - n.children().and_then(|c| c.last()).map(|c| c.id).ok_or_else(|| EngineError::Other("the layer has no objects to clip by".into()))?; + // The topmost object: a layer's ruler guides above its art do not clip. + let top = n + .children() + .and_then(|c| c.iter().rev().find(|c| !c.is_ruler_guide())) + .map(|c| c.id) + .ok_or_else(|| EngineError::Other("the layer has no objects to clip by".into()))?; super::object::make_clipping_path(d, top)?; d.move_node(top, Some(id), 0)?; if let Some(n) = d.node_mut(id) { @@ -556,9 +561,8 @@ fn delete_rows(s: &mut Session, p: &Value) -> Result<Value> { return Err(EngineError::Other("a document needs at least one layer".into())); } s.edit("Delete Selection", |d, sel| { - d.remove_many(&ids)?; // The guides on the deleted layers go with them. - d.drop_guides_of_deleted_layers(sel); + d.remove_many(&ids)?; sel.prune(d); Ok(()) })?; @@ -577,10 +581,10 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad("layer.duplicate", "no such rows")); } let copies = s.edit("Duplicate Selection", |d, _| { - super::edit::copy_above(d, &ids, |d, n, c| { + // A copied layer's ruler guides are copied with it. + super::edit::copy_above(d, &ids, |_, n, c| { if n.is_layer() { c.name = Some(format!("{} copy", n.display_name())); - d.copy_layer_guides(n, c); } }) })?; @@ -590,7 +594,7 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> { fn set_current(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.setCurrent"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let st = s.doc_mut()?; let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?; st.active_layer = Some(layer); @@ -696,7 +700,7 @@ fn in_isolation(doc: &Document, isolation: Option<NodeId>, id: NodeId) -> bool { /// The selection column: select a row's art. fn select_art(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.selectAll"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let add = switch_or(p, "add", false, C)?; let st = s.doc()?; let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -706,6 +710,9 @@ fn select_art(s: &mut Session, p: &Value) -> Result<Value> { vec![] } else if n.is_layer() { n.layer_art(true) + } else if n.is_ruler_guide() { + // A ruler guide row selects the guide through `guide.select`, not as art. + vec![] } else { vec![id] }; @@ -740,9 +747,12 @@ enum Place { /// Drag rows in the Layers panel. fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.move"; - let mut ids = ids_param(p, "ids", C)?.or_else(|| id_param(p, "id").map(|i| vec![i])).ok_or_else(|| bad(C, "missing ids"))?; + let mut ids = match ids_param(p, "ids", C)? { + Some(ids) => ids, + None => vec![object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing ids"))?], + }; ids.truncate(MAX_ROWS); - let target = id_param(p, "target").ok_or_else(|| bad(C, "missing target"))?; + let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing target"))?; let place = match str_param(p, "place").unwrap_or("inside") { "above" => Place::Above, "below" => Place::Below, @@ -784,11 +794,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { let mut nodes = vec![]; for id in &ids { let n = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?; - let c = d.reid(&n); - if n.is_layer() { - d.copy_layer_guides(&n, &c); - } - nodes.push(Arc::new(c)); + // A copied layer's ruler guides are copied with it. + nodes.push(Arc::new(d.reid(&n))); } nodes } else { @@ -810,6 +817,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { let ch = d.children_mut(parent)?; let index = index.min(ch.len()); ch.splice(index..index, nodes); + // A layer's ruler guides stay above its art, each in the order it now has. + ch.sort_by_key(|c| c.is_ruler_guide()); // Copied type whose layout caches `reid` dropped has them again. if copy { super::typecmd::refresh_bounds_of(d, &out); @@ -825,8 +834,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { fn move_node(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "node.move"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; - let parent = id_param(p, "parent"); + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let parent = object_param(p, "parent", C)?; let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index); let d = &s.doc()?.doc; let n = d.node(id).ok_or(EngineError::NoNode(id))?; @@ -972,7 +981,7 @@ fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Selection, indi for &i in indices.iter().rev() { let id = d.artboards.remove(i).id; d.retire_artboard_id(id); - d.retain_guides(sel, |_, g| g.artboard != Some(id)); + d.retain_guides(sel, |g| g.artboard != Some(id)); } Ok(()) } diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 0a81a947ec..95c152e959 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -255,9 +255,9 @@ fn merge_into(d: &mut Document, into: NodeId, others: &[NodeId]) -> Result<()> { let mut all = std::mem::take(ch); all.extend(taken); all.sort_by(|a, b| keys.get(&a.id).cmp(&keys.get(&b.id))); + // Ruler guides (the merged layers' among them) stay above the art, each kind in that order. + all.sort_by_key(|c| c.is_ruler_guide()); *ch = all; - // The merged layers' guides go to it too. - d.rehome_guides(into); Ok(()) } @@ -318,9 +318,8 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> { let others: Vec<NodeId> = d.layers.iter().filter(|l| l.id != into && l.visible && !l.is_template()).map(|l| l.id).collect(); let hidden: Vec<NodeId> = d.layers.iter().filter(|l| l.id != into && !l.visible && !l.is_template()).map(|l| l.id).collect(); s.edit("Flatten Artwork", |d, sel| { - d.remove_many(&hidden)?; // Hidden layers are discarded with their guides. - d.drop_guides_of_deleted_layers(sel); + d.remove_many(&hidden)?; merge_into(d, into, &others)?; sel.prune(d); sel.deselect_uneditable(d); @@ -349,8 +348,8 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> { NodeKind::Group { .. } => true, _ => return Err(bad(C, "release a layer or a group")), }; - // Its objects, bottom first (sublayers stay as they are). - let objects: Vec<NodeId> = n.children().into_iter().flatten().filter(|c| !c.is_layer()).map(|c| c.id).collect(); + // Its objects, bottom first (sublayers and ruler guides stay as they are). + let objects: Vec<NodeId> = n.children().into_iter().flatten().filter(|c| !c.is_layer() && !c.is_ruler_guide()).map(|c| c.id).collect(); if objects.is_empty() { return Err(EngineError::Other("there are no objects to release".into())); } @@ -386,7 +385,8 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> { } let new: Vec<NodeId> = layers.iter().map(|l| l.id).collect(); let ch = d.children_mut(Some(parent))?; - let at = index.min(ch.len()); + // Below the parent's ruler guides. + let at = index.min(Node::guide_run_start(ch)); ch.splice(at..at, layers); // Copied type whose layout caches `reid` dropped has them again. if build { diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index 5b5a6aa48a..f2ce9d4d12 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> { "Find Linked Files", [], None, - "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 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?}", + "{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. With automation read roots, a reply leaves out the files found outside the caller's roots, a link's path outside them, and the folder when it is outside them (error then gives the reason without the path); 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 )] @@ -52,6 +52,8 @@ pub(crate) struct LinkSearch { pub(crate) id: u64, /// The folder as given. pub(crate) folder: String, + /// The path of the document the links were taken from, which a relative link path starts from. + pub(crate) doc: Option<String>, pub(crate) links: Vec<Sought>, /// The size of each file read, by the path the search reports ([`LinkFiles::sizes`]). pub(crate) sizes: Arc<Mutex<HashMap<PathBuf, u64>>>, @@ -163,6 +165,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { if links.is_empty() { return Err(bad(C, if ids.is_some() { "these objects show no linked files" } else { "no linked files are missing" })); } + let doc = super::links::LinkBase::of(st).doc.map(str::to_string); // A new search stops the last one. s.link_search = None; let threads = s.search_threads.unwrap_or_else(findfiles::threads); @@ -171,7 +174,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> { let visitor = Arc::new(LinkFiles::new(&links, sizes.clone())); let search = findfiles::start(PathBuf::from(&folder), s.search_rules.clone(), limits, threads, 2 * links.len(), visitor).map_err(EngineError::Other)?; - s.link_search = Some(LinkSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, links, sizes, search }); + s.link_search = Some(LinkSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, doc, links, sizes, search }); Ok(state(s)) } @@ -209,7 +212,9 @@ fn shared_folders(saved: &str, found: &Path) -> usize { /// Where the session's last search stands (`links.findFiles` without `folder`). fn state(s: &Session) -> Value { let Some(l) = &s.link_search else { return json!({ "state": "idle", "links": [] }) }; - let p = l.search.progress(); + let mut p = l.search.progress(); + // Only what the caller asking now may read: a search another caller started can hold more. + let (folder, error) = p.keep_readable(&l.folder); let n = l.links.len(); let sizes = lock(&l.sizes).clone(); // Per linked file: the files found, each with whether it is the same file. @@ -267,19 +272,23 @@ fn state(s: &Session) -> Value { f }) .collect(); - json!({ "name": link.name, "path": link.path, "ids": link.ids, "files": files }) + let mut row = json!({ "name": link.name, "ids": link.ids, "files": files }); + super::links::note_path(&mut row, "path", &link.path, l.doc.as_deref()); + row }) .collect(); - let folder = if p.folder.as_os_str().is_empty() { l.folder.clone() } else { p.folder.to_string_lossy().into_owned() }; let mut out = json!({ - "id": l.id, "state": p.state(), "folder": folder, "links": links, + "id": l.id, "state": p.state(), "links": links, "searched": { "folders": p.folders, "files": p.files, "read": p.read }, "skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0, }); + if let Some(folder) = folder { + out["folder"] = json!(folder); + } if let Some(why) = p.stopped() { out["stopped"] = json!(why); } - if let Some(e) = p.error() { + if let Some(e) = error { out["error"] = json!(e); } out diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 22d61723e9..89c0afefcf 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> { "Check Links", [], None, - "{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}", + "{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, check ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -113,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> { "Link Info", [], None, - "{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch), refused? (why the path is not followed); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's or page's 100% size", + "{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch), refused? (why the path is not followed); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's or page's 100% size; under automation read roots, a link whose file is outside the roots has no link, path or location, and fileSize and modified come only from the file", has_doc, info ), @@ -521,10 +521,25 @@ fn linked_image(bytes: &[u8]) -> Result<RasterImage> { /// The file read for a link: the link to it and its image. type FileRead = (LinkInfo, RasterImage); -/// The file at `f` read for a link like `base` (its image decoded). -fn read_image(f: &mut Found, base: &LinkInfo) -> Result<FileRead> { +/// The images read in one operation, by the path of the file and its content hash: groups whose +/// image keys differ but whose file is the same share one decoded image (and its encoded bytes) +/// instead of each keeping a copy. +type ImageReads = BTreeMap<String, (String, RasterImage)>; + +/// The file at `f` read for a link like `base` (its image decoded, or the one `reads` holds for +/// the same file content). +fn read_image(f: &mut Found, base: &LinkInfo, reads: &mut ImageReads) -> Result<FileRead> { let bytes = f.read()?; - Ok((f.link(&bytes, base), linked_image(&bytes)?)) + let hash = hash_bytes(&bytes); + let img = match reads.get(&f.path) { + Some((h, img)) if *h == hash => img.clone(), + _ => { + let img = linked_image(&bytes)?; + reads.insert(f.path.clone(), (hash.clone(), img.clone())); + img + } + }; + Ok((f.link_hashed(hash, base), img)) } /// A linked file read for the objects that show it. @@ -536,8 +551,8 @@ enum Read { } /// The file at `f` read for group `g`: its image, or the artboard or page `g` shows. -fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result<Read> { - let Some((bounding, page_box)) = g.document else { return read_image(f, &g.link).map(Read::Image) }; +fn read_for(f: &mut Found, g: &Group, cmd: &str, reads: &mut ImageReads) -> Result<Read> { + let Some((bounding, page_box)) = g.document else { return read_image(f, &g.link, reads).map(Read::Image) }; let bytes = f.read()?; let page = g.link.page.unwrap_or(1); let src = super::place::document::source(&f.path, &bytes, Some(&f.path), page, bounding, page_box, cmd)?; @@ -867,17 +882,35 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio } /// Groups (of the document saved at `doc_path`) as `{name, path, ids}` rows (those with objects in -/// the layers), with `refused`: why the path isn't followed, when it isn't. +/// the layers), with `refused`: why the path isn't followed, when it isn't. `path` is left out +/// where [`path_shown`] says so. fn rows<'a>(gs: impl Iterator<Item = &'a Group>, doc_path: Option<&str>) -> Vec<Value> { gs.filter(|g| !g.ids.is_empty()) .map(|g| { - let mut row = json!({ "name": g.link.name(), "path": g.link.path, "ids": ids_json(&g.ids) }); + let mut row = json!({ "name": g.link.name(), "ids": ids_json(&g.ids) }); + note_path(&mut row, "path", &g.link.path, doc_path); note_refused(&mut row, &g.link, doc_path); row }) .collect() } +/// May a reply to the caller asking now carry the link path `path` (of the document saved at +/// `doc_path`)? Always without read roots in force; with them, only when the file it names (a +/// relative path taken from the document's folder) lies inside them. +pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool { + crate::file_access::current().is_none() || fileio::document_path(path, doc_path).is_ok_and(|p| crate::file_access::check_read(&p).is_ok()) +} + +/// `row[key] = path` when [`path_shown`] says so; otherwise `row` has no `key`. +pub(crate) fn note_path(row: &mut Value, key: &str, path: &str, doc_path: Option<&str>) { + if path_shown(path, doc_path) { + row[key] = json!(path); + } else if let Some(o) = row.as_object_mut() { + o.remove(key); + } +} + /// `row["refused"]`: why the path of `link` isn't followed, when it isn't ([`refused`]). fn note_refused(row: &mut Value, link: &LinkInfo, doc_path: Option<&str>) { if let Some(r) = refused(link, doc_path) { @@ -922,6 +955,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps // (the path as it was, the content shown, a placed document?, the link now) of each file found // away from its path or read again. let mut moved: Vec<(String, String, bool, LinkInfo)> = vec![]; + let mut image_reads = ImageReads::new(); for g in groups(d, None) { let row = rows(std::iter::once(&g), base.doc); let shows_preview = match g.document { @@ -934,7 +968,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps (Status::Missing, _) => out.missing.extend(row), (Status::Modified, Some(mut f)) if update || unread => { let force = unread.then_some(Preserve::Bounds); - match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) { + match read_for(&mut f, &g, "document.open", &mut image_reads).and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) { Ok(()) if unread => {} Ok(()) => out.updated.extend(row), Err(_) => out.missing.extend(row), @@ -943,7 +977,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps (Status::Modified, _) => out.modified.extend(row), // A placed document keeps its file's bytes: only lost ones are read again. (Status::Ok, Some(mut f)) if g.document.is_some() => { - let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None }; + let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open", &mut image_reads)) } else { None }; match read { Some(Ok(read)) => { if install_read(d, &g.ids, read, Some(Preserve::Bounds), Some(&g)).is_err() { @@ -1172,10 +1206,12 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { let (status, found) = probe(g, LinkBase::of(st)); missing += usize::from(status == Status::Missing); modified += usize::from(status == Status::Modified); - let mut row = json!({ "name": g.link.name(), "path": g.link.path, "status": status.as_str(), "ids": ids_json(&g.ids) }); - note_refused(&mut row, &g.link, LinkBase::of(st).doc); + let doc_path = LinkBase::of(st).doc; + let mut row = json!({ "name": g.link.name(), "status": status.as_str(), "ids": ids_json(&g.ids) }); + note_path(&mut row, "path", &g.link.path, doc_path); + note_refused(&mut row, &g.link, doc_path); if let Some(f) = found.filter(|f| f.path != g.link.path) { - row["found"] = json!(f.path); + note_path(&mut row, "found", &f.path, doc_path); } if stale(&st.doc, g) { row["preview"] = json!(true); @@ -1196,6 +1232,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> { fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> { let st = s.doc()?; let (mut reads, mut missing) = (vec![], vec![]); + let mut image_reads = ImageReads::new(); let asked = ids.is_some() || path.is_some(); for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| path.is_none_or(|p| g.document.is_some() && g.link.path == p)) { match probe(&g, LinkBase::of(st)) { @@ -1203,7 +1240,7 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) - // Unchanged and showing the file: nothing to read unless asked for. (Status::Ok, Some(_)) if !asked && !stale(&st.doc, &g) => {} // Unreadable as an image (or a document) counts as missing. - (_, Some(mut f)) => match read_for(&mut f, &g, "links.update") { + (_, Some(mut f)) => match read_for(&mut f, &g, "links.update", &mut image_reads) { Ok(read) => reads.push((g, read)), Err(_) => missing.extend(ids_json(&g.ids)), }, @@ -1646,14 +1683,15 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> { o.insert("linked".into(), json!(link.is_some())); o.insert("status".into(), json!(status)); } + let doc_path = LinkBase::of(st).doc; if let Some(l) = link { - row["path"] = json!(l.path); + note_path(&mut row, "path", &l.path, doc_path); if let Some(page) = l.page { row["page"] = json!(page); } } if let Some(f) = found { - row["found"] = json!(f); + note_path(&mut row, "found", f, doc_path); } if preview { row["preview"] = json!(true); @@ -1706,13 +1744,14 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> { let ids: Vec<NodeId> = ids.into_iter().filter(|id| matches!(kind(id), Some(NodeKind::Image(_)))).collect(); // Images showing their preview take their file's pixels first. let (mut done, mut reads) = (vec![], vec![]); + let mut image_reads = ImageReads::new(); for g in groups(&st.doc, Some(&ids)) { if !previewing(&st.doc, &g.key) { done.extend(g.ids); continue; } match probe(&g, LinkBase::of(st)) { - (Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link) { + (Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link, &mut image_reads) { Ok(read) => { done.extend(&g.ids); reads.push((g.ids, read)); @@ -1793,13 +1832,17 @@ fn placement_json(o: PlacementOptions) -> Value { /// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`. fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { + // Whether the path is shown is judged for the caller asking, before the opener's roots apply. + let shown = path_shown(&l.path, LinkBase::of(st).doc); // A confined caller reads within its own roots; anyone else within what the caller that // opened the document may read (never wider than the caller asking now). let roots = crate::file_access::current().or_else(|| st.opened_by.clone()); - crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, out)); + crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, shown, out)); } -fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { +/// [`file_fields`]; without `shown`, the link's path (`path`, `link`) and folder (`location`) +/// and the size and date the document keeps of its file are left out. +fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, shown: bool, out: &mut Value) { let base = LinkBase::of(st); let status = groups(&st.doc, Some(&[id])).first().map_or(Status::Missing, |g| probe(g, base).0); let doc_path = base.doc; @@ -1807,13 +1850,20 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va let stamp = path.as_deref().and_then(file_stamp); out["status"] = json!(status.as_str()); note_refused(out, l, doc_path); - out["path"] = json!(l.path); + if shown { + out["path"] = json!(l.path); + out["location"] = json!(l.folder()); + } else if let Some(o) = out.as_object_mut() { + for k in ["path", "link", "location"] { + o.remove(k); + } + } out["fileName"] = json!(l.name()); - out["location"] = json!(l.folder()); + let kept = |v: Option<u64>| v.filter(|_| shown); for (k, v) in [ ("page", l.page.map(u64::from)), - ("fileSize", stamp.map(|s| s.0).or(l.size)), - ("modified", stamp.and_then(|s| s.1).or(l.modified)), + ("fileSize", stamp.map(|s| s.0).or(kept(l.size))), + ("modified", stamp.and_then(|s| s.1).or(kept(l.modified))), ("created", path.as_deref().and_then(file_created)), ] { if let Some(v) = v { @@ -1921,3 +1971,26 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> { set(&mut shown); Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) })) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::tests::links::{Folder, RED, png, write}; + + #[test] + fn groups_of_one_file_share_one_decoded_image() { + let dir = Folder::new("shared-read"); + let path = dir.file("pic.png"); + write(&path, &png(40, 20, RED)); + let (mut reads, base) = (ImageReads::new(), LinkInfo::new(path.clone())); + let mut read = || read_image(&mut found_at(path.clone()).unwrap(), &base, &mut reads).unwrap().1; + let (a, b) = (read(), read()); + assert!(Arc::ptr_eq(&a.blob.bytes, &b.blob.bytes), "one retained copy of the bytes"); + // A changed file is decoded again. + write(&path, &png(40, 20, [1, 2, 3])); + let c = read(); + assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); + } +} diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index 464f241159..618865cede 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -21,7 +21,7 @@ use super::expand::gradient_sampler; use super::pathops::Beside; use super::{ CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi, - has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, text_param, + has_selection, named_ids, number_or, object_param, ok, str_param, switch_or, text_param, }; mod blend; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 7d7c21227a..d47e81befd 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -1,5 +1,7 @@ use std::collections::BTreeSet; +use vectorcraft_doc::live::BlendSpineMode; + 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, @@ -61,6 +63,19 @@ fn extend_spine(spec: &mut BlendSpec, old: &[Arc<Node>], old_spec: &BlendSpec, k spec.spine = Some(path); } +/// Does `p` set easing (`easingType` or `ramp`)? Easing needs a spine. +fn gives_easing(p: &Value) -> bool { + ["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) +} + +/// The Create Spine mode `p` gives as `key`, or `current` when it is omitted or null. +fn spine_mode_param(p: &Value, cmd: &str, key: &str, current: BlendSpineMode) -> Result<BlendSpineMode> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(current), + Some(v) => v.as_str().and_then(BlendSpineMode::from_id).ok_or_else(|| bad(cmd, format!("`{key}` must be one of auto, always, never"))), + } +} + pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.blend.make"; let roots = roots_param(s, p)?; @@ -69,16 +84,22 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> { } let starts = starts_param(p, &roots)?; let base = first_blend(&s.doc()?.doc, &roots); + let defaults = s.prefs.blend_options.unwrap_or_default(); + // Create Spine applies to a new blend; one taking more keys keeps whether it has a spine. + let create_spine = spine_mode_param(p, C, "createSpine", defaults.create_spine)?; let cur = match base.as_ref().map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation }, - _ => s.prefs.blend_options.unwrap_or_default(), + Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation, ..defaults }, + _ => defaults, }; let spacing = spacing_param(p, C, cur.spacing)?; let orientation = orientation_param(p, cur.orientation); - let (ease0, color0) = match base.as_ref().map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift), - _ => Default::default(), + let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) { + Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine), + _ => (Default::default(), 0.0, !create_spine.creates_spine()), }; + if no_spine && gives_easing(p) { + return Err(bad(C, "the blend has no spine")); + } let ease = ease_param(p, C, ease0)?; let color_shift = percent_param(p, C, "colorShift", color0, -100.0)?; let id = s.edit("Make Blend", |d, sel| { @@ -91,7 +112,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> { n.knockout = vectorcraft_doc::Knockout::On; n }); - let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, ..Default::default() }; + let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, no_spine, ..Default::default() }; if let NodeKind::Blend { children: old, spec: old_spec } = &n.kind { extend_spine(&mut spec, old, old_spec, &children); } @@ -303,7 +324,11 @@ pub(super) fn spine_remove_anchor(s: &mut Session, p: &Value) -> Result<Value> { if anchors.contains(&index) { return Err(bad(C, "a key object sits on that point")); } - if sp.anchors.len() <= 2 { + // A closed spine pinned open keeps a copy of its first point at its end (#6809), so the + // points left must be two apart, not only two in number. + let mut rest = sp.anchors.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, a)| a.p); + let first = rest.next(); + if sp.anchors.len() <= 2 || first.is_none_or(|f| rest.all(|q| q.distance(f) < 0.01)) { return Err(bad(C, "a spine keeps at least two points")); } sp.anchors.remove(index); @@ -346,9 +371,12 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> { // Nothing to set them on: the options new blends start with (easing is per blend). let d = s.prefs.blend_options.unwrap_or_default(); let spacing = spacing_param(p, C, d.spacing)?; - s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation) }); + s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d }); return Ok(json!({ "defaults": true })); }; + if gives_easing(p) && any_without_spine(s) { + return Err(bad(C, "the blend has no spine")); + } let spacing = spacing_param(p, C, cur.spacing)?; let orientation = orientation_param(p, cur.orientation); let ease = ease_param(p, C, cur.ease)?; @@ -384,6 +412,7 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> { v["colorShift"] = json!(spec.color_shift); v["starts"] = json!((0..keys.len()).map(|i| spec.start(i)).collect::<Vec<_>>()); v["keys"] = json!(keys.iter().map(|k| k.0).collect::<Vec<_>>()); + v["hasSpine"] = json!(!spec.no_spine); if let Some(NodeKind::Blend { children, .. }) = s.doc()?.doc.node(id).map(|n| &n.kind) && let Some((path, anchors)) = live::blend_spine(children, &spec) && let Some(sp) = path.subpaths.first() @@ -403,6 +432,19 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> { }) } +/// The Blend panel's Create Spine: with `mode`, sets whether new blends get a spine; without, reads +/// it. A tool setting kept with the preferences, not an undo step; blends already made keep theirs. +pub(super) fn blend_create_spine(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "object.blend.createSpine"; + let mut d = s.prefs.blend_options.unwrap_or_default(); + let mode = spine_mode_param(p, C, "mode", d.create_spine)?; + if mode != d.create_spine { + d.create_spine = mode; + s.prefs.blend_options = Some(d); + } + Ok(json!({ "mode": mode.id() })) +} + pub(super) fn blend_expand(s: &mut Session, _: &Value) -> Result<Value> { let blends = selected_of(s, is_blend); let ids = s.edit("Expand Blend", |d, sel| { @@ -507,6 +549,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> { let spine = d.node(path).and_then(|n| n.path_data().cloned()).ok_or(EngineError::NoNode(path))?; d.remove(path)?; if let Some(NodeKind::Blend { children, spec }) = d.node_mut(b).map(|n| &mut n.kind) { + // A blend made without a spine gets this one. + spec.no_spine = false; spec.spine = Some(spine); spec.key_anchors.clear(); keys_to_spine(children, spec); @@ -517,7 +561,16 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> { ok() } +/// Is any selected blend one made without a spine? +fn any_without_spine(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> { + if any_without_spine(s) { + return Err(bad("object.blend.reverseSpine", "the blend has no spine")); + } edit_blends(s, "Reverse Spine", |children, spec| { if spec.spine.is_some() && pin(children, spec) { // The keys keep their anchors, which now count from the other end. diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index b69b4e869d..1013c606c5 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -1,6 +1,6 @@ use super::blend::{ - blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, blend_reverse_stack, - spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment, + blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, + blend_reverse_stack, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment, }; use super::common::{has_blend, has_envelope, has_mesh}; use super::envelope::{ @@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make", ["Object", "Blend"], Some("Cmd+Alt+B"), - "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name and transparency) instead of nesting → {id}", + "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", has_doc, blend_make ), @@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> { "Release", ["Object", "Blend"], Some("Cmd+Alt+Shift+B"), - "{} release the selected blends: the key objects come back and the spine stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}", + "{} release the selected blends: the key objects come back and the spine (if the blend has one) stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}", has_blend, blend_release ), @@ -40,6 +40,15 @@ pub fn specs() -> Vec<CommandSpec> { always, blend_options ), + cmd!( + "object.blend.createSpine", + "Create Spine", + [], + None, + "{mode?: auto|always|never} the Blend panel's Create Spine: whether new blends get a spine (auto and always: the straight lines between the key centers, as before; never: no spine to show, edit, reverse or release, and no easing, until Replace Spine gives one); with no `mode`, reads it; blends already made keep theirs (a tool setting kept with the preferences, not an undo step) → {mode}", + always, + blend_create_spine + ), cmd!( "object.blend.expand", "Expand", @@ -54,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { "Replace Spine", ["Object", "Blend"], None, - "{} use the selected path as the spine of the selected blend (the path is consumed)", + "{} use the selected path as the spine of the selected blend (the path is consumed); a blend made without a spine gets this one", has_blend, blend_replace_spine ), @@ -63,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reverse Spine", ["Object", "Blend"], None, - "{} reverse the order of the key objects along the spine", + "{} reverse the order of the key objects along the spine; an error when a selected blend has no spine", has_blend, blend_reverse_spine ), @@ -72,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> { "Blend Info", [], None, - "{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}", + "{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], hasSpine?: false for a blend made without a spine (no `spine` then), spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}", always, blend_info ), @@ -136,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make with Warp…", ["Object", "Envelope Distort"], Some("Cmd+Alt+Shift+W"), - "{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}", + "{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v, version?: 0|1 (1: each style bends the bounds as one Bézier patch; 0: VectorCraft's earlier map)} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}", has_selection, env_make_warp ), @@ -163,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reset with Warp…", ["Object", "Envelope Distort"], None, - "{style?, bend?, h?, v?, horizontal? | orientation? (as makeWithWarp; unset: the envelope's current warp, else arc 50 %), horizontalDistortion?: as h, verticalDistortion?: as v} make the selected envelopes warp envelopes, keeping their content", + "{style?, bend?, h?, v?, horizontal? | orientation? (as makeWithWarp; unset: the envelope's current warp, else arc 50 %), horizontalDistortion?: as h, verticalDistortion?: as v, version?: as makeWithWarp (unset: a warp envelope's own, else 1)} make the selected envelopes warp envelopes, keeping their content", has_envelope, env_reset_warp ), @@ -181,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> { "Envelope Info", [], None, - "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", + "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", has_doc, env_info ), @@ -199,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> { "Envelope Options…", ["Object", "Envelope Distort"], None, - "{fidelity?: 0..100, antiAlias?: bool, preserveShape?: clippingMask|transparency, distortAppearance?: bool, distortLinearGradients?: bool, distortPatternFills?: bool (the last two work with distortAppearance; on an envelope with boundsMargin, distortAppearance also switches the content between the box with the margins and its geometric box), style?, bend?, h?, v?, horizontal? (warp envelopes), horizontalDistortion?: as h, verticalDistortion?: as v, orientation?: horizontal|vertical} set the selected envelopes' options; with no envelope selected, the options new envelopes get (see object.envelope.info)", + "{fidelity?: 0..100, antiAlias?: bool, preserveShape?: clippingMask|transparency, distortAppearance?: bool, distortLinearGradients?: bool, distortPatternFills?: bool (the last two work with distortAppearance; on an envelope with boundsMargin, distortAppearance also switches the content between the box with the margins and its geometric box), style?, bend?, h?, v?, horizontal? (warp envelopes), horizontalDistortion?: as h, verticalDistortion?: as v, orientation?: horizontal|vertical, version?: 0|1 (warp envelopes' map, as makeWithWarp)} set the selected envelopes' options; with no envelope selected, the options new envelopes get (see object.envelope.info)", has_doc, env_options ), diff --git a/crates/engine/src/cmd/live/envelope.rs b/crates/engine/src/cmd/live/envelope.rs index 1aceb49b54..b9a315325b 100644 --- a/crates/engine/src/cmd/live/envelope.rs +++ b/crates/engine/src/cmd/live/envelope.rs @@ -3,7 +3,7 @@ use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wr use super::mesh::{handle_param, index_param, whole}; use super::{ Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint, - PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, id_param, json, live, ok, switch_or, text_param, + PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, json, live, object_param, ok, switch_or, text_param, }; // ---------- Envelope ---------- @@ -13,9 +13,14 @@ const WARP_NUMBERS: &[&str] = &["bend", "h", "v", "horizontalDistortion", "verti fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<EnvelopeKind> { check_numbers(p, WARP_NUMBERS, cmd)?; - let (mut style, mut bend, mut h, mut v, mut horizontal) = ("arc".to_string(), 50.0, 0.0, 0.0, true); - if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0 }) = cur { - (style, bend, h, v, horizontal) = (s0.clone(), *b0, *h0, *v0, *z0); + // A new warp takes its style's Bézier net; an edited one keeps the map it has unless `version` + // names one. + let (mut style, mut bend, mut h, mut v, mut horizontal, mut version) = ("arc".to_string(), 50.0, 0.0, 0.0, true, live::WARP_NET); + if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0, version: n0 }) = cur { + (style, bend, h, v, horizontal, version) = (s0.clone(), *b0, *h0, *v0, *z0, *n0); + } + if let Some(n) = p.get("version") { + version = live::warp_version(n).ok_or_else(|| bad(cmd, format!("`version` must be 0 or {}", live::WARP_NET)))?; } if let Some(s) = text_param(p, "style", cmd)? { let s = s.strip_prefix("warp.").unwrap_or(s); @@ -32,7 +37,7 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop Some(o) => o == "horizontal", None => given, }; - Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal }) + Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal, version }) } /// The options and fidelity new envelopes get (Envelope Options with no envelope selected). @@ -206,8 +211,8 @@ pub(super) fn env_info(s: &mut Session, _: &Value) -> Result<Value> { return Ok(envelope_options_json(json!({ "id": null }), &options, fidelity)); }; let v = match &**kind { - EnvelopeKind::Warp { style, bend, h, v, horizontal } => { - json!({"type": "warp", "style": style, "bend": bend, "h": h, "v": v, "horizontal": horizontal}) + EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => { + json!({"type": "warp", "style": style, "bend": bend, "h": h, "v": v, "horizontal": horizontal, "version": version}) } EnvelopeKind::Mesh { rows, cols, .. } => json!({"type": "mesh", "rows": rows, "cols": cols}), EnvelopeKind::TopObject { .. } => json!({"type": "topObject"}), @@ -419,7 +424,7 @@ pub(super) fn env_edit_contents(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn env_set_mesh_point(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.envelope.setMeshPoint"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let index = index_param(p, "index", C)?; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let handle = handle_param(p, C)?; diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 70c2d9f348..187d2149f2 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec use super::envelope::{outline_of, rows_cols}; use super::{ Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad, - check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param, + check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, json, live, object_param, ok, str_param, }; // ---------- Gradient mesh ---------- @@ -115,7 +115,7 @@ fn image_mesh(d: &Document, im: &vectorcraft_doc::ImageObject, rows: u32, cols: /// Run `f` on the gradient mesh `p.id` (one undo step `label`); with `envelopes`, a mesh /// envelope's grid too (see [`edit_grid`]). fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> { - let id = id_param(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?; + let id = object_param(p, "id", cmd)?.ok_or_else(|| bad(cmd, "missing `id`"))?; s.edit(label, move |d, _| edit_grid(d, id, cmd, envelopes, f)) } @@ -147,7 +147,7 @@ const MAX_POINTS: usize = 1 << 20; /// points}…]}`. Each mesh comes once, with its points in order and without repeats. fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> { let one = |q: &Value| -> Result<(NodeId, BTreeSet<usize>)> { - let id = id_param(q, "id").ok_or_else(|| bad(cmd, "missing `id`"))?; + let id = object_param(q, "id", cmd)?.ok_or_else(|| bad(cmd, "missing `id`"))?; let points = match q.get("points") { None | Some(Value::Null) => BTreeSet::from([index_param(q, "index", cmd)?]), Some(Value::Array(v)) if v.len() <= MAX_POINTS => v diff --git a/crates/engine/src/cmd/maskedit.rs b/crates/engine/src/cmd/maskedit.rs index f2d322a39c..debd0db684 100644 --- a/crates/engine/src/cmd/maskedit.rs +++ b/crates/engine/src/cmd/maskedit.rs @@ -259,10 +259,12 @@ pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<NodeId>) { /// mode when the object or the layer is gone (e.g. deleted). pub(crate) fn sync(d: &mut Document) { let Some(me) = d.mask_edit else { return }; - let art: Option<Vec<Arc<Node>>> = d.node(me.layer).and_then(|l| l.children().cloned()); + // The layer's art: ruler guides on it are not part of the mask. + let art: Option<Vec<Arc<Node>>> = + d.node(me.layer).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect()); let (Some(art), true) = (art, d.node(me.object).is_some_and(|n| n.extras().mask.is_some())) else { d.mask_edit = None; - let _ = d.remove(me.layer); + let _ = d.remove_edit_layer(me.layer); return; }; let new_art = match art.as_slice() { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 8ea016db65..1dd1548363 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -871,7 +871,7 @@ fn rasterize(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } -fn has_image(s: &Session) -> std::result::Result<(), String> { +pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; let st = s.active().ok_or("no document open")?; if st.selection.objects.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) { @@ -1306,13 +1306,16 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> { let symbols = d.symbol_boxes(); let boxes: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, d.node(*id)?.geometric_bounds_with(&symbols)?))).collect(); let mut converted = vec![]; + // The highest artboard id the document has, kept up to date as artboards are added. + let mut top = d.artboards.iter().map(|a| a.id).max(); for (id, b) in boxes { if b.width() <= 0.0 || b.height() <= 0.0 { continue; } // Named one past the highest artboard id the document has, whatever id it is given. - let number = d.artboards.iter().map(|a| a.id).max().map_or(1, |m| m.saturating_add(1)); - let aid = d.next_artboard_id(); + let number = top.map_or(1, |m| m.saturating_add(1)); + let aid = d.next_artboard_id_above(top); + top = top.max(Some(aid)); d.artboards.push(vectorcraft_doc::Artboard { id: aid, name: format!("Artboard {number}"), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 20dc187ab5..bd15d748ca 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -7,7 +7,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, Background, ColorMode, Document, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Document Presets", [], None, - "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode}]}]}; file.new {preset: name} starts from one", + "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", always, list ), @@ -144,6 +144,10 @@ pub struct DocSettings { #[serde(deserialize_with = "de_ppi")] pub raster_effects_ppi: f64, pub preview_mode: PreviewMode, + /// Align New Objects to Pixel Grid ([`vectorcraft_doc::DocSetup::align_new_objects_to_pixel_grid`]): + /// on in the Mobile and Web presets, off in the others and in a saved or Recent preset from + /// before it. + pub align_new_objects_to_pixel_grid: bool, } impl Default for DocSettings { @@ -163,6 +167,7 @@ impl Default for DocSettings { color_mode: ColorMode::Rgb, raster_effects_ppi: 72.0, preview_mode: PreviewMode::Default, + align_new_objects_to_pixel_grid: false, } } } @@ -211,6 +216,7 @@ impl DocSettings { "colorMode": color_mode_id(self.color_mode), "rasterEffectsPpi": self.raster_effects_ppi, "previewMode": self.preview_mode.id(), + "alignNewObjectsToPixelGrid": self.align_new_objects_to_pixel_grid, }) } @@ -273,6 +279,7 @@ impl DocSettings { if let Some(m) = p.get("previewMode").filter(|v| !v.is_null()) { self.preview_mode = m.as_str().and_then(PreviewMode::parse).ok_or_else(|| bad(cmd, "previewMode must be default, pixel or overprint"))?; } + self.align_new_objects_to_pixel_grid = switch_or(p, "alignNewObjectsToPixelGrid", self.align_new_objects_to_pixel_grid, cmd)?; let extent = self.boards().iter().fold(Rect::ZERO, |a, r| a.union(*r)); if extent.width().max(extent.height()) + self.bleed.iter().fold(0.0f64, |a, b| a.max(*b)) * 2.0 > crate::MAX_COORD { return Err(bad(cmd, "the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size")); @@ -330,6 +337,7 @@ impl DocSettings { d.raster_effects_ppi = self.raster_effects_ppi; d.setup.bleed = self.bleed; d.setup.background = self.background; + d.setup.align_new_objects_to_pixel_grid = self.align_new_objects_to_pixel_grid; d.artboards = self .boards() .into_iter() @@ -543,6 +551,10 @@ pub const CATEGORIES: &[Category] = &[ ), ]; +/// The built-in categories whose presets start with Align New Objects to Pixel Grid on +/// (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>). +const PIXEL_ALIGNED_CATEGORIES: [&str; 2] = ["Mobile", "Web"]; + /// The category tabs in order: Recent, Saved, then the built-in categories. pub fn category_names() -> impl Iterator<Item = &'static str> { ["Recent", "Saved"].into_iter().chain(CATEGORIES.iter().map(|c| c.0)) @@ -551,7 +563,8 @@ pub fn category_names() -> impl Iterator<Item = &'static str> { /// The built-in presets of one category: screen sizes in pixels, the others in `general` /// (Preferences ▸ Units ▸ General). fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + '_ { - let (_, color_mode, ppi, presets) = *c; + let (category, color_mode, ppi, presets) = *c; + let align = PIXEL_ALIGNED_CATEGORIES.contains(&category); presets.iter().map(move |&(name, w, h, units)| DocSettings { name: name.into(), width: units.to_pt(w), @@ -559,6 +572,7 @@ fn builtin(c: &Category, general: Unit) -> impl Iterator<Item = DocSettings> + ' units: if units == Unit::Pixels { units } else { general }, color_mode, raster_effects_ppi: ppi, + align_new_objects_to_pixel_grid: align, ..DocSettings::default() }) } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index c467f06e5a..5eee2d3fce 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -36,6 +36,9 @@ pub(crate) use arrange::group_nodes; pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; -pub(crate) use pixelgrid::{keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned}; +pub(crate) use pixelgrid::{ + align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, + snap_if_aligned, +}; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/align.rs b/crates/engine/src/cmd/object/align.rs index b32275d1b7..c3a2898571 100644 --- a/crates/engine/src/cmd/object/align.rs +++ b/crates/engine/src/cmd/object/align.rs @@ -102,15 +102,15 @@ fn items_bounds(d: &Document, ids: &[NodeId], m: Measure) -> Vec<(NodeId, Rect)> ids.iter().filter_map(|id| Some((*id, m.of(d, *id)?))).collect() } -/// Move each object of `moves` by its offset and each ruler guide of `guides` (index, position) +/// Move each object of `moves` by its offset and each ruler guide of `guides` (id, position) /// to its position, as undo step `label`; pattern tiles move too when [`transform_patterns`] says /// so for `ids`. When every move is a rounding error (1e-9 pt or less on both axes), the document /// and its undo history stay as they are. -fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: &[(NodeId, Vec2)], guides: &[(usize, f64)]) -> Result<Value> { +fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: &[(NodeId, Vec2)], guides: &[(NodeId, f64)]) -> Result<Value> { let sc = Scaling { patterns: transform_patterns(s, p, ids)?, ..Scaling::default() }; - let guides: Vec<(usize, f64)> = { + let guides: Vec<(NodeId, f64)> = { let d = &s.doc()?.doc; - guides.iter().copied().filter(|&(i, pos)| d.guides.get(i).is_some_and(|g| (g.pos - pos).abs() > 1e-9)).collect() + guides.iter().copied().filter(|&(i, pos)| d.ruler_guide(i).is_some_and(|g| (g.pos - pos).abs() > 1e-9)).collect() }; if moves.iter().all(|(_, dv)| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) && guides.is_empty() { return ok(); @@ -124,9 +124,7 @@ fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: & super::pixelgrid::keep_compound_aligned(d, *id, sc); } for &(i, pos) in &guides { - if let Some(g) = d.guides.get_mut(i) { - g.pos = pos; - } + d.edit_ruler_guide(i, |g| g.pos = pos); } Ok(()) })?; @@ -143,7 +141,7 @@ fn align_to<'a>(s: &Session, p: &'a Value) -> Option<&'a str> { /// [`vectorcraft_doc::Selection::key_guide`]): its position, and whether it is vertical. fn key_guide(s: &Session, p: &Value) -> Option<(f64, bool)> { let st = s.doc().ok()?; - let g = st.doc.guides.get(st.selection.key_guide?)?; + let g = st.doc.ruler_guide(st.selection.key_guide?)?; (align_to(s, p) == Some("key")).then_some((g.pos, g.vertical)) } @@ -164,7 +162,7 @@ fn align_reference(s: &Session, p: &Value, ids: &[NodeId], m: Measure, own: Opti /// Bounds of the selected ruler guides (each guide is a zero-thickness line), for Align to /// Selection when no objects are selected. fn selected_guides_bounds(st: &crate::DocState) -> Option<Rect> { - st.selection.guides.iter().filter_map(|&i| st.doc.guides.get(i)).fold(None, |acc: Option<Rect>, g| { + st.selection.guides.iter().filter_map(|&i| st.doc.ruler_guide(i)).fold(None, |acc: Option<Rect>, g| { let r = if g.vertical { Rect::new(g.pos, 0.0, g.pos, 0.0) } else { Rect::new(0.0, g.pos, 0.0, g.pos) }; Some(acc.map(|a| a.union(r)).unwrap_or(r)) }) @@ -264,7 +262,7 @@ pub(super) fn align(s: &mut Session, p: &Value) -> Result<Value> { /// `v` names. Align to the key object (or key guide) moves them too, and the key guide stays put. /// Align to the artboard moves them (#3463). Align to the selection moves them when only guides are /// selected; with objects in the selection they stay put. -fn guide_moves(s: &Session, p: &Value, r: Rect, h: Option<&str>, v: Option<&str>) -> Result<Vec<(usize, f64)>> { +fn guide_moves(s: &Session, p: &Value, r: Rect, h: Option<&str>, v: Option<&str>) -> Result<Vec<(NodeId, f64)>> { let st = s.doc()?; let to = align_to(s, p); let move_guides = match to { @@ -290,7 +288,7 @@ fn guide_moves(s: &Session, p: &Value, r: Rect, h: Option<&str>, v: Option<&str> .guides .iter() .filter(|&&i| !skip_key || Some(i) != st.selection.key_guide) - .filter_map(|&i| Some((i, at(st.doc.guides.get(i)?.vertical)?))) + .filter_map(|&i| Some((i, at(st.doc.ruler_guide(i)?.vertical)?))) .collect()) } @@ -361,7 +359,7 @@ pub(super) fn can_distribute(s: &Session) -> std::result::Result<(), String> { #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Spaced { Object(NodeId), - Guide(usize), + Guide(NodeId), } /// The selected objects `ids` with their bounds (measured by `m`), and the selected @@ -371,7 +369,7 @@ fn spaced_items(s: &Session, ids: &[NodeId], m: Measure, horiz: bool) -> Result< let st = s.doc()?; let objects = items_bounds(&st.doc, ids, m).into_iter().map(|(id, r)| (Spaced::Object(id), r)); let guides = st.selection.guides.iter().filter_map(|&i| { - let g = st.doc.guides.get(i).filter(|g| g.vertical == horiz)?; + let g = st.doc.ruler_guide(i).filter(|g| g.vertical == horiz)?; Some((Spaced::Guide(i), Rect::new(g.pos, g.pos, g.pos, g.pos))) }); Ok(objects.chain(guides).collect()) @@ -404,7 +402,7 @@ fn apply_spaced(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], horiz: for &(it, delta) in deltas { match it { Spaced::Object(id) => moves.push((id, along(delta))), - Spaced::Guide(i) => guides.extend(d.guides.get(i).map(|g| (i, g.pos + delta))), + Spaced::Guide(i) => guides.extend(d.ruler_guide(i).map(|g| (i, g.pos + delta))), } } apply_moves(s, label, p, ids, &moves, &guides) diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 7aef60fca0..ff5b950d03 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -39,7 +39,9 @@ pub(super) fn arrange(s: &mut Session, how: Arrange) -> Result<Value> { group.retain(|id| d.position(*id).is_some_and(|(_, idx, _)| idx >= floor)); } for (k, id) in group.iter().enumerate() { - let Some((_, idx, len)) = d.position(*id) else { continue }; + let Some((_, idx, _)) = d.position(*id) else { continue }; + // The parent's art, without the ruler guides that stay above it. + let len = d.children(par).map_or(0, |ch| Node::guide_run_start(ch)); if len <= floor { continue; } @@ -73,12 +75,16 @@ pub(super) fn send_to_current_layer(s: &mut Session, _: &Value) -> Result<Value> } // When the selected objects are already the topmost in the current layer, in paint order, the // document and its undo history stay as they are. - if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) { + // (The layer's ruler guides stay above its art.) + let art = |c: &&std::sync::Arc<Node>| !c.is_ruler_guide(); + if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().filter(art).map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) { return ok(); } s.edit("Send to Current Layer", |d, _| { let moved = d.remove_many(&ids)?; - d.children_mut(Some(layer))?.extend(moved); + let ch = d.children_mut(Some(layer))?; + let at = Node::guide_run_start(ch); + ch.splice(at..at, moved); Ok(()) })?; ok() @@ -176,7 +182,7 @@ fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> { fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> { let mut v = vec![]; d.walk(|n| { - if !n.is_layer() && f(n) { + if !n.is_layer() && !n.is_ruler_guide() && f(n) { v.push(n.id) } }); @@ -198,7 +204,7 @@ fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> if let Some(node) = d.node(root) { for child in node.children().into_iter().flatten() { child.walk(&mut |n| { - if !n.is_layer() && f(n) { + if !n.is_layer() && !n.is_ruler_guide() && f(n) { ids.push(n.id); } }); @@ -222,7 +228,7 @@ fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> } for c in d.node(*g).and_then(Node::children).into_iter().flatten() { c.walk(&mut |n| { - if !n.is_layer() && f(n) { + if !n.is_layer() && !n.is_ruler_guide() && f(n) { v.push(n.id) } }); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 2f0aa742d1..5c66ec8442 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reflect…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg, origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, reflect ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg, axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), @@ -297,7 +297,7 @@ pub fn specs() -> Vec<CommandSpec> { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counterclockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 6441fda0c3..64d47ca0a9 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -22,6 +22,16 @@ pub(crate) fn can_align(n: &Node) -> bool { matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) } +/// For an object being drawn into `d`: when the document's Align New Objects to Pixel Grid is on +/// and [`can_align`] accepts `n`, turn `n`'s pixel-aligned property on. The edit that adds it snaps +/// it to the pixel grid ([`refresh`]). Pasted, duplicated, placed and imported objects do not come +/// through here. +pub(crate) fn align_new_object(d: &Document, n: &mut Node) { + if d.setup.align_new_objects_to_pixel_grid && can_align(n) { + n.extras_mut().pixel_aligned = true; + } +} + /// `object.setPixelAligned`: turn the pixel-aligned property of the objects given (or the selected /// objects) on or off. Turning it on snaps them to the pixel grid at once. Every object must be /// one [`can_align`] accepts, else nothing changes. When every object already has the value, the diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 6184860979..d102068947 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -145,16 +145,14 @@ fn apply_transform_moving_guides( } None if copy => { let guide_copies = if with_guides { - let copies: Vec<_> = sel.guides.iter().filter_map(|&i| d.guides.get(i).cloned()).collect(); + let copies: Vec<_> = sel.guides.iter().filter_map(|&i| d.ruler_guide(i)).collect(); (!copies.is_empty()).then_some(copies) } else { None }; let new_ids = duplicate_in(d, sel, &ids, Affine::IDENTITY)?; if let Some(copies) = guide_copies { - let first = d.guides.len(); - d.guides.extend(copies); - sel.guides = (first..d.guides.len()).collect(); + sel.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect(); } new_ids } @@ -177,9 +175,7 @@ fn apply_transform_moving_guides( } if with_guides && (delta.x != 0.0 || delta.y != 0.0) { for i in sel.guides.clone() { - if let Some(g) = d.guides.get_mut(i) { - *g = g.moved(delta); - } + d.edit_ruler_guide(i, |g| *g = g.moved(delta)); } } Ok(targets) @@ -224,10 +220,8 @@ pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: boo let ids = duplicate_in(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY)?; if has_guide_copies { let d = Arc::make_mut(&mut doc); - let first = d.guides.len(); - let copies: Vec<_> = st.selection.guides.iter().filter_map(|&i| d.guides.get(i).cloned()).collect(); - d.guides.extend(copies); - selection.guides = (first..d.guides.len()).collect(); + let copies: Vec<_> = st.selection.guides.iter().filter_map(|&i| d.ruler_guide(i)).collect(); + selection.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect(); } let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), doc, selection, ids }); it.copies = Some(k.clone()); diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 7906a68e85..4cc1fa24c3 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -12,7 +12,7 @@ use vectorcraft_geom::FillRule; use super::appearance::{ItemTarget, item_target}; use super::edit::selected_roots; -use super::{CommandSpec, Result, Session, bad, bool_or, cmd, f64_or, has_doc, ids_param, targets}; +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, ids_param, number_or, switch_or, targets}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -214,22 +214,23 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> { /// Overprint Black on `n` and its descendants; returns the objects changed. fn overprint_black_tree(n: &mut Node, op: &OverprintBlack, spots: &[String]) -> usize { let mut changed = usize::from(op.apply(n, spots)); - for c in n.children_mut().into_iter().flatten() { + for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { changed += overprint_black_tree(Arc::make_mut(c), op, spots); } changed } pub(crate) fn overprint_black(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "edit.colors.overprintBlack"; let op = OverprintBlack { - remove: bool_or(p, "remove", false), - min_k: (f64_or(p, "percentage", 100.0) / 100.0).clamp(0.0, 1.0) as f32, - fill: bool_or(p, "fill", true), - stroke: bool_or(p, "stroke", true), - rich: bool_or(p, "includeCmyBlacks", false), - spot: bool_or(p, "includeSpotBlacks", false), + remove: switch_or(p, "remove", false, C)?, + min_k: (number_or(p, "percentage", 100.0, C)? / 100.0).clamp(0.0, 1.0) as f32, + fill: switch_or(p, "fill", true, C)?, + stroke: switch_or(p, "stroke", true, C)?, + rich: switch_or(p, "includeCmyBlacks", false, C)?, + spot: switch_or(p, "includeSpotBlacks", false, C)?, }; - let ids = match ids_param(p, "ids", "edit.colors.overprintBlack")? { + let ids = match ids_param(p, "ids", C)? { Some(v) => v, None => selected_roots(s)?, }; diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 673ad2cbb8..8d6f53d55b 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -12,9 +12,9 @@ use vectorcraft_doc::{Document, LinkInfo}; use serde_json::{Value, json}; -use super::fileio::{create_dir, write_file}; +use super::fileio::{create_dir, document_path, shown_link, shown_path, write_file}; use super::links::LinkBase; -use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc, str_param, unique_name}; +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name}; const C: &str = "file.package"; @@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> { "Package", [], None, - "{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder", + "{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name", has_doc, package )] @@ -178,8 +178,10 @@ impl<'a> Collector<'a> { /// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the /// copy of `source` finds it only by its name, beside it. + /// `path` is the link's path as the warning names it. fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) { if Path::new(copy).file_name().and_then(std::ffi::OsStr::to_str) != Some(name) { + let source = shown_path(source); let message = format!( "{path}: copied as {copy}; the copy of {source} looks for it as {name} and shows the file of that name, if any, else its preview" ); @@ -207,11 +209,13 @@ impl<'a> Collector<'a> { let section = self.sections.len(); self.sections.push(vec![]); let mut lines = vec![]; - // The packaged document's sections read as before; a placed document's name its file. + // The packaged document's sections read as before; a placed document's name its file. The + // report and the warnings name a file outside a confined request's read roots by its name. + let shown_source = shown_path(source); let heading = |lines: &mut Vec<String>, title: &str| { lines.push(title.into()); if depth > 0 { - lines.push(format!("Document: {source}")); + lines.push(format!("Document: {shown_source}")); } }; // A file's saved path is only meaningful inside its own document. @@ -243,17 +247,21 @@ impl<'a> Collector<'a> { heading(&mut lines, "LINKED FILES"); for file in linked_files(doc) { let found_path = file.found_path.as_deref().unwrap_or(&file.path); + // The stored path, whole when the place it names (read from this document's folder) is + // inside the read roots. A file found elsewhere does not show a stored path outside them. + let resolved = document_path(&file.path, Some(source)).ok(); + let shown = shown_link(&file.path, resolved.as_deref()).into_owned(); if let Some(ancestor) = self.visiting.get(found_path).cloned() { // The ancestor is already included (possibly the root document). A // cyclic reference cannot have a final content hash until both files // have been written, so leave its size/hash unspecified, not stale. - self.warn(&mut lines, format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path)); + self.warn(&mut lines, format!("{shown}: circular placed-document link to {ancestor}; stopped following the cycle")); local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None }); continue; } if let Some(existing) = self.copies.get(found_path).cloned() { if by_name { - self.renamed(&mut lines, source, &file.path, &file.name, &existing.name); + self.renamed(&mut lines, source, &shown, &file.name, &existing.name); } // Another document may place other pages of a PDF copied already. if self.opts.copy_fonts @@ -265,8 +273,8 @@ impl<'a> Collector<'a> { continue; } let Some(mut bytes) = file.bytes else { - lines.push(format!("{}: not found ({}), not copied", file.name, file.path)); - self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) }); + lines.push(format!("{}: not found ({shown}), not copied", file.name)); + self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({shown_source})", file.name) }); continue; }; if self.copies.len() >= 10_000 { @@ -277,7 +285,7 @@ impl<'a> Collector<'a> { let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken }); let destination_file = format!("{dir}{unique}"); if by_name { - self.renamed(&mut lines, source, &file.path, &file.name, &destination_file); + self.renamed(&mut lines, source, &shown, &file.name, &destination_file); } // A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file // read from its editing data links are copied beside it. @@ -285,7 +293,7 @@ impl<'a> Collector<'a> { let placed_file = pages.is_some(); if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) { if depth >= vectorcraft_doc::placed_document::MAX_DEPTH { - self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path)); + self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links")); } else { self.collect(&mut art, found_path, &destination_file, depth + 1, true, None)?; } @@ -296,7 +304,7 @@ impl<'a> Collector<'a> { } if placed_file && super::place::document::is_native(&file.name, &bytes) { if depth >= vectorcraft_doc::placed_document::MAX_DEPTH { - self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path)); + self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links")); } else { match vectorcraft_format::load_file(&bytes) { Ok(saved) => { @@ -320,8 +328,7 @@ impl<'a> Collector<'a> { Err(e) => self.warn( &mut lines, format!( - "{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked", - file.path + "{shown}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked" ), ), } @@ -329,7 +336,7 @@ impl<'a> Collector<'a> { } Err(e) => self.warn( &mut lines, - format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path), + format!("{shown}: unreadable linked document ({e}); copied unchanged, its own links were not collected"), ), } } @@ -337,7 +344,7 @@ impl<'a> Collector<'a> { let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); - lines.push(format!("{} → {destination_file}", file.path)); + lines.push(format!("{shown} → {destination_file}")); self.entries.push((destination_file, bytes)); } lines.push(String::new()); @@ -451,19 +458,20 @@ impl Session { /// name, the report's Document Info text and the document. fn prepare(s: &mut Session, p: &Value) -> Result<Package> { let o = Options { - copy_links: bool_or(p, "copyLinks", true), - links_folder: bool_or(p, "linksFolder", true), - relink: bool_or(p, "relink", true), - copy_fonts: bool_or(p, "copyFonts", true), - report: bool_or(p, "report", true), + copy_links: switch_or(p, "copyLinks", true, C)?, + links_folder: switch_or(p, "linksFolder", true, C)?, + relink: switch_or(p, "relink", true, C)?, + copy_fonts: switch_or(p, "copyFonts", true, C)?, + report: switch_or(p, "report", true, C)?, }; + let given_name = text_param(p, "name", C)?; + let folder = text_param(p, "folder", C)?; let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?; let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); - let name = str_param(p, "name").map_or_else(|| format!("{stem} Folder"), str::to_string); + let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string); if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) { return Err(bad(C, format!("`{name}` can't name a folder"))); } - let folder = str_param(p, "folder"); let root = folder.map(|f| Path::new(f).join(&name)); let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None }; let doc = s.doc()?.doc.clone(); @@ -517,7 +525,7 @@ fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Res // The report. if let Some(info) = info { let report_name = free_name(&format!("{stem} Report.txt"), &mut taken); - let mut text = format!("Package: {doc_name}\nFrom: {doc_path}\n\n"); + let mut text = format!("Package: {doc_name}\nFrom: {}\n\n", shown_path(&doc_path)); lines.iter().for_each(|l| text.push_str(&format!("{l}\n"))); text.push_str(&info); entries.push((report_name, text.into_bytes())); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 4cc4bbc2e4..b199f9a356 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -242,6 +242,10 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool { /// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and /// other containers inside them), a compound path for its parts. pub(crate) fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) { + // A ruler guide has no paints. + if n.is_ruler_guide() { + return; + } let expand = match n.kind { NodeKind::Group { .. } | NodeKind::Layer { .. } => true, NodeKind::Compound { .. } => false, @@ -637,7 +641,7 @@ fn paint_new_art(s: &mut Session, paint: &Paint, fill: bool) { } } -/// Does `p` ask for `span: "selection"` (#2127)? Only a linear or radial gradient the targets +/// Does `p` ask for `span: "selection"` (#2127)? Only a linear, radial, conic or diamond gradient the targets /// would each fit to their own bounds can span them: one with its own vector (`start`/`end`), /// a freeform one or a gradient swatch already has its placement. fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> { @@ -652,7 +656,7 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> return Err("span: \"selection\" places a `gradient`, not a swatch".into()); } if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some() { - return Err("span: \"selection\" places a linear or radial gradient, not a freeform one".into()); + return Err("span: \"selection\" places a linear, radial, conic or diamond gradient, not a freeform one".into()); } if g.geom.is_some() { return Err( diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 9f50507aff..83a0655284 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment)", has_doc, set_format ), @@ -352,7 +352,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val for &i in indices.iter().rev() { let gone = d.artboards.remove(i).id; d.retire_artboard_id(gone); - d.retain_guides(sel, |_, g| g.artboard != Some(gone)); + d.retain_guides(sel, |g| g.artboard != Some(gone)); } d.remove_many(&art)?; sel.prune(d); @@ -482,6 +482,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "hyphenate", "hyphenateCapitalized", "romanHangingPunctuation", + "koreanLineBreakAnywhere", ], C, )?; @@ -552,6 +553,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { "fontAxes", "burasagari", "romanHangingPunctuation", + "koreanLineBreakAnywhere", "kashida", "composer", ]; @@ -879,6 +881,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> { if let Some(v) = flag("romanHangingPunctuation") { para.roman_hanging = v; } + if let Some(v) = flag("koreanLineBreakAnywhere") { + para.korean_line_break_anywhere = v; + } if let Some(v) = kashida { para.kashida = v; } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index c9f51e0654..60fa90c32c 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -51,7 +51,7 @@ pub struct ParamKeys<'a> { /// The text between the braces of the object `doc` starts with and what follows it, or why it /// has none. -fn object_body(doc: &str) -> std::result::Result<(&str, &str), String> { +pub(crate) fn object_body(doc: &str) -> std::result::Result<(&str, &str), String> { // (Named, not written in the `Err`: these are for the tests of the descriptions, not messages // the app shows, which the message catalogs would have to translate.) let (no_object, not_closed) = ("the description doesn't start with the params object `{…}`", "the params object `{…}` isn't closed"); @@ -78,7 +78,7 @@ fn object_body(doc: &str) -> std::result::Result<(&str, &str), String> { } /// `s` split at each `sep` that is outside brackets, quotes and backticks. -fn split_top(s: &str, sep: char) -> Vec<&str> { +pub(crate) fn split_top(s: &str, sep: char) -> Vec<&str> { let (mut out, mut depth, mut quote, mut start) = (Vec::new(), 0usize, None, 0); for (i, c) in s.char_indices() { match (quote, c) { @@ -98,7 +98,7 @@ fn split_top(s: &str, sep: char) -> Vec<&str> { out } -fn is_key(s: &str) -> bool { +pub(crate) fn is_key(s: &str) -> bool { let mut chars = s.chars(); chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') } @@ -317,6 +317,14 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") { return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`")); } + // A Warp's map is one this build draws: 0, the earlier map, or its style's Bézier net. + let newest = vectorcraft_render::effects::WARP_NET; + if effect.starts_with("warp.") + && let Some(v) = given.get("version") + && vectorcraft_render::effects::warp_version(v).is_none() + { + return Err(bad(id, format!("`version` must be 0 or {newest}"))); + } check_effect_color(id, effect, params)?; check_effect_channel(id, effect, params) } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d00ba7192c..c05493e964 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -12,7 +12,7 @@ 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_selected_path, - has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets, + has_selection, ids_param, index, number_or, object_param, ok, str_param, switch_or, targets, }; use crate::EngineError; @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Close Path", [], None, - "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor), independent?: bool}", + "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}", has_doc, close ), @@ -168,7 +168,7 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result< } fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.appendAnchor", "missing id"))?; + let id = object_param(p, "id", "path.appendAnchor")?.ok_or_else(|| bad("path.appendAnchor", "missing id"))?; let a = anchor_from_json(p, "path.appendAnchor")?; let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize); s.edit("Pen", |d, sel| { @@ -202,14 +202,18 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> { ok() } -/// Close the active open subpath of `id`, optionally setting the incoming handle of the first anchor. +/// Close the active open subpath of `id`, optionally setting the handles of the first anchor. The +/// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only +/// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape. fn close(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?; + let id = object_param(p, "id", "path.close")?.ok_or_else(|| bad("path.close", "missing id"))?; let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize); - let h_in = match p.get("in").filter(|h| !h.is_null()) { - None => None, - Some(h) => Some(finite_numbers(h).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.close", "`in` must be [x, y]"))?), + let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) { + None => Ok(None), + Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))), }; + let h_in = handle("in")?; + let h_out = handle("out")?; let independent = switch_or(p, "independent", false, "path.close")?; s.edit("Close Path", |d, sel| { let path = path_mut(d, id)?; @@ -218,11 +222,13 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> { None => path.subpaths.iter_mut().rev().find(|s| !s.closed).ok_or_else(|| EngineError::Other("path is already closed".into()))?, }; sp.closed = true; - if let (Some(h), Some(first)) = (h_in, sp.anchors.first_mut()) { - first.h_in = h; - if !independent { - first.h_out = first.p - (h - first.p); - first.kind = AnchorKind::Smooth; + if let Some(first) = sp.anchors.first_mut() { + if let Some(h) = h_in { + first.set_handle(false, h, independent); + } + if let Some(h) = h_out { + first.h_out = h; + first.kind = AnchorKind::Corner; } } let top = compound_or_self(d, id); @@ -289,9 +295,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge } if is_translation && (delta.x != 0.0 || delta.y != 0.0) { for &i in &sel.guides { - if let Some(g) = doc.guides.get_mut(i) { - *g = g.moved(delta); - } + doc.edit_ruler_guide(i, |g| *g = g.moved(delta)); } } Ok(()) @@ -299,7 +303,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge } fn set_handle(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.setHandle", "missing id"))?; + let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?; let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0); let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.setHandle", "missing anchor"))?; let out = str_param(p, "which") != Some("in"); @@ -317,7 +321,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> { /// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point /// tool's Shift-drag). fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.moveAnchor", "missing id"))?; + let id = object_param(p, "id", "path.moveAnchor")?.ok_or_else(|| bad("path.moveAnchor", "missing id"))?; let si = usize_opt(p, "subpath", "path.moveAnchor")?.unwrap_or(0); let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.moveAnchor", "missing anchor"))?; let pos = Point::new(f64_req(p, "x", "path.moveAnchor")?, f64_req(p, "y", "path.moveAnchor")?); @@ -337,7 +341,7 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> { } fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.setAnchors", "missing id"))?; + let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?; let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?; let data = PathData::new( subs.iter() @@ -1232,7 +1236,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> { s.edit("Clear", |d, selection| { if with_guides { let gone = selection.guides.clone(); - d.retain_guides(selection, |i, _| !gone.contains(&i)); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); } let targets: BTreeSet<NodeId> = whole.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.is_layer())).collect(); let whole_ids: Vec<NodeId> = targets @@ -1558,7 +1562,7 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz } fn reshape(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.reshape", "missing id"))?; + let id = object_param(p, "id", "path.reshape")?.ok_or_else(|| bad("path.reshape", "missing id"))?; let at = Point::new(f64_req(p, "x", "path.reshape")?, f64_req(p, "y", "path.reshape")?); check_numbers(p, &["dx", "dy", "tol", "radius"], "path.reshape")?; let delta = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0)); @@ -1680,7 +1684,7 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> { } fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("path.insertAnchor", "missing id"))?; + let id = object_param(p, "id", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing id"))?; let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0); let seg = p.get("segment").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.insertAnchor", "missing segment"))?; let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 3da73c0385..5b9e25d354 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -1351,7 +1351,9 @@ fn split_into_grid(s: &mut Session, p: &Value) -> Result<Value> { let node = shape_node(d, c, Some(&top)); out.push(d.insert(par, idx + k, node)?); } - d.guides.extend(edges.iter().map(|&(vertical, pos)| vectorcraft_doc::Guide { layer, ..vectorcraft_doc::Guide::new(vertical, pos) })); + for &(vertical, pos) in &edges { + d.add_ruler_guide(&vectorcraft_doc::Guide { layer, ..vectorcraft_doc::Guide::new(vertical, pos) }); + } sel.set(out.iter().copied()); Ok(out) })?; diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index ef7820b71f..4075676ca6 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -116,7 +116,7 @@ pub fn specs() -> Vec<CommandSpec> { "Mirror", ["Object", "Repeat"], None, - "{ids?, angle?: deg (90 = vertical axis), offset?: pt (10)} mirror repeat of the selection → {id}", + "{ids?, angle?: deg clockwise from level (the mirror axis; 90 = vertical), offset?: pt (10)} mirror repeat of the selection → {id}", has_selection, repeat_mirror ), @@ -134,7 +134,7 @@ pub fn specs() -> Vec<CommandSpec> { "Options…", ["Object", "Repeat"], None, - "{instances?, radius?, reverseOverlap?, startAngle?, endAngle?, center?: [x,y] | hSpacing?, vSpacing?, rows?, cols?, gridType?, brickOffset?, flipRows?, flipCols? | angle?} set the options of the selected repeats", + "{instances?, radius?, reverseOverlap?, startAngle?, endAngle?: deg clockwise (0: where the source art sits), center?: [x,y] | hSpacing?, vSpacing?, rows?, cols?, gridType?, brickOffset?, flipRows?, flipCols? | angle?: deg clockwise from level (the mirror axis; 90 = vertical)} set the options of the selected repeats", has_repeat, repeat_options ), @@ -271,8 +271,9 @@ fn enter_edit(d: &mut Document, sel: &mut Selection, name: &str, original: Optio /// Leave editing mode: drop the layer, return the edit record. fn leave_edit(d: &mut Document, sel: &mut Selection) -> Result<(PatternEdit, Vec<Arc<Node>>)> { let pe = d.pattern_edit.take().ok_or_else(|| EngineError::Other("not in pattern editing mode".into()))?; - let art = match d.remove(pe.layer) { - Ok(l) => l.children().cloned().unwrap_or_default(), + // The tile art: ruler guides on the edit layer are not part of it and stay in the document. + let art = match d.remove_edit_layer(pe.layer) { + Ok(l) => l.children().into_iter().flatten().cloned().collect(), Err(_) => vec![], }; sel.clear(); @@ -427,7 +428,8 @@ fn pattern_save_copy(s: &mut Session, p: &Value) -> Result<Value> { let name = s.edit("Save a Copy", |d, _| { let pe = d.pattern_edit.clone().ok_or_else(|| EngineError::Other("not in pattern editing mode".into()))?; let mut def = d.pattern(&pe.pattern).cloned().ok_or_else(|| EngineError::Other("pattern missing".into()))?; - let art: Vec<Arc<Node>> = d.node(pe.layer).and_then(|l| l.children().cloned()).unwrap_or_default(); + let art: Vec<Arc<Node>> = + d.node(pe.layer).into_iter().flat_map(|l| l.children().into_iter().flatten()).filter(|c| !c.is_ruler_guide()).cloned().collect(); let name = unique_pattern_name(d, wanted.as_deref().unwrap_or(&format!("{} copy", pe.pattern.trim()))); def.name = name.clone(); def.art = copies(d, &art).into_iter().map(Arc::new).collect(); @@ -481,7 +483,8 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> { let out_name = new_name.clone().unwrap_or(name.clone()); s.edit("Pattern Options", |d, _| { // While editing, the tile art is the edit layer's. - let live_art: Option<Vec<Arc<Node>>> = edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children().cloned()); + let live_art: Option<Vec<Arc<Node>>> = + edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect()); let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?; def.tile_type = tt; def.overlap = overlap; diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 011dfc131c..8fd2a0ea5e 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -23,8 +23,10 @@ pub struct BuiltinPatternLibrary { } /// The built-in pattern libraries (Window → Swatch Libraries → Patterns), in menu order. -pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = - &[BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }]; +pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = &[ + BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }, + BuiltinPatternLibrary { id: "grit-textures", name: "Grit Textures", make: grit_textures }, +]; /// The library category of the built-in pattern libraries. pub const CATEGORY: &str = "patterns"; @@ -154,6 +156,106 @@ fn geometric_patterns(d: &mut Document) { add(d, "Zigzag", 10.0, 8.0, TileType::Grid, vec![polygon(&[(0.0, 5.0), (5.0, 1.0), (10.0, 5.0), (10.0, 7.0), (5.0, 3.0), (0.0, 7.0)])]); } +/// SplitMix64, a small generator with a fixed seed per pattern, so a grit pattern draws the same +/// marks every time it is made. +struct SplitMix64(u64); + +impl SplitMix64 { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A number from `lo` up to, but not including, `hi`. + fn range(&mut self, lo: f64, hi: f64) -> f64 { + lo + (self.next() >> 11) as f64 / (1u64 << 53) as f64 * (hi - lo) + } +} + +/// A round dot of radius `r` at (`x`, `y`). +fn dot(x: f64, y: f64, r: f64) -> PathData { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)) +} + +/// An irregular fleck of four to seven corners about (`x`, `y`), at most `r` from it. +fn fleck(rng: &mut SplitMix64, x: f64, y: f64, r: f64) -> PathData { + use std::f64::consts::TAU; + let n = 4 + (rng.next() % 4) as usize; + let turn = rng.range(0.0, TAU); + let points: Vec<(f64, f64)> = (0..n) + .map(|k| { + let a = turn + TAU * (k as f64 + rng.range(-0.3, 0.3)) / n as f64; + let reach = r * rng.range(0.55, 1.0); + (x + reach * a.cos(), y + reach * a.sin()) + }) + .collect(); + polygon(&points) +} + +/// A thin straight scratch `len` long and `width` wide, centered on (`x`, `y`) at a random angle. +fn scratch(rng: &mut SplitMix64, x: f64, y: f64, len: f64, width: f64) -> PathData { + let (s, c) = rng.range(0.0, std::f64::consts::PI).sin_cos(); + let (hx, hy, wx, wy) = (c * len / 2.0, s * len / 2.0, -s * width / 2.0, c * width / 2.0); + polygon(&[(x - hx - wx, y - hy - wy), (x + hx - wx, y + hy - wy), (x + hx + wx, y + hy + wy), (x - hx + wx, y - hy + wy)]) +} + +/// A grit pattern of `count` marks scattered over a square grid tile of side `size`, drawn from +/// `seed` (`mark` draws one at a point). A mark that reaches past an edge is kept whole: the tiling +/// draws the part outside the tile on the next tile, so the tiles join without a seam. +fn grit(d: &mut Document, name: &str, size: f64, seed: u64, count: usize, mark: impl Fn(&mut SplitMix64, f64, f64) -> PathData) { + let mut rng = SplitMix64(seed); + let marks = (0..count) + .map(|_| { + let (x, y) = (rng.range(0.0, size), rng.range(0.0, size)); + mark(&mut rng, x, y) + }) + .collect(); + add(d, name, size, size, TileType::Grid, marks); +} + +/// Grit Textures: seamless black grain, grit, sand, speckle, stipple, scratch and fleck textures on +/// a clear background, each drawn from its own fixed seed. +fn grit_textures(d: &mut Document) { + grit(d, "Fine Grain", 24.0, 1, 320, |rng, x, y| dot(x, y, rng.range(0.15, 0.35))); + grit(d, "Coarse Grit", 30.0, 2, 150, |rng, x, y| { + let r = rng.range(0.45, 1.1); + fleck(rng, x, y, r) + }); + grit(d, "Sand", 24.0, 3, 280, |rng, x, y| { + let r = rng.range(0.2, 0.45); + fleck(rng, x, y, r) + }); + grit(d, "Speckle", 30.0, 4, 90, |rng, x, y| dot(x, y, rng.range(0.3, 0.9))); + // Stipple: one dot in each cell of a 12 × 12 grid, moved a little off the cell's center. + let mut rng = SplitMix64(5); + let (size, cells) = (24.0, 12); + let step = size / f64::from(cells); + let dots = (0..cells) + .flat_map(|row| (0..cells).map(move |col| (col, row))) + .map(|(col, row)| { + let x = (f64::from(col) + 0.5) * step + rng.range(-0.3, 0.3) * step; + let y = (f64::from(row) + 0.5) * step + rng.range(-0.3, 0.3) * step; + dot(x, y, rng.range(0.3, 0.45)) + }) + .collect(); + add(d, "Stipple", size, size, TileType::Grid, dots); + grit(d, "Scratches", 36.0, 6, 45, |rng, x, y| { + let (len, width) = (rng.range(2.0, 7.0), rng.range(0.15, 0.35)); + scratch(rng, x, y, len, width) + }); + grit(d, "Sparse Flecks", 36.0, 7, 32, |rng, x, y| { + let r = rng.range(0.35, 0.8); + fleck(rng, x, y, r) + }); + grit(d, "Dense Flecks", 18.0, 8, 220, |rng, x, y| { + let r = rng.range(0.2, 0.5); + fleck(rng, x, y, r) + }); +} + #[cfg(test)] mod tests { use super::*; @@ -168,4 +270,60 @@ mod tests { assert_eq!(existing_pattern(&d, &lib, "Dots").as_deref(), expected, "{other}"); } } + + fn grit_doc() -> Document { + let mut d = Document::new(100.0, 100.0); + grit_textures(&mut d); + d + } + + #[test] + fn grit_textures_draw_the_same_marks_every_time() { + let (a, b) = (grit_doc(), grit_doc()); + assert_eq!(a.patterns.len(), 8); + assert_eq!(a.patterns, b.patterns); + } + + /// Every grit tile is 18 to 36 pt with at most 600 marks, each with an area, touching the tile + /// and near it. Marks reach past the edges, and the tiling draws a tile's art on the next tile + /// across each edge a mark crosses. No mark is another mark moved by a whole tile, which the tiling would draw + /// twice in one place. + #[test] + fn grit_tiles_join_without_a_seam() { + let mut crossing = 0; + for p in &grit_doc().patterns { + let (w, h) = (p.width(), p.height()); + assert!((18.0..=36.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name); + assert!(!p.art.is_empty() && p.art.len() <= 600, "{}: {} marks", p.name, p.art.len()); + let bounds: Vec<Rect> = p + .art + .iter() + .map(|n| match &n.kind { + vectorcraft_doc::NodeKind::Path { path, .. } => path.bounds().unwrap_or_else(|| panic!("{}: an empty mark", p.name)), + _ => panic!("{}: a mark that is not a path", p.name), + }) + .collect(); + let near = |a: &Rect, b: Rect| { + (a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9 + }; + let band = p.tile.inflate(w / 4.0, h / 4.0); + for b in &bounds { + assert!(b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name); + assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name); + assert!(b.x0 >= band.x0 && b.y0 >= band.y0 && b.x1 <= band.x1 && b.y1 <= band.y1, "{}: {b:?} is too far out", p.name); + // The tile past each edge the mark crosses draws this tile's art. + let (dx, dy) = (f64::from(i8::from(b.x1 > w) - i8::from(b.x0 < 0.0)), f64::from(i8::from(b.y1 > h) - i8::from(b.y0 < 0.0))); + for (x, y) in [(dx, 0.0), (0.0, dy), (dx, dy)] { + let next = p.tile + kurbo::Vec2::new(x * w, y * h); + assert!(p.offsets_covering(next).contains(&kurbo::Vec2::ZERO), "{}: {b:?} is cut off at {next:?}", p.name); + } + crossing += usize::from(dx != 0.0 || dy != 0.0); + for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] { + let moved = *b + kurbo::Vec2::new(dx, dy); + assert!(!bounds.iter().any(|o| near(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name); + } + } + } + assert!(crossing > 0, "no mark reaches past an edge"); + } } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index db9bbf67d1..5d56a2b646 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -5,7 +5,7 @@ //! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with //! `link` ([`super::links`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options -//! (`dxf`, [`fileio::dxfimport`]). +//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). //! - An EMF or WMF picture becomes one group, clipped to its frame (`crop: "crop"`) or bounded by //! its art (`crop: "bounding"`). //! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by @@ -47,7 +47,10 @@ use vectorcraft_geom::{Affine, Point, Rect, shapes}; use vectorcraft_pdf::CropTo; use super::fileio::{self, Format, RasterImage}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, object_param, str_param, unique_name}; +use super::{ + CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, finite_numbers, has_doc, object_param, str_param, + switch_or, unique_name, +}; use crate::{EngineError, MAX_COORD}; const PLACE: &str = "file.place"; @@ -66,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -84,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> { "Image Info", [], None, - "{id?} an image object (default: the one selected) → {id, name, linked, link, colorMode: RGB|Grayscale|CMYK, pixelWidth, pixelHeight, ppi: [x, y] at its placed size, width, height}", + "{id?} an image object (default: the one selected) → {id, name, linked, link (the linked file's path; null when embedded, or when automation read roots are in force and the file is outside them), colorMode: RGB|Grayscale|CMYK, pixelWidth, pixelHeight, ppi: [x, y] at its placed size, width, height}", has_doc, image_info ), @@ -261,7 +264,7 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored); let layers = std::mem::take(&mut doc.layers); let symbols = doc.symbol_boxes(); - let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf") { + let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") { // An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard), // as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By // default, as Illustrator places one, it is its art's bounds. @@ -377,7 +380,7 @@ fn placeable(l: &Node) -> bool { fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> { nodes .filter_map(|c| match &c.kind { - NodeKind::Path { guide: true, .. } => None, + _ if c.is_guide() => None, NodeKind::Layer { children, clip, .. } => placeable(c).then(|| { let mut g = (**c).clone(); g.kind = NodeKind::Group { children: art_of(children.iter()).into_iter().map(Arc::new).collect(), clip: *clip }; @@ -556,8 +559,9 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> { } fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> { - let replace = bool_or(p, "replace", false); - let template = bool_or(p, "template", false); + let replace = switch_or(p, "replace", false, PLACE)?; + let template = switch_or(p, "template", false, PLACE)?; + check_switches(p, &["link"], PLACE)?; let at = at_param(p)?; let rect = rect_param(p)?; if replace && (template || at.is_some() || rect.is_some()) { @@ -778,6 +782,8 @@ impl Session { /// desktop the Place dialog's OK with several files does this off the UI thread). pub fn prepare_place_queue(&self, params: &Value) -> Result<QueueJob> { has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?; + check_switches(params, &["link", "template"], QUEUE)?; + check_numbers(params, &["thumbnail"], QUEUE)?; Ok(QueueJob { params: params.clone(), files: queued_files(params)? }) } @@ -846,6 +852,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> { /// `file.place.info` with `p`, without the session (on the desktop the Place dialog reads its /// files' lines this way off the UI thread). pub fn read_info(p: &Value) -> Result<Value> { + check_switches(p, &["link"], "file.place.info")?; + check_numbers(p, &["thumbnail"], "file.place.info")?; // A PDF/.ai page linked or not has the same size and art. let mut l = load(p, "file.place.info", None, false)?; let natural = l.natural; @@ -883,11 +891,13 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> { let [a, b, c, d, ..] = im.xf.as_coeffs(); let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); let size = n.geometric_bounds().unwrap_or_default(); + // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. + let doc_path = super::links::LinkBase::of(st).doc; Ok(json!({ "id": id.0, "name": n.display_name(), "linked": im.link.is_some(), - "link": im.link.as_ref().map(|l| &l.path), + "link": im.link.as_ref().map(|l| &l.path).filter(|path| super::links::path_shown(path, doc_path)), "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index ab5562b5f9..25f5f36dbd 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -108,7 +108,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char { } /// Byte `b` of Mac Roman. -pub(super) fn mac_roman(b: u8) -> char { +pub(in crate::cmd) fn mac_roman(b: u8) -> char { const HIGH: [char; 128] = [ 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index a5b71d538b..2d16bbc683 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -52,7 +52,7 @@ use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; -use vectorcraft_plugins::permissions::{self, Grant, Permission}; +use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission}; /// What a plug-in error looks like to the user. A run the caller cancelled changed nothing. fn err(e: vectorcraft_plugins::Error) -> EngineError { @@ -741,17 +741,18 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> { } // Installed plug-ins stay installed after a restart (#2541). The module is written first and its // grant only once it is there; when the grant can't be written, the store gets the module it - // held back. A failed write of that module is only logged, and the grant then doesn't cover - // the new module. A stored module that can't be read back isn't replaced by one that needs a - // grant. + // held back. A failed write of that module is only logged: the store then holds the new module, + // which the grant doesn't cover. A write that reports a failure may still have put the old + // module back, so the store is read again to tell which module it holds. A stored module that + // can't be read back isn't replaced by one that needs a grant. let previous = s.stored_plugin_bytes(plugin.id()); let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes); + let holds_new = |s: &Session| s.stored_plugin_bytes(plugin.id()).is_ok_and(|held| held.as_deref() == Some(&bytes[..])); if m.asks_permissions() { let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted }; - registry::grant(g.clone()); + registry::grant(GrantToken::after_engine_approval(g.clone())); if stored && !s.store_grant(&m.id, Some(g)) { - s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()); - stored = false; + stored = !s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()) && holds_new(s); } } else { // This module takes the id over, so nothing the user approved for the id applies any more. @@ -759,14 +760,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> { // When the write failed, the old stored module stays in the folder and needs its grant at // the next launch. A grant that can't be removed still approves the old bytes, so the store // gets the module it held back. When that module can't be read or written back, or there - // was none, no module goes with the grant, and the grant stops counting for this session. A - // grants file that is too large or doesn't hold a list approves nothing, and the new module - // stays; one that can't be opened or read may approve the old bytes once it reads again. + // was none, no module goes with the grant, and the grant stops counting for every session in + // the process attached to the folder. A grants file that is too large or doesn't hold a list + // approves nothing, and the new module stays; one that can't be opened or read may approve + // the old bytes once it reads again. + let writes = s.grant_writes(); if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) { let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref())); - stored = !back; + stored = !back && holds_new(s); if !back || matches!(previous, Ok(None)) { - s.ignore_stored_grant(&m.id); + s.ignore_stored_grant(&m.id, writes); } } } @@ -786,7 +789,8 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> { if changed { s.store_disabled_plugins(); } - let mut v = describe_installed(®istry::install(plugin)); + let installed = registry::install(plugin).map_err(err)?; + let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); } @@ -885,7 +889,7 @@ fn load_folder(s: &Session, folder: &str) -> Value { None if crate::file_access::current().is_none() => Ok(()), None => Err(format!("automation path rejected: {} isn't valid text", f.display())), }; - match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_approver()) { + match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) { Ok(r) => { for id in &r.loaded { s.attach_plugin_storage(id); @@ -1096,7 +1100,7 @@ pub fn specs() -> Vec<CommandSpec> { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", always, remove ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f7c7003b11..329cb59cf2 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -32,6 +32,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.color.strokeToFill", "addon.color.swatchLegend", "addon.contour.set", + "addon.cutting.bridges", + "addon.image.removeBackground", "addon.pathtools.addPoints", "addon.pathtools.close", "addon.pathtools.corner", @@ -107,7 +109,9 @@ pub(super) const ALLOWED: &[&str] = &[ "brush.move", "brush.new", "brush.options", + "brush.placeArt", "brush.remove", + "brush.replaceArt", "brush.selectionArt", "brush.setCurrent", "brush.unused", @@ -396,6 +400,7 @@ pub(super) const ALLOWED: &[&str] = &[ "paraStyle.apply", "paraStyle.delete", "paraStyle.duplicate", + "paraStyle.edit", "paraStyle.list", "paraStyle.new", "paraStyle.redefine", @@ -484,6 +489,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.object.brushStrokes", "select.object.clippingMasks", "select.object.directionHandles", + "select.object.notAlignedToPixelGrid", "select.object.pointText", "select.object.slices", "select.object.strayPoints", @@ -578,6 +584,7 @@ pub(super) const ALLOWED: &[&str] = &[ "symbol.replace", "symbol.selectInstances", "symbol.setCurrent", + "symbol.sortByName", "symbol.spray", "symbol.unused", "symbol.update", @@ -631,12 +638,15 @@ pub(super) const ALLOWED: &[&str] = &[ "type.convertToAreaType", "type.convertToPointType", "type.createOutlines", + "type.dynamicText", "type.fillPlaceholder", "type.fitHeadline", "type.insert", "type.opticalMarginAlignment", "type.orientation.horizontal", "type.orientation.vertical", + "type.pathCenter.bottom", + "type.pathCenter.top", "type.pathOptions", "type.resetHorizontalScale", "type.resetTracking", @@ -671,6 +681,7 @@ pub(super) const DENIED: &[&str] = &[ "addon.pen.nextSegment", "effect.refreshDeferred", "graphicStyle.setOptions", + "object.blend.createSpine", "object.blend.options", "object.liquify", "object.pathfinder.options", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index a92b4095a9..af09b032da 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -687,6 +687,10 @@ impl Session { for e in self.prefs.keep_folders(&mut p) { log::warn!("{e}"); } + // Saved gradient presets get names no built-in preset or other saved one has. + for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) { + log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name"); + } // The edit the active tool computes on another thread is applied first (the Preferences // dialog applies its settings here, outside a command). A failure to apply it was the // edit's own, and the preferences apply all the same. @@ -765,7 +769,7 @@ impl Session { pub fn specs() -> Vec<CommandSpec> { vec![ - cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}", always, get), + cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}; under automation read roots a folder preference outside them is null, and an export preset's folder outside them is left out", always, get), cmd!( query "prefs.set", "Set Preference", @@ -776,7 +780,7 @@ pub fn specs() -> Vec<CommandSpec> { set ), cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset), - cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list), + cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list), cmd!( query "prefs.export", "Export Preferences", @@ -882,8 +886,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({ "imported": values.len() })) } +/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks. +const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"]; + +/// The scratch disk choices that are not folders. +const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"]; + +/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the +/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside +/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is +/// left out. An empty value (the default folder) and a scratch +/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are. +fn shown_prefs(prefs: &Prefs) -> Value { + let mut all = prefs.to_json(); + if crate::file_access::current().is_none() { + return all; + } + // The app trims a folder before it uses it. + let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err(); + for key in PATH_PREFS { + let Some(path) = all[key].as_str() else { continue }; + if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) { + all[key] = Value::Null; + } + } + if let Some(presets) = all.get_mut("screenExportPresets").and_then(Value::as_array_mut) { + for settings in presets.iter_mut().filter_map(|p| p.get_mut("settings").and_then(Value::as_object_mut)) { + if settings.get("folder").and_then(Value::as_str).is_some_and(hidden) { + settings.remove("folder"); + } + } + } + all +} + fn get(s: &mut Session, p: &Value) -> Result<Value> { - let all = s.prefs.to_json(); + let all = shown_prefs(&s.prefs); match str_param(p, "key") { Some(k) if spec(k).is_some() || PREF_GROUPS.contains(&k) => Ok(all[k].clone()), Some(k) => Err(bad("prefs.get", format!("unknown preference `{k}`"))), @@ -911,7 +949,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> { if document_units && values.contains_key("unitsGeneral") && s.active().is_some() { s.set_document_units(s.default_units())?; } - let all = s.prefs.to_json(); + let all = shown_prefs(&s.prefs); Ok(Value::Object(values.keys().map(|k| (k.clone(), all[k.as_str()].clone())).collect())) } @@ -925,11 +963,11 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> { let mut next = s.prefs.clone(); next.reset(cat); s.apply_prefs(next); - Ok(json!({ "prefs": s.prefs.to_json() })) + Ok(json!({ "prefs": shown_prefs(&s.prefs) })) } fn list(s: &mut Session, _: &Value) -> Result<Value> { - let all = s.prefs.to_json(); + let all = shown_prefs(&s.prefs); Ok(Value::Array( PREF_SPECS .iter() diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 76e09641f9..9fe4665a5c 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index 537658447b..8e1c3f5be8 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -48,12 +48,13 @@ pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[F Ok(Some(flatten_document(&printed, &o)?.unwrap_or_else(|| printed.into_owned()))) } -/// Leave guide paths out of `nodes` (the renderer draws them; they never print). +/// Leave guides out of `nodes`: guide paths (the renderer draws them; they never print) and ruler +/// guides. fn drop_guides(nodes: &mut Vec<Arc<Node>>) { fn has_guides(n: &Node) -> bool { - matches!(n.kind, NodeKind::Path { guide: true, .. }) || n.children().is_some_and(|c| c.iter().any(|c| has_guides(c))) + n.is_guide() || n.children().is_some_and(|c| c.iter().any(|c| has_guides(c))) } - nodes.retain(|n| !matches!(n.kind, NodeKind::Path { guide: true, .. })); + nodes.retain(|n| !n.is_guide()); for n in nodes.iter_mut().filter(|n| has_guides(n)) { if let Some(children) = Arc::make_mut(n).children_mut() { drop_guides(children); diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index d41a4529b7..566a16dbfd 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -263,7 +263,7 @@ fn retain_effects(n: &mut Node, members: bool, keep: &dyn Fn(&Effect) -> bool) { it.effects_mut().retain(keep); } if members { - for c in n.children_mut().into_iter().flatten() { + for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { retain_effects(Arc::make_mut(c), true, keep); } } @@ -367,7 +367,9 @@ pub(crate) fn replace_with_image(mut v: Node, image: Node) -> Node { v.appearance = Default::default(); v.set_clips(false); if let Some(ch) = v.children_mut() { - *ch = vec![Arc::new(image)]; + // Its ruler guides stay above the image. + let guides = ch.split_off(Node::guide_run_start(ch)); + *ch = std::iter::once(Arc::new(image)).chain(guides).collect(); } v } diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 6dcdc9dc4b..74347caa04 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -13,9 +13,7 @@ use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::colorcmds::{NotChanged, Recolor, Scope, left_out}; -use super::{ - CommandSpec, Result, Session, always, bad, check_switches, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param, -}; +use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param}; pub fn specs() -> Vec<CommandSpec> { vec![ @@ -566,8 +564,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> { if ids.is_empty() && group.is_none() { return Err(bad(C, "select artwork to recolour, or give a colour `group`")); } - check_switches(p, &["includeImages", "includePatterns"], C)?; - let scope = Scope { fill: true, stroke: true, ..Scope::of(p) }; + let scope = + Scope { fill: true, stroke: true, images: switch_or(p, "includeImages", true, C)?, patterns: switch_or(p, "includePatterns", true, C)? }; let label = if ids.is_empty() { "Edit Color Group" } else { "Recolor Artwork" }; // `model`: keep each colour's model (default), take the new colour's own, or the document's. // A given `model` must be a string; only a missing one means "keep". A row's own `model` diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 4cf070c6ae..fce76bcc27 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -17,7 +17,11 @@ //! store can, an announcement that lasts as long as the app ([`RecoveryStore::announce`]: the //! browser's Web Locks). Only areas nobody holds any more (their app is gone) are offered, and //! while their copies are restored or discarded the area is held, so two apps launched together -//! never both take it. +//! never both take it. An area's lock file or folder can be removed while its app runs, so each +//! recovery save and heartbeat checks that the lock still holds the area, and locks it again or +//! takes a new area. The copies it had in the old area stay there until it has written them again +//! in the new one, and an entry `<new area>/keeps-<old area>` ([`mark_left`]) tells other apps +//! that those copies belong to a running app, so none of them offers or discards them meanwhile. //! //! A heartbeat alone can't tell a gone app from one whose timers stopped (a background tab), so //! when unsure an area counts as held, and its app repairs what another app did meanwhile: each @@ -59,6 +63,9 @@ const BLOB_EXT: &str = ".blob"; /// The heartbeat entry of an area in a store without locks: when its app last said it runs (Unix /// seconds, as text). const BEAT: &str = "heartbeat"; +/// The start of an entry `<area>/keeps-<left area>`: the app holding `<area>` still keeps the copies +/// it left in `<left area>` ([`mark_left`]). +const KEEPS: &str = "keeps-"; /// The least time without a heartbeat after which an area's app counts as gone (seconds); else /// three Data Recovery intervals. const MIN_STALE: i64 = 180; @@ -100,6 +107,12 @@ pub trait RecoveryStore: Send + Sync { fn lock(&self, _area: &str) -> std::result::Result<Lock, String> { Ok(Lock::Unsupported) } + /// Does `hold`, which [`RecoveryStore::lock`] gave for area `area`, still hold it? A lock on a + /// file or folder that was removed or replaced since holds nothing; when that can't be told now, + /// it does (default: it does). + fn still_held(&self, _area: &str, _hold: &(dyn std::any::Any + Send + Sync)) -> bool { + true + } /// Stores without locks: also hold area `area` in a way other apps can see that lasts exactly as /// long as this app runs, if the store has one (the browser's Web Locks) → it, until dropped. fn announce(&self, _area: &str) -> Option<Hold> { @@ -111,8 +124,13 @@ pub trait RecoveryStore: Send + Sync { fn announced(&self, _area: &str) -> Option<bool> { None } - /// Tidy away area `area` once it holds no copies and nobody holds it (its lock file and folder). + /// Tidy away area `area` once it holds no copies (its lock file and folder). The caller holds + /// the area until this returns. fn remove_area(&self, _area: &str) {} + /// Remove area `area`'s folder if it is empty, after [`RecoveryStore::remove_area`] and after the + /// caller let the area go. On some file systems a file that is open is removed only when it is + /// closed, so `remove_area` leaves the folder there while the area is held. + fn remove_empty_area(&self, _area: &str) {} /// The clock heartbeats are judged by (Unix seconds; `None`: none, so no area counts as gone). fn now(&self) -> Option<i64> { vectorcraft_doc::metadata::now_unix() @@ -261,7 +279,60 @@ impl FolderStore { builder.recursive(true); #[cfg(unix)] std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); - builder.create(dir).map_err(|e| format!("{}: {e}", dir.display())) + builder.create(dir).map_err(|e| Self::folder_error(dir, &e, true)) + } + + /// The first folder on the way to `dir` (`dir` included), from the top down, that is not a + /// folder (`true`) or is missing (`false`). None when every one of them is a folder or one of + /// them can't be checked. + fn in_the_way(dir: &std::path::Path) -> Option<(&std::path::Path, bool)> { + let mut way: Vec<&std::path::Path> = dir.ancestors().filter(|p| !p.as_os_str().is_empty()).collect(); + way.reverse(); + for p in way { + match std::fs::metadata(p) { + Ok(m) if m.is_dir() => {} + Ok(_) => return Some((p, true)), + Err(m) if m.kind() == std::io::ErrorKind::NotFound => return Some((p, false)), + Err(_) => return None, + } + } + None + } + + /// The message for error `e` on folder `dir`, which was being made (`making`) or read. It + /// names the first folder on the way to `dir` that is not a folder, or is missing (when + /// `making`, the one that couldn't be made), and otherwise `dir`. + fn folder_error(dir: &std::path::Path, e: &std::io::Error, making: bool) -> String { + match Self::in_the_way(dir) { + Some((p, true)) => format!("{} is not a folder: {e}", p.display()), + Some((p, false)) if making => format!("couldn't make {}: {e}", p.display()), + Some((p, false)) if p != dir => format!("{} is missing", p.display()), + _ => format!("{}: {e}", dir.display()), + } + } + + /// The message for error `e` on file `f`. It names the first folder on the way to `f` that is + /// not a folder or is missing, and otherwise `f`. + fn file_error(f: &std::path::Path, e: &std::io::Error) -> String { + match f.parent().and_then(Self::in_the_way) { + Some((p, true)) => format!("{} is not a folder: {e}", p.display()), + Some((p, false)) => format!("{} is missing", p.display()), + None => format!("{}: {e}", f.display()), + } + } + + /// The outcome `r` of removing file `f`. A file that is not there counts as removed, unless a + /// file is on the way to it: Windows reports that as a missing file, and it is named as for a + /// listing. + pub(crate) fn removed(f: &std::path::Path, r: std::io::Result<()>) -> std::result::Result<(), String> { + match r { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => match f.parent().and_then(Self::in_the_way) { + Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())), + _ => Ok(()), + }, + Err(e) => Err(Self::file_error(f, &e)), + Ok(()) => Ok(()), + } } /// Refuse area folder `dir` unless it is a folder itself, not a link to one, and (on Unix) @@ -269,7 +340,7 @@ impl FolderStore { /// linked to a folder of its own in a shared recovery folder looked free, and claiming it /// wrote the copies through the link. fn own_area(dir: &std::path::Path) -> std::result::Result<(), String> { - let m = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let m = std::fs::symlink_metadata(dir).map_err(|e| Self::folder_error(dir, &e, false))?; if !m.file_type().is_dir() { return Err(format!("{}: not a folder of its own", dir.display())); } @@ -281,11 +352,17 @@ impl FolderStore { } /// The plain names of the files (or, `dirs`, folders) in `dir`; none when it doesn't exist. + /// A file on the way to `dir` is an error: Windows reports such a folder as missing. fn names(dir: &std::path::Path, dirs: bool) -> std::result::Result<Vec<String>, String> { let entries = match std::fs::read_dir(dir) { Ok(e) => e, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]), - Err(e) => return Err(format!("{}: {e}", dir.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return match Self::in_the_way(dir) { + Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())), + _ => Ok(vec![]), + }; + } + Err(e) => return Err(Self::folder_error(dir, &e, false)), }; Ok(entries .filter_map(|e| e.ok()) @@ -295,6 +372,73 @@ impl FolderStore { .filter(|n| Self::plain(n)) .collect()) } + + /// Lock area folder `dir`, which was just made. Another app tidies an empty area away + /// (`tidy`) by removing its lock file and folder while it holds the lock. So when the folder + /// or the lock file is gone by now, or the lock taken is on a lock file the folder no longer + /// has, that app had the area: it is [`Lock::Busy`], and the caller tries another one. + pub(crate) fn lock_area(dir: &std::path::Path) -> std::result::Result<Lock, String> { + if let Err(e) = Self::own_area(dir) { + let gone = std::fs::symlink_metadata(dir).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound); + return if gone { Ok(Lock::Busy) } else { Err(e) }; + } + let path = dir.join(LOCK_FILE); + match std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path) { + Ok(file) => Self::take(file, &path), + Err(e) => Self::open_failed(e, &path), + } + } + + /// Opening lock file `path` failed with `e`. When the folder is gone by now, another app had the + /// area: it is [`Lock::Busy`]. So it is when the lock file is there but can't be opened: some + /// file systems keep a removed file that another app still has open until that app closes it, + /// and refuse to open it meanwhile. A lock file that can't be made is an error. + pub(crate) fn open_failed(e: std::io::Error, path: &std::path::Path) -> std::result::Result<Lock, String> { + match e.kind() { + std::io::ErrorKind::NotFound => Ok(Lock::Busy), + std::io::ErrorKind::PermissionDenied if std::fs::symlink_metadata(path).is_ok() => Ok(Lock::Busy), + _ => Err(Self::file_error(path, &e)), + } + } + + /// Lock `file`, opened as lock file `path`. The lock holds the area only while `path` still + /// names that file. + pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result<Lock, String> { + match file.try_lock() { + Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))), + Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy), + // The lock file was removed meanwhile, and locking it failed instead. + Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy), + Err(std::fs::TryLockError::Error(e)) => Err(Self::file_error(path, &e)), + } + } + + /// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on + /// Windows they must be the same file (volume serial number and file index); elsewhere `path` + /// must exist. When either file can't be read, it does not. + fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + match (file.metadata(), std::fs::symlink_metadata(path)) { + (Ok(a), Ok(b)) => a.dev() == b.dev() && a.ino() == b.ino(), + _ => false, + } + } + #[cfg(windows)] + { + let opened = file.try_clone().and_then(same_file::Handle::from_file); + match (opened, same_file::Handle::from_path(path)) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } + } + #[cfg(not(any(unix, windows)))] + { + let _ = file; + std::fs::symlink_metadata(path).is_ok() + } + } } #[cfg(not(target_arch = "wasm32"))] @@ -313,10 +457,10 @@ impl RecoveryStore for FolderStore { if let Some(dir) = f.parent() { Self::own_area(dir)?; } - if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() { + if !std::fs::symlink_metadata(&f).map_err(|e| Self::file_error(&f, &e))?.file_type().is_file() { return Err(format!("{}: not a plain file", f.display())); } - std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display())) + std::fs::read(&f).map_err(|e| Self::file_error(&f, &e)) } fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { let f = self.file(name)?; @@ -324,14 +468,11 @@ impl RecoveryStore for FolderStore { Self::create_area(dir)?; Self::own_area(dir)?; } - vectorcraft_format::write_atomic(&f, bytes).map_err(|e| format!("{}: {e}", f.display())) + vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e)) } fn remove(&self, name: &str) -> std::result::Result<(), String> { let f = self.file(name)?; - match std::fs::remove_file(&f) { - Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", f.display())), - _ => Ok(()), - } + Self::removed(&f, std::fs::remove_file(&f)) } fn location(&self) -> String { self.0.to_string_lossy().into_owned() @@ -342,29 +483,33 @@ impl RecoveryStore for FolderStore { fn lock(&self, area: &str) -> std::result::Result<Lock, String> { let dir = self.area(area)?; Self::create_area(&dir)?; - Self::own_area(&dir)?; + Self::lock_area(&dir) + } + fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool { + let (Some(file), Ok(dir)) = (hold.downcast_ref::<std::fs::File>(), self.area(area)) else { return true }; let path = dir.join(LOCK_FILE); - let file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(&path) - .map_err(|e| format!("{}: {e}", path.display()))?; - match file.try_lock() { - Ok(()) => Ok(Lock::Held(Box::new(file))), - Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy), - Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())), + // Only a lock file or folder that is gone, or another one in its place, ends the hold. One + // that can't be read now (a network folder that doesn't answer) still counts as held. + match std::fs::symlink_metadata(&path) { + Ok(_) => Self::own_area(&dir).is_ok() && Self::still_named(file, &path), + Err(e) => e.kind() != std::io::ErrorKind::NotFound, } } fn remove_area(&self, area: &str) { // Best effort: whatever is left is tidied at a later launch. A folder that isn't empty - // (copies came back meanwhile) stays. + // (copies came back meanwhile) stays. The caller still holds the lock here. if let Ok(dir) = self.area(area) { let _ = std::fs::remove_file(dir.join(LOCK_FILE)); let _ = std::fs::remove_dir(&dir); } } + fn remove_empty_area(&self, area: &str) { + // Best effort, as above. An app that made the folder again meanwhile and has not locked it + // yet finds it gone and takes another area (`lock_area`); one that has keeps it. + if let Ok(dir) = self.area(area) { + let _ = std::fs::remove_dir(&dir); + } + } } /// The area this session keeps its copies in, while it holds it. @@ -391,6 +536,12 @@ pub struct Recovery { /// heartbeat it wrote there: that one doesn't make them look running, a newer one does (their /// app was only paused and came back). adopted: BTreeMap<String, i64>, + /// Copies in an area this session had to leave (`keep_hold`), by document uid, with their + /// store: each stays until its document has a copy in the new area, or needs none. They are + /// still this session's: never offered or discarded as a crash's here. + left: BTreeMap<u64, (Arc<dyn RecoveryStore>, String)>, + /// The `<own area>/keeps-<left area>` entries this session wrote in its area ([`mark_left`]). + marked: BTreeSet<String>, } impl Recovery { @@ -460,14 +611,120 @@ fn beating(store: &dyn RecoveryStore, area: &str, stale: i64, mine: Option<i64>) /// Refresh this session's hold on its area (the app does this every [`HEARTBEAT_EVERY`] seconds, /// so also on its first frame after its timers were paused): its heartbeat in a store without -/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now). -/// Best effort: a missed beat only lets another app offer the copies once three intervals have -/// passed. +/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now), +/// and those whose only copy is in an area the session left (`keep_hold`). Best effort: a missed +/// beat only lets another app offer the copies once three intervals have passed. pub fn heartbeat(s: &mut Session) -> Vec<u64> { + let mut lost = keep_hold(s); + // An entry that couldn't be written before, or that was removed since (by the user, a + // cleaner), is written now. + if let Some(own) = &s.recovery.own + && !s.recovery.marked.is_empty() + && let Ok(names) = own.store.list() + { + s.recovery.marked.retain(|n| names.contains(n)); + } + mark_left(s); if let Some(own) = s.recovery.own.as_ref().filter(|o| o.beats) { let _ = beat(own.store.as_ref(), &own.area); } - repair(s) + // A copy that was being written when the session left its area finished there. A document + // that gets no copy now (a complex one) keeps the copy it has. + lost.extend( + s.recovery + .left + .keys() + .filter(|&&uid| s.documents().iter().any(|d| d.uid == uid && d.recovery.is_none() && skip_reason(s, d).is_none())) + .copied(), + ); + lost.extend(repair(s)); + lost.sort_unstable(); + lost.dedup(); + lost +} + +/// Check that this session's lock still holds its area (stores with locks). The area's lock file, +/// or the whole area, can be removed while the app runs (by the user, a cleaner, another program), +/// and then another app can lock the area and offer or delete this session's copies as a crash's. +/// The area is locked again, made again first if it went (its copies are then written again). +/// When another app holds it now, the session takes a new area, and each copy left in the old one +/// stays until its document has a copy in the new one. → the documents whose copies must be +/// written again. +fn keep_hold(s: &mut Session) -> Vec<u64> { + drop_left_done(s); + let Some(own) = &mut s.recovery.own else { return vec![] }; + if own.beats || own.hold.as_deref().is_none_or(|h| own.store.still_held(&own.area, h)) { + return vec![]; + } + let (store, area) = (own.store.clone(), own.area.clone()); + // The lock held is on a file the area no longer has, so it holds nothing: it goes first (a + // removed file this app still has open can keep a new lock file from being made). + own.hold = None; + if let Ok(Lock::Held(h)) = store.lock(&area) { + own.hold = Some(h); + return repair(s); + } + let mut lost = vec![]; + for st in &mut s.docs { + if let Some(c) = st.recovery.take() { + s.recovery.left.insert(st.uid, (store.clone(), c.file)); + lost.push(st.uid); + } + } + s.recovery.own = None; + // Best effort: when no area can be taken now, the next recovery save says why. + let _ = claim(s, &store); + lost +} + +/// The copies left in an area this session left whose documents were saved, reverted or closed +/// since go. +fn drop_left_done(s: &mut Session) { + let done: Vec<u64> = s.recovery.left.keys().filter(|&&uid| !s.documents().iter().any(|d| d.uid == uid && d.is_dirty())).copied().collect(); + for uid in done { + drop_left(s, uid); + } +} + +/// Document `uid`'s copy in an area this session left goes. A copy that can't be removed now stays +/// this session's, and a later heartbeat removes it. +fn drop_left(s: &mut Session, uid: u64) { + let Some((store, file)) = s.recovery.left.get(&uid) else { return }; + let doc = store.remove(&format!("{file}{DOC_EXT}")); + let meta = store.remove(&format!("{file}{META_EXT}")); + if doc.is_ok() && meta.is_ok() { + s.recovery.left.remove(&uid); + mark_left(s); + } +} + +/// Record in this session's area each area it left that still holds copies of its documents: an +/// entry `<own area>/keeps-<left area>`, so another app leaves those copies alone while this one +/// runs ([`keeper`]). The entries of areas that hold none of its copies any more go. Best effort: +/// an entry not written or removed now is written or removed at the next heartbeat. +fn mark_left(s: &mut Session) { + let Some(own) = &s.recovery.own else { return }; + let (store, area) = (own.store.clone(), own.area.clone()); + let want: BTreeSet<String> = s + .recovery + .left + .values() + .filter(|(st, _)| st.location() == store.location()) + .filter_map(|(_, f)| f.split_once('/').map(|(a, _)| a)) + .filter(|a| *a != area) + .map(|a| format!("{area}/{KEEPS}{a}")) + .collect(); + let gone: Vec<String> = s.recovery.marked.difference(&want).cloned().collect(); + for n in gone { + if store.remove(&n).is_ok() { + s.recovery.marked.remove(&n); + } + } + for n in want { + if !s.recovery.marked.contains(&n) && store.write(&n, b"").is_ok() { + s.recovery.marked.insert(n); + } + } } /// Forget this session's copies that are missing from its area, so the next recovery save writes @@ -489,10 +746,13 @@ pub fn repair(s: &mut Session) -> Vec<u64> { /// This session's area in `store`, taken now if it has none there yet: a fresh area, held for the /// session's lifetime (locked, or with a heartbeat and an announcement where the store has them). pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String> { - if let Some(own) = &s.recovery.own { - if own.store.location() == store.location() { + if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) { + // Documents whose copies went are left without one, so the caller writes them again. + keep_hold(s); + if let Some(own) = &s.recovery.own { return Ok(own.area.clone()); } + } else if s.recovery.own.is_some() { // The store moved (the preference names another folder): copies start again there. release(s); } @@ -512,6 +772,9 @@ pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String> } }; s.recovery.own = Some(Own { store: store.clone(), area: area.clone(), hold, beats }); + // The entries written before are in the area this session had (released or left). + s.recovery.marked.clear(); + mark_left(s); return Ok(area); } Err(EngineError::Other("no free recovery area".into())) @@ -522,13 +785,22 @@ pub fn release(s: &mut Session) { for st in &mut s.docs { st.recovery = None; } + // Copies left in an area this session had to leave go too. + let left: Vec<u64> = s.recovery.left.keys().copied().collect(); + for uid in left { + drop_left(s, uid); + } let Some(Own { store, area, hold, .. }) = s.recovery.own.take() else { return }; + // Its `keeps-` entries go with the area's other entries. + s.recovery.marked.clear(); let mine = |n: &String| n.split_once('/').is_some_and(|(a, _)| a == area); for name in store.list().unwrap_or_default().iter().filter(|n| mine(n)) { let _ = store.remove(name); } - drop(hold); + // Held until it is gone, as in `tidy`. store.remove_area(&area); + drop(hold); + store.remove_empty_area(&area); } /// Let go of this session's area but leave its copies, as a crash would, so the next app started @@ -682,12 +954,16 @@ pub struct RecoveryJob { pub title: String, meta: Meta, save: SaveJob, + /// The store the copy goes to (the preference can name another folder before it is finished). + store: Arc<dyn RecoveryStore>, } impl RecoveryJob { /// Encode the snapshot and store it with its details and the images the area doesn't have - /// yet → `{file, title, bytes (the document's), imageBytes (images written now)}`. - pub fn write(&self, store: &dyn RecoveryStore) -> std::result::Result<Value, String> { + /// yet, in the store the job was made for → `{file, title, bytes (the document's), imageBytes + /// (images written now)}`. + pub fn write(&self) -> std::result::Result<Value, String> { + let store = self.store.as_ref(); let doc = self.save.doc(); // A linked image keeps its preview, as a save writes it. let linked = doc.linked_only_images(); @@ -740,13 +1016,36 @@ impl RecoveryJob { /// Once stored: the document (if still open) remembers the copy, so it isn't written again /// while unchanged and goes when the document is saved or closed. A document saved or closed - /// meanwhile has nothing left to recover: its copy goes at once. + /// meanwhile has nothing left to recover: its copy goes at once. So does a copy written in an + /// area the session left meanwhile (`keep_hold`), and its document gets a new one. pub fn finish(self, s: &mut Session) { let snapshot = self.save.snapshot().clone(); let copy = RecoveryCopy { file: self.file.clone(), doc: snapshot }; + let area = self.file.split_once('/').map(|(a, _)| a); + let current = s.recovery.own.as_ref().is_some_and(|o| o.store.location() == self.store.location() && Some(o.area.as_str()) == area); match s.document_mut(self.uid).filter(|st| st.is_dirty()) { - Some(st) => st.recovery = Some(copy), - None => remove_copy(s, &self.file), + Some(st) if current => { + st.recovery = Some(copy); + drop_left(s, self.uid); + } + // Written in an area left meanwhile: kept, in place of the copy left there before, + // until the document has a copy in the new area. + Some(st) if st.recovery.is_none() => { + let before = s.recovery.left.insert(self.uid, (self.store.clone(), self.file.clone())); + // The copy left there before, unless this one was written over it. Best effort, + // as in `remove_copy`. + if let Some((store, file)) = before.filter(|(old, f)| old.location() != self.store.location() || *f != self.file) { + let _ = store.remove(&format!("{file}{DOC_EXT}")); + let _ = store.remove(&format!("{file}{META_EXT}")); + } + mark_left(s); + } + // Best effort, as in `remove_copy`. + _ => { + let _ = self.store.remove(&format!("{}{DOC_EXT}", self.file)); + let _ = self.store.remove(&format!("{}{META_EXT}", self.file)); + drop_left(s, self.uid); + } } } } @@ -799,6 +1098,11 @@ fn fresh_name(area: &str, stem: &str, taken: &[String]) -> String { /// when it has none and a copy is needed) → (jobs, skipped: `[{title, reason}]` for modified /// documents that get none). pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<RecoveryJob>, Vec<Value>)> { + // A lost lock is taken again first: copies that go with it are written again, even of + // documents unchanged since. + if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) { + keep_hold(s); + } // Copies another app removed are written again. repair(s); let skipped: Vec<Value> = s @@ -855,7 +1159,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco // Filled in as the copy is written. images: BTreeMap::new(), }; - out.push(RecoveryJob { uid: st.uid, file, title, meta, save }); + out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() }); } Ok((out, skipped)) } @@ -886,7 +1190,7 @@ pub(crate) fn save_copies(s: &mut Session) -> Result<()> { return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into())); } for j in jobs { - j.write(store.as_ref()).map_err(EngineError::Other)?; + j.write().map_err(EngineError::Other)?; j.finish(s); } Ok(()) @@ -898,6 +1202,8 @@ pub fn forget(s: &mut Session, uid: u64) { if s.script_in_run { return; } + // So does a copy of it left in an area this session left. + drop_left(s, uid); let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return }; remove_copy(s, ©.file); } @@ -907,12 +1213,16 @@ pub fn forget_all(s: &mut Session) { release(s); } -/// The copies of documents with no unsaved changes left (undone back to the saved state) go. +/// The copies of documents with no unsaved changes left (undone back to the saved state) go, and +/// the copies left in an area this session left of documents closed since. pub fn forget_clean(s: &mut Session) { let uids: Vec<u64> = s.documents().iter().filter(|d| !d.is_dirty() && d.recovery.is_some()).map(|d| d.uid).collect(); for uid in uids { forget(s, uid); } + if !s.script_in_run { + drop_left_done(s); + } } fn save(s: &mut Session, _: &Value) -> Result<Value> { @@ -920,7 +1230,7 @@ fn save(s: &mut Session, _: &Value) -> Result<Value> { let (jobs, skipped) = jobs(s, &store)?; let mut saved = vec![]; for j in jobs { - saved.push(j.write(store.as_ref()).map_err(EngineError::Other)?); + saved.push(j.write().map_err(EngineError::Other)?); j.finish(s); } forget_clean(s); @@ -950,6 +1260,10 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec< } match store.lock(area) { Ok(Lock::Held(h)) => { + // Copies an app left here when it had to leave the area stay its own while it runs. + if let Some(who) = keeper(s, store, area) { + return who; + } hold.push(h); Owner::Gone } @@ -958,6 +1272,9 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec< if store.announced(area).unwrap_or(false) || beating(store, area, stale_after(s), s.recovery.adopted.get(area).copied()) { return Owner::Running; } + if let Some(who) = keeper(s, store, area) { + return who; + } // Best effort: without it another app might offer the copies too, which loses nothing. if take && let Ok(t) = beat(store, area) { s.recovery.adopted.insert(area.to_string(), t); @@ -967,7 +1284,45 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec< } } -/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`). +/// Who keeps the copies left in `area` by an app that had to leave it, from the entries +/// `<its area>/keeps-<area>` ([`mark_left`]): this session, or another app that is running. `None`: +/// no app that runs keeps them. An entry counts only in an area this account can lock or tell is +/// held ([`holder`]), so an entry in a folder of another account, or in one whose lock can't be +/// checked, keeps nothing. A store that can't be listed now keeps them (a copy kept loses nothing). +fn keeper(s: &Session, store: &dyn RecoveryStore, area: &str) -> Option<Owner> { + let Ok(names) = store.list() else { return Some(Owner::Running) }; + let mark = format!("/{KEEPS}{area}"); + let mut who = None; + for k in names.iter().filter_map(|n| n.strip_suffix(mark.as_str())).filter(|k| *k != area) { + match holder(s, store, k) { + Owner::Mine => return Some(Owner::Mine), + Owner::Running => who = Some(Owner::Running), + Owner::Gone => {} + } + } + who +} + +/// Whose area `area` is, without taking it over: this session's, a running app's, or nobody's (a +/// lock taken to tell goes at once). An area whose lock fails (not a recovery area of this +/// account, a lock file that can't be opened) is nobody's. +fn holder(s: &Session, store: &dyn RecoveryStore, area: &str) -> Owner { + if s.recovery.own.as_ref().is_some_and(|o| o.area == area && o.store.location() == store.location()) { + return Owner::Mine; + } + match store.lock(area) { + Ok(Lock::Held(_)) | Err(_) => Owner::Gone, + Ok(Lock::Busy) => Owner::Running, + Ok(Lock::Unsupported) => { + let runs = store.announced(area).unwrap_or(false) || beating(store, area, stale_after(s), s.recovery.adopted.get(area).copied()); + if runs { Owner::Running } else { Owner::Gone } + } + } +} + +/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`). The +/// area is removed while it is still held, so an app taking a new area of that name meanwhile +/// finds it held or gone and takes the next name. fn tidy(store: &dyn RecoveryStore, area: &str, hold: Vec<Hold>) { let names = store.list().unwrap_or_default(); let mine: Vec<&String> = names.iter().filter(|n| n.split_once('/').is_some_and(|(a, _)| a == area)).collect(); @@ -977,8 +1332,9 @@ fn tidy(store: &dyn RecoveryStore, area: &str, hold: Vec<Hold>) { for n in mine { let _ = store.remove(n); } - drop(hold); store.remove_area(area); + drop(hold); + store.remove_empty_area(area); } /// The copies of documents open now in this session. @@ -986,9 +1342,15 @@ fn open_copies(s: &Session) -> Vec<String> { s.documents().iter().filter_map(|d| d.recovery.as_ref()).map(|c| c.file.clone()).collect() } +/// The copies of documents open now in this session that are in an area it left, in `store`. +fn left_copies(s: &Session, store: &dyn RecoveryStore) -> Vec<String> { + s.recovery.left.values().filter(|(st, _)| st.location() == store.location()).map(|(_, f)| f.clone()).collect() +} + fn list(s: &mut Session, _: &Value) -> Result<Value> { let store = need_store(s, "file.recovery.list")?; let open = open_copies(s); + let left = left_copies(s, store.as_ref()); let copies = copies_in(&store.list().map_err(EngineError::Other)?); let mut rows = vec![]; for area in store.areas().map_err(EngineError::Other)? { @@ -1000,7 +1362,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> { let title = if meta.title.is_empty() { f.rsplit('/').next().unwrap_or(f).to_string() } else { meta.title }; rows.push(json!({ "file": f, "title": title, "path": meta.path, "format": meta.format, "saved": meta.saved, - "open": who == Owner::Mine && open.contains(f), "running": who == Owner::Running, + "open": (who == Owner::Mine && open.contains(f)) || left.contains(f), "running": who == Owner::Running, })); } // A gone app's empty area is tidied away. @@ -1024,7 +1386,14 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) -> { return Err(bad(cmd, format!("no recovery copy `{f}` (see file.recovery.list)"))); } - let picked = |c: &str| file.is_none_or(|f| f == c); + // A copy this session left in an area it had to leave is still its own. + let left = left_copies(s, store); + if let Some(f) = file + && left.iter().any(|c| c == f) + { + return Err(bad(cmd, format!("`{f}` is the copy of a document open now"))); + } + let picked = |c: &str| file.is_none_or(|f| f == c) && !left.iter().any(|l| l == c); let areas: BTreeSet<&str> = copies.iter().filter(|(_, c)| picked(c)).map(|(a, _)| a.as_str()).collect(); let mut out = vec![]; for area in areas { diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 493ba68db7..8c86f0dfe3 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text) and $.includePath the #includepath list; alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine and #engine are refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -45,6 +45,24 @@ pub fn specs() -> Vec<CommandSpec> { always, stop ), + cmd!( + query "script.engines", + "List Script Engines", + [], + None, + "{} the named engines (#targetengine) this session keeps, in the order they were made: a named engine keeps its globals between the runs that name it until it is dropped or the session ends; main, the engine of a script without #targetengine, is new for each run and is not listed; a session keeps at most 8, each with at most 64 MiB of heap (VectorCraft's own limits; none on the web) → {engines: [{name, heapBytes: its heap after its last run, running: a run has it now}], limit: 8, heapLimit: 67108864}", + always, + engines + ), + cmd!( + query "script.engine.drop", + "Drop Script Engine", + [], + None, + "{name: a named engine script.engines lists} drop the engine and the globals its runs left; the next run that names it gets a new one; main, an engine no run made and the engine of the running script are refused → {dropped: true, name}", + always, + engine_drop + ), cmd!( query "script.console", "Script Console", @@ -175,6 +193,22 @@ fn stop(s: &mut Session, _: &Value) -> Result<Value> { Ok(json!({"stopped": s.script_request_stop()})) } +fn engines(s: &mut Session, _: &Value) -> Result<Value> { + let list: Vec<Value> = + s.script_engines().into_iter().map(|(name, heap, running)| json!({"name": name, "heapBytes": heap, "running": running})).collect(); + Ok(json!({"engines": list, "limit": script::MAX_ENGINES, "heapLimit": script::ENGINE_HEAP_BYTES})) +} + +fn engine_drop(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "script.engine.drop"; + let name = match p.get("name") { + Some(Value::String(name)) if !name.is_empty() => name.clone(), + _ => return Err(bad(C, "`name` must be the name of a script engine")), + }; + s.drop_script_engine(&name)?; + Ok(json!({"dropped": true, "name": name})) +} + fn console_lines(s: &mut Session, _: &Value) -> Result<Value> { Ok(s.script_console().to_json()) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 4ef1e6bc6a..aeeac58855 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -7,6 +7,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_tools::builder::is_live_paint; +use super::object::can_align; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param, @@ -178,6 +179,15 @@ pub fn specs() -> Vec<CommandSpec> { cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| !p.is_closed()))), + cmd!( + "select.object.notAlignedToPixelGrid", + "Not Aligned to Pixel Grid", + ["Select", "Object"], + None, + "{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups but not into compound paths → {count}", + has_doc, + not_pixel_aligned + ), cmd!( "select.same.graphicStyle", "Graphic Style", @@ -442,15 +452,16 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> { if id.is_some() { return Err(bad("select.key", "give `id` or `guide`, not both")); } - if !sel.guides.contains(&g) { + let gid = super::docmenu::guide_ids(&s.doc()?.doc).get(g).copied(); + let Some(gid) = gid.filter(|id| sel.guides.contains(id)) else { return Err(bad("select.key", format!("guide {g} is not selected"))); - } + }; if sel.is_empty() { return Err(bad("select.key", "select objects to align to the guide")); } s.select(|_, sel| { sel.key = None; - sel.key_guide = Some(g); + sel.key_guide = Some(gid); })?; return key_result(s); } @@ -472,9 +483,9 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> { /// `{key}`, with `guide` when a guide is the key. fn key_result(s: &Session) -> Result<Value> { - let sel = &s.doc()?.selection; - let mut out = json!({ "key": sel.key }); - if let Some(g) = sel.key_guide { + let st = s.doc()?; + let mut out = json!({ "key": st.selection.key }); + if let Some(g) = st.selection.key_guide.and_then(|id| super::docmenu::guide_indexes(&st.doc, &[id]).first().copied()) { out["guide"] = json!(g); } Ok(out) @@ -864,3 +875,19 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> { // The objects selected, after Lock Guides has left out guide paths. Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned +/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk +/// does not look at the paths inside it. +fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> { + let st = s.doc()?; + let mut ids = vec![]; + walk_selectable(&st.doc, st.isolation, |n| { + if can_align(n) && !n.extras().pixel_aligned { + ids.push(n.id); + } + !matches!(n.kind, NodeKind::Compound { .. }) + }); + s.select(|_, sel| sel.set(ids))?; + Ok(json!({ "count": s.doc()?.selection.objects.len() })) +} diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 5792c44fdf..746be9c244 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::{Appearance, CellAlign, CellVAlign, Document, Node, NodeKin 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, + CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, f64_req, has_doc, has_selection, ids_param, index, number_or, object_param, switch_or, targets, }; @@ -340,8 +340,9 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> { fn from_guides(s: &mut Session, _: &Value) -> Result<Value> { let d = &s.doc()?.doc; let region = d.slice_clip().ok_or_else(|| EngineError::Other("Create from Guides: the document has no artboard".into()))?; + let guides = d.ruler_guides(); let cuts = |vertical: bool, lo: f64, hi: f64| -> Vec<f64> { - let mut v: Vec<f64> = d.guides.iter().filter(|g| g.vertical == vertical && g.pos > lo && g.pos < hi).map(|g| g.pos).collect(); + let mut v: Vec<f64> = guides.iter().filter(|g| g.vertical == vertical && g.pos > lo && g.pos < hi).map(|g| g.pos).collect(); v.extend([lo, hi]); v.sort_by(f64::total_cmp); v.dedup(); @@ -379,7 +380,8 @@ fn from_selection(s: &mut Session, p: &Value) -> Result<Value> { fn duplicate(s: &mut Session, p: &Value) -> Result<Value> { let targets = selected(s)?; - let (dx, dy) = (f64_or(p, "dx", 10.0), f64_or(p, "dy", 10.0)); + let dx = number_or(p, "dx", 10.0, "object.slice.duplicate")?; + let dy = number_or(p, "dy", 10.0, "object.slice.duplicate")?; let ids = s.edit("Duplicate Slice", |d, sel| { let mut out = vec![]; for id in &targets { @@ -678,7 +680,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> { fn set_rect(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "object.slice.setRect"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let r = rect_param(p, C)?; let d = &s.doc()?.doc; if d.slice(id).is_none() { @@ -736,7 +738,7 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> { fn select(s: &mut Session, p: &Value) -> Result<Value> { let slices = p.get("slices").filter(|v| !v.is_null()).cloned().unwrap_or(json!([])); let ids = slice_targets(s, &json!({ "slices": slices }), "object.slice.select")?; - let toggle = bool_or(p, "toggle", false); + let toggle = switch_or(p, "toggle", false, "object.slice.select")?; s.select(|_, sel| { let mut now = if toggle { sel.slices.clone() } else { vec![] }; for id in ids { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e97659bfc9..4153fedd51 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -206,11 +206,31 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool { ids.is_empty() && p.get("ids").is_none() && p.get("id").is_none() } +/// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of +/// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other +/// targets reach their painted leaves, as before. +fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::NodeId>> { + let picked = super::targets(s, p)?; + let d = &s.doc()?.doc; + let own = |id: &vectorcraft_doc::NodeId| { + d.node(*id).is_some_and(|n| { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some() + }) + }; + let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own); + for id in super::leaf_targets(s, &rest)? { + if !out.contains(&id) { + out.push(id); + } + } + Ok(out) +} + fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.set"; let change = StrokeChange::parse(p, C)?; let item = item_target(s, p, C)?.of_kind(s, false); - let mut ids = item.targets(s, p)?; + let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? }; let new_art = no_targets(&ids, p); if item == ItemTarget::Top { // Images and symbol instances take no stroke from the panel. @@ -261,7 +281,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { return Ok(()); } if index.is_none() && n.appearance.stroke().is_none() { - n.appearance.set_stroke(Paint::solid(Color::BLACK)); + // Options alone (cap, join, miter limit, dashes, alignment) don't make a stroke + // visible: the row made for them has no paint. A weight, an arrowhead or a profile + // still gives the object the black stroke the panel draws (#6739). + let visible = change.weight.is_some() || sa.is_some() || ea.is_some() || profile.is_some(); + n.appearance.set_stroke(if visible { Paint::solid(Color::BLACK) } else { Paint::None }); } if let Some(st) = n.appearance.stroke_at_mut(index) { set(st); diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index d73f01eaae..bca9ed6ea9 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -13,11 +13,12 @@ //! to loses its characters' own fill (stroke) when the style has fills (strokes), so the style's //! paint shows instead of the character colour under it. +use std::borrow::Cow; use std::collections::HashMap; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind, Shared}; use vectorcraft_geom::Rect; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, object_param, ok, str_param, unique_name}; @@ -153,7 +154,8 @@ fn descends(n: &Node, top: bool) -> bool { /// The objects whose appearance a style applied to `n` sets: `n`, or its painted contents. fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) { match n.children() { - Some(ch) if descends(n, top) => ch.iter().for_each(|c| painted(c, false, out)), + // A layer's ruler guides have no appearance to set. + Some(ch) if descends(n, top) => ch.iter().filter(|c| !c.is_ruler_guide()).for_each(|c| painted(c, false, out)), _ => out.push(n), } } @@ -259,9 +261,14 @@ fn override_chars(n: &mut Node, ap: &Appearance) { } /// Give `n` style `g`: its appearance (a group or layer too: its own, above its contents; type its -/// characters' colour too with `chars`, Override Character Color) and transparency. -fn style_node(n: &mut Node, g: &GraphicStyle, chars: bool) { - n.appearance = g.appearance_on(n).into_owned().into(); +/// characters' colour too with `chars`, Override Character Color) and transparency. Objects that +/// take `g`'s appearance as it is share one copy of it, made in `shared` the first time; an object +/// whose placed gradients land on its own bounds gets its own. +fn style_node(n: &mut Node, g: &GraphicStyle, shared: &mut Option<Shared<Appearance>>, chars: bool) { + n.appearance = match g.appearance_on(n) { + Cow::Borrowed(ap) => shared.get_or_insert_with(|| Shared::new(ap.clone())).clone(), + Cow::Owned(ap) => ap.into(), + }; if chars { override_chars(n, &g.appearance); } @@ -269,9 +276,9 @@ fn style_node(n: &mut Node, g: &GraphicStyle, chars: bool) { } /// Give `id` style `g` ([`style_node`]) and link it. -fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, chars: bool) { +fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, shared: &mut Option<Shared<Appearance>>, chars: bool) { if let Some(n) = d.node_mut(id) { - style_node(n, g, chars); + style_node(n, g, shared, chars); n.extras_mut().graphic_style = Some(g.id); super::object::snap_if_aligned(n); } @@ -312,7 +319,7 @@ impl Session { /// Color as set): the Graphic Styles panel's previews. pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node { let mut n = n.clone(); - style_node(&mut n, g, self.prefs.override_char_color); + style_node(&mut n, g, &mut None, self.prefs.override_char_color); n } } @@ -353,8 +360,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> { } else { d.graphic_style_id(i); let g = d.graphic_styles[i].clone(); + let mut shared = None; for id in &ids { - apply_style(d, *id, &g, chars); + apply_style(d, *id, &g, &mut shared, chars); } super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); } @@ -473,8 +481,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> { let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); let g = d.graphic_styles[i].clone(); + let mut shared = None; for nid in &follow { - apply_style(d, *nid, &g, chars); + apply_style(d, *nid, &g, &mut shared, chars); } super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true); set_link(d, &[src], Some(id)); diff --git a/crates/engine/src/cmd/stylelib.rs b/crates/engine/src/cmd/stylelib.rs index 7b0cad576a..2a9f480e89 100644 --- a/crates/engine/src/cmd/stylelib.rs +++ b/crates/engine/src/cmd/stylelib.rs @@ -14,7 +14,9 @@ use vectorcraft_doc::style_libs::{self, STYLE_LIBRARIES, STYLES_EXT, builtin_sty use vectorcraft_doc::{Document, GraphicStyle, PatternDef, StyleLibrary}; use super::menucmds::squash; -use super::swatchlib::{FileData, LibraryFile, LibraryInfo, names_param, stem}; +use super::swatchlib::{ + FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, names_param, shown_id, shown_library_id, stem, +}; use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param, switch_or, text_param, unique_name}; pub fn specs() -> Vec<CommandSpec> { @@ -94,6 +96,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<StyleLibrary> if let Some(found) = s.style_libraries.get(key) { return Some(found); } + if let Some(found) = concealed_library_id(s, key).and_then(|id| s.style_libraries.get(&id)) { + return Some(found); + } if let Some(b) = STYLE_LIBRARIES.iter().find(|b| b.id == key) { return Some((builtin_info(b), builtin_style_library(key)?)); } @@ -108,20 +113,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc< fn list(s: &mut Session, _: &Value) -> Result<Value> { s.style_libraries.rescan(); + let concealed = concealed_library_ids(s, []); let libs: Vec<Value> = libraries(s) .into_iter() .map(|l| { let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len()); - json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.style_libraries.path(&l.id)}) + let (id, path) = (shown_id(&concealed, &l.id), s.style_libraries.shown_path(&l.id)); + json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path}) }) .collect(); - Ok(json!({ "libraries": libs, "userFolder": s.style_libraries.user_dir() })) + Ok(json!({ "libraries": libs, "userFolder": s.style_libraries.shown_user_dir() })) } fn get(s: &mut Session, p: &Value) -> Result<Value> { let (info, lib) = library_param(s, p, "graphicStyle.library")?; let styles: Vec<Value> = lib.styles.iter().map(super::style::style_json).collect(); - Ok(json!({"id": info.id, "name": info.name, "category": info.category, "styles": styles})) + Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "styles": styles})) } /// Pattern `name` of `lib` in `d`: the document's own when it has the same pattern (under any @@ -192,7 +199,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { }; let doc_name = |lib_name: &str| added.iter().find(|(l, _)| l == lib_name).map_or_else(|| lib_name.to_string(), |(_, n)| n.clone()); let mut out = json!({ - "library": info.id, + "library": shown_library_id(s, &info.id), "added": added.iter().map(|(_, n)| n).collect::<Vec<_>>(), "existing": existing.iter().map(|g| &g.name).collect::<Vec<_>>(), }); @@ -238,5 +245,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> { } } })?; - Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 2421441b91..c809d58090 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1,6 +1,6 @@ //! The Swatches panel: new, delete and duplicate swatches, colour groups and sorting. -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent}; @@ -222,9 +222,10 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> { /// The `names` list and `name` parameters, without repeats; at least one is required. pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> { + let mut seen: HashSet<String> = HashSet::new(); let mut names: Vec<String> = vec![]; for n in str_list(p, "names").into_iter().chain(str_param(p, "name").map(str::to_string)) { - if !names.contains(&n) { + if seen.insert(n.clone()) { names.push(n); } } @@ -234,17 +235,73 @@ pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> { Ok(names) } +/// Take swatches `names` out of the document in that order, as [`Document::remove_swatch`] for +/// each name in turn would, in one pass over the swatches: a name takes the first swatch of that +/// name still there (ungrouped first, then each colour group's) when `take` accepts it, and +/// nothing when `take` refuses it or no swatch has the name. +fn take_swatches(d: &mut Document, names: &[String], take: impl Fn(&Swatch) -> bool) -> Vec<Swatch> { + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + // Each wanted name's swatches in lookup order: (list, index, accepted), where list 0 holds the + // ungrouped swatches and list g + 1 colour group g's. + let mut places: HashMap<&str, VecDeque<(usize, usize, bool)>> = HashMap::new(); + let lists = std::iter::once(&d.swatches[..]).chain(d.swatch_groups.iter().map(|g| &g.swatches[..])); + for (l, list) in lists.enumerate() { + for (i, w) in list.iter().enumerate() { + if let Some(n) = wanted.get(w.name.as_str()) { + places.entry(n).or_default().push_back((l, i, take(w))); + } + } + } + let mut picked: Vec<(usize, usize)> = vec![]; + for n in names { + if let Some(q) = places.get_mut(n.as_str()) + && let Some(&(l, i, true)) = q.front() + { + q.pop_front(); + picked.push((l, i)); + } + } + if picked.is_empty() { + return vec![]; + } + let hit: HashSet<(usize, usize)> = picked.iter().copied().collect(); + let hit_lists: HashSet<usize> = picked.iter().map(|&(l, _)| l).collect(); + let mut taken: HashMap<(usize, usize), Swatch> = HashMap::with_capacity(picked.len()); + let mut split = |l: usize, list: &mut Vec<Swatch>| { + for (i, w) in std::mem::take(list).into_iter().enumerate() { + if hit.contains(&(l, i)) { + taken.insert((l, i), w); + } else { + list.push(w); + } + } + }; + // Both lists are copied on write, so each is only written when a swatch leaves it. + if hit_lists.contains(&0) { + split(0, &mut d.swatches); + } + if hit_lists.iter().any(|&l| l > 0) { + for (g, group) in d.swatch_groups.iter_mut().enumerate() { + if hit_lists.contains(&(g + 1)) { + split(g + 1, &mut group.swatches); + } + } + } + picked.iter().filter_map(|k| taken.remove(k)).collect() +} + fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.delete"; let names = names_param(p, C)?; check_switches(p, &["unlink"], C)?; let d = &s.doc()?.doc; + let by_name = swatches_by_name(d); // Global swatches going away (named ones and those in named groups): their links are dropped. - let mut global: Vec<String> = vec![]; + let mut global: HashSet<String> = HashSet::new(); for n in &names { let swatches: Vec<&Swatch> = match d.swatch_groups.iter().find(|g| g.name == *n) { Some(g) => g.swatches.iter().collect(), - None => vec![d.swatch(n).ok_or_else(|| bad(C, format!("no swatch or colour group `{n}`")))?], + None => vec![by_name.get(n.as_str()).copied().ok_or_else(|| bad(C, format!("no swatch or colour group `{n}`")))?], }; if swatches.iter().any(|w| w.is_reserved()) { return Err(bad(C, format!("`{n}` can't be deleted"))); @@ -258,10 +315,9 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> { |_: &mut Color, link: &mut Option<String>, _: &mut f32| link.as_ref().is_some_and(|l| global.contains(l)) && link.take().is_some(); let colorized_ok = super::paint::check_colorized(d).is_ok(); let unlinked = s.edit("Delete Swatch", |d, _| { - d.swatch_groups.retain(|g| !names.contains(&g.name)); - for n in &names { - d.remove_swatch(n); - } + let named: HashSet<&str> = names.iter().map(String::as_str).collect(); + d.swatch_groups.retain(|g| !named.contains(g.name.as_str())); + take_swatches(d, &names, |_| true); let unlinked = map_swatch_links(d, &mut unlink); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(unlinked) @@ -347,6 +403,8 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> { GradientKind::Linear => 0, GradientKind::Radial => 1, GradientKind::Freeform => 2, + GradientKind::Conic => 3, + GradientKind::Diamond => 4, }; let method = match g.method { GradientMethod::Classic => 0, @@ -419,15 +477,9 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> { new.extend(art.into_iter().map(|c| (c, to_global))); } let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group")); - let mut group = SwatchGroup { name: name.clone(), swatches: vec![] }; // Colour groups hold solid colours only. - for n in &names { - if d.swatch(n).is_some_and(|sw| matches!(sw.paint, Paint::Solid { .. })) - && let Some(sw) = d.remove_swatch(n) - { - group.swatches.push(sw); - } - } + let swatches = take_swatches(d, &names, |sw| matches!(sw.paint, Paint::Solid { .. })); + let mut group = SwatchGroup { name: name.clone(), swatches }; // The global swatches made from the art's colours, which its unlinked paints link to. let mut links: Vec<(Color, String)> = vec![]; let mut free = d.free_swatch_names(); @@ -483,8 +535,9 @@ fn swatch_move(s: &mut Session, p: &Value) -> Result<Value> { insert_before(&mut d.swatch_groups, items, at.as_deref(), |g| &g.name); return Ok(()); } + let by_name = swatches_by_name(d); for n in &names { - let sw = d.swatch(n).ok_or_else(|| bad(C, format!("no swatch `{n}` (swatches and colour groups move separately)")))?; + let sw = by_name.get(n.as_str()).ok_or_else(|| bad(C, format!("no swatch `{n}` (swatches and colour groups move separately)")))?; if sw.is_reserved() { return Err(bad(C, format!("`{n}` can't be moved"))); } @@ -503,7 +556,7 @@ fn swatch_move(s: &mut Session, p: &Value) -> Result<Value> { } } let at = anchor(list(d, dest), to, &names, |w| &w.name); - let items: Vec<Swatch> = names.iter().filter_map(|n| d.remove_swatch(n)).collect(); + let items = take_swatches(d, &names, |_| true); insert_before(list(d, dest), items, at.as_deref(), |w| &w.name); Ok(()) })?; @@ -955,8 +1008,9 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.merge"; let names = names_param(p, C)?; let d = &s.doc()?.doc; + let by_name = swatches_by_name(d); for n in &names { - let sw = d.swatch(n).ok_or_else(|| bad(C, format!("no swatch `{n}`")))?; + let sw = by_name.get(n.as_str()).ok_or_else(|| bad(C, format!("no swatch `{n}`")))?; if sw.is_reserved() { return Err(bad(C, format!("`{n}` can't be merged"))); } @@ -970,9 +1024,10 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { } let kept = d.swatch(keep).ok_or_else(|| bad(C, format!("no swatch `{keep}`")))?; let (color, link) = (d.linked_color(kept.paint.color().unwrap_or_default(), kept.spot), kept.global.then(|| keep.clone())); + let merged_names: HashSet<&str> = merged.iter().map(String::as_str).collect(); // Tints keep their tint (of the kept colour). let mut relink = |c: &mut Color, l: &mut Option<String>, t: &mut f32| { - if !l.as_ref().is_some_and(|l| merged.contains(l)) { + if !l.as_ref().is_some_and(|l| merged_names.contains(l.as_str())) { return false; } *c = color.tinted(*t); @@ -981,9 +1036,7 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> { }; let colorized_ok = super::paint::check_colorized(d).is_ok(); let relinked = s.edit("Merge Swatches", |d, _| { - for n in merged { - d.remove_swatch(n); - } + take_swatches(d, merged, |_| true); let relinked = map_swatch_links(d, &mut relink); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index fe2816ed16..45320066cf 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -6,7 +6,7 @@ //! pattern) into the document; `swatch.library.save` writes the document's ([`palette_io`]). //! `swatch.library.copyToUser` copies a loaded library into the user library folder. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; @@ -211,6 +211,22 @@ impl<L: LibraryFile> Libraries<L> { self.extra.iter().find(|e| e.info.id == id).and_then(|e| e.path.as_deref()) } + /// The ids [`Libraries::get`] finds: the User Defined and loaded libraries', and the loaded ids of + /// libraries copied into the user library folder. + fn ids(&self) -> impl Iterator<Item = String> + '_ { + self.extra.iter().map(|e| e.info.id.clone()).chain(self.copied.iter().map(|(loaded, _)| loaded.clone())) + } + + /// The file library `id` was read from, when the request being served may read it. + pub fn shown_path(&self, id: &str) -> Option<&str> { + self.path(id).filter(|p| readable(p)) + } + + /// The user library folder, when the request being served may read it. + pub fn shown_user_dir(&self) -> Option<&str> { + self.user_dir().filter(|d| readable(d)) + } + /// The User Defined library whose file has the extension of file name `file` and holds `bytes`. fn user_file(&self, file: &str, bytes: &[u8]) -> Option<&Extra<L>> { let ext = extension(file); @@ -281,7 +297,10 @@ impl<L: LibraryFile> Libraries<L> { self.saved_as .insert(format!("user/{file}").to_lowercase(), SavedAs { name: name.to_string(), hash: vectorcraft_doc::links::hash_bytes(bytes) }); self.rescan(); - out["path"] = json!(path); + // The folder is the app's own: a confined request sees the file only inside its read roots. + if readable(&path) { + out["path"] = json!(path); + } out["library"] = json!(format!("user/{file}")); } else if let Some(path) = path { write_file(path, bytes)?; @@ -349,6 +368,10 @@ impl<L: LibraryFile> Libraries<L> { .ok_or_else(|| bad(cmd, format!("`{id}` isn't a loaded library")))?; let (file, bytes) = match source.filter(|p| L::EXTS.contains(&extension(p).as_str())) { Some(p) => { + // Outside the request's read roots: the error names no path. + if !readable(&p) { + return Err(bad(cmd, "the library's file is outside the read roots")); + } let ext = extension(&p); let base = file_name(&p); // A sandbox copy of an import often lands as tmp….tmp.acb (#2996): store it under the @@ -446,6 +469,72 @@ fn file_name(path: &str) -> String { std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string()) } +/// May the request being served read `path` ([`crate::file_access::check_read`])? Always, without +/// roots in force. +fn readable(path: &str) -> bool { + crate::file_access::check_read(path).is_ok() +} + +/// The loaded library ids (`loaded/<path>`) whose file the request being served may not read, each +/// with the id a reply shows instead: `loaded/<file name>`, as a library loaded without a path is +/// named. The ids are those of the session's swatch, brush, symbol and graphic style libraries, then +/// `others` (ids the UI state refers to). When another id already is or shows that id, the next free +/// one of `loaded/<file name> (2)`, `(3)` and so on is shown, so that two libraries stay two. The +/// session's libraries are numbered first, in the sorted order of their full ids, so a library shows +/// the same id whatever `others` holds; then `others`, in the same order. Without roots in force, none. +pub fn concealed_library_ids(s: &Session, others: impl IntoIterator<Item = String>) -> Vec<(String, String)> { + if crate::file_access::current().is_none() { + return vec![]; + } + let session: BTreeSet<String> = + s.swatch_libraries.ids().chain(s.brush_libraries.ids()).chain(s.symbol_libraries.ids()).chain(s.style_libraries.ids()).collect(); + let others: BTreeSet<String> = others.into_iter().filter(|id| !session.contains(id)).collect(); + let mut hidden = Vec::new(); + let mut taken = BTreeSet::new(); + for ids in [session, others] { + for id in ids { + let name = id.strip_prefix("loaded/").filter(|path| !path.is_empty()).map(|path| (file_name(path), path)); + match name { + Some((name, path)) if name != path && !readable(path) => hidden.push((id, name)), + _ => { + taken.insert(id); + } + } + } + } + hidden + .into_iter() + .map(|(id, name)| { + let mut shown = format!("loaded/{name}"); + let mut n = 2; + while taken.contains(&shown) { + shown = format!("loaded/{name} ({n})"); + n += 1; + } + taken.insert(shown.clone()); + (id, shown) + }) + .collect() +} + +/// The id a reply shows for library `id`, given the [`concealed_library_ids`] in force. +pub(crate) fn shown_id(concealed: &[(String, String)], id: &str) -> String { + concealed.iter().find(|(own, _)| own == id).map_or_else(|| id.to_string(), |(_, shown)| shown.clone()) +} + +/// The id a reply shows for library `id` ([`concealed_library_ids`]). +pub(crate) fn shown_library_id(s: &Session, id: &str) -> String { + shown_id(&concealed_library_ids(s, []), id) +} + +/// The library id behind `key` when `key` is the id a reply shows for a concealed loaded library. +pub(crate) fn concealed_library_id(s: &Session, key: &str) -> Option<String> { + if !key.starts_with("loaded/") { + return None; + } + concealed_library_ids(s, []).into_iter().find(|(_, shown)| shown == key).map(|(own, _)| own) +} + /// `name` without its extension. pub(crate) fn stem(name: &str) -> &str { name.rsplit_once('.').map_or(name, |(s, _)| s) @@ -479,6 +568,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<SwatchLibrary if let Some(found) = s.swatch_libraries.get(key) { return Some(found); } + if let Some(found) = concealed_library_id(s, key).and_then(|id| s.swatch_libraries.get(&id)) { + return Some(found); + } if let Some(b) = builtins().find(|(_, b)| b.id == key) { return Some((builtin_info(b), builtin_library(key)?)); } @@ -556,14 +648,16 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc< fn list(s: &mut Session, _: &Value) -> Result<Value> { s.swatch_libraries.rescan(); + let concealed = concealed_library_ids(s, []); let libs: Vec<Value> = libraries(s) .into_iter() .map(|l| { let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len()); - json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.swatch_libraries.path(&l.id)}) + let (id, path) = (shown_id(&concealed, &l.id), s.swatch_libraries.shown_path(&l.id)); + json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path}) }) .collect(); - Ok(json!({ "libraries": libs, "userFolder": s.swatch_libraries.user_dir() })) + Ok(json!({ "libraries": libs, "userFolder": s.swatch_libraries.shown_user_dir() })) } /// The document's swatches `names` (swatches or colour groups; empty: all) as a library named @@ -619,7 +713,7 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> { document_library(&loaded.doc, &[], stem(file).to_string(), C) } })?; - Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } fn get(s: &mut Session, p: &Value) -> Result<Value> { @@ -629,7 +723,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> { let groups: Vec<Value> = lib.groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect(); Ok( - json!({"id": info.id, "name": info.name, "category": info.category, "swatches": ungrouped.chain(grouped).collect::<Vec<_>>(), "groups": groups}), + json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "swatches": ungrouped.chain(grouped).collect::<Vec<_>>(), "groups": groups}), ) } @@ -652,7 +746,7 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> { "user" => (info, lib, false), _ => return Err(bad(C, format!("`{}` is built in and always listed", info.name))), }; - let path = s.swatch_libraries.path(&info.id); + let path = s.swatch_libraries.shown_path(&info.id); Ok(json!({"library": info.id, "name": info.name, "count": lib.len(), "path": path, "copied": copied})) } @@ -792,7 +886,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { })? }; let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>(); - let mut out = json!({"library": info.id, "added": names(&added), "existing": names(&existing)}); + let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); s.execute(cmd, &json!({"swatch": name, "focus": focus}))?; diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 22cfc74e9f..606ab40fcf 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -19,7 +19,7 @@ use vectorcraft_doc::symbol_overrides::SymbolOverride; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, SymbolRegistration}; use vectorcraft_geom::{Affine, Point}; -use super::brushsym::{natural_size, place_xf}; +use super::brushsym::{fit_parts, natural_size, place_xf}; use super::{EngineError, Result, Session, bad, number_or, object_param, ok, str_param}; /// The name of the undo step that enters symbol editing mode. @@ -248,7 +248,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> { /// the instance editing was entered from. The symbol already holds the layer's art ([`sync`]). pub(crate) fn finish(d: &mut Document, sel: &mut Selection) { let Some(se) = d.symbol_edit.take() else { return }; - let _ = d.remove(se.layer); + let _ = d.remove_edit_layer(se.layer); match se.instance.filter(|i| d.node(*i).is_some()) { Some(i) => sel.set([i]), None => sel.clear(), @@ -425,8 +425,8 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy } /// Each instance's appearance changes to objects of symbol `name`'s art follow those objects -/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes to -/// objects the art still has. That covers the instances on the layers and in the art of the +/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art +/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the /// document's other symbols, graph designs, pattern tiles (the tiles pattern editing's Cancel puts /// back included) and brushes, opacity-mask art included. The editing layer holds no instance of /// the symbol, since [`sync`] refuses one. @@ -435,7 +435,7 @@ fn follow_objects(d: &mut Document, name: &str, old: (&[Arc<Node>], bool), new: let mut follow = |o: &mut Vec<SymbolOverride>| { follow_paths(o, old, new); match &art { - Some(art) => vectorcraft_doc::symbol_overrides::retain_parts(o, art), + Some(art) => fit_parts(o, art), None => o.clear(), } }; @@ -480,18 +480,24 @@ fn follow_objects(d: &mut Document, name: &str, old: (&[Arc<Node>], bool), new: /// an instance of the symbol itself. pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { let Some(se) = d.symbol_edit.clone() else { return Ok(()) }; - let art: Option<Vec<Arc<Node>>> = d.node(se.layer).and_then(|l| l.children().cloned()); + // The layer's art: ruler guides on it are not part of the symbol. + let art_of = |d: &Document| -> Option<Vec<Arc<Node>>> { + d.node(se.layer).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect()) + }; + let art = art_of(d); let (Some(art), Some(index)) = (art, d.symbols.iter().position(|x| x.name == se.symbol)) else { d.symbol_edit = None; - let _ = d.remove(se.layer); + let _ = d.remove_edit_layer(se.layer); return Ok(()); }; // Entering, and edits that left the layer's art alone, write nothing. let same = |b: &[Arc<Node>]| b.len() == art.len() && b.iter().zip(&art).all(|(a, b)| Arc::ptr_eq(a, b)); let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) { None => return Ok(()), - Some(_) if before.node(se.layer).and_then(|l| l.children()).is_some_and(|b| same(b)) => return Ok(()), - Some(b) => (before.node(se.layer).and_then(|l| l.children().cloned()).unwrap_or_default(), b.group), + Some(b) => match art_of(before) { + Some(old) if same(&old) => return Ok(()), + old => (old.unwrap_or_default(), b.group), + }, }; if art.iter().any(|n| holds_symbol(d, n, &se.symbol, &mut HashSet::new())) { return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 02767aef39..98b46a5d1a 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -19,7 +19,7 @@ use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_nat use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::swatch::str_list; -use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem}; +use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem}; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param}; /// The extension of saved symbol libraries: native documents. @@ -159,6 +159,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[ BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames }, BuiltinSymbolLibrary { id: "map-markers", name: "Map Markers", make: map_markers }, BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons }, + BuiltinSymbolLibrary { id: "skill-icons", name: "Skill Icons", make: skill_icons }, ]; /// Built-in library `id`, made once. @@ -312,6 +313,51 @@ fn inventory_icons() -> SymbolLibrary { SymbolLibrary { name: "Inventory Icons".into(), doc } } +/// Skill Icons: attack, defend, heal, buff and ult marks for RPG/UI art (original, no 9-slice). +fn skill_icons() -> SymbolLibrary { + let c = Point::ZERO; + let attack = [(-18.0, 14.0), (-6.0, 2.0), (-2.0, 6.0), (18.0, -14.0), (14.0, -18.0), (-6.0, -2.0), (-10.0, 2.0), (-18.0, 6.0)]; + let defend = [(0.0, -18.0), (14.0, -10.0), (12.0, 6.0), (0.0, 18.0), (-12.0, 6.0), (-14.0, -10.0)]; + let heal = [ + (-4.0, -18.0), + (4.0, -18.0), + (4.0, -4.0), + (18.0, -4.0), + (18.0, 4.0), + (4.0, 4.0), + (4.0, 18.0), + (-4.0, 18.0), + (-4.0, 4.0), + (-18.0, 4.0), + (-18.0, -4.0), + (-4.0, -4.0), + ]; + let buff = [(0.0, -18.0), (10.0, -2.0), (4.0, -2.0), (4.0, 18.0), (-4.0, 18.0), (-4.0, -2.0), (-10.0, -2.0)]; + let attack: Vec<Point> = attack.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let defend: Vec<Point> = defend.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let heal: Vec<Point> = heal.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let buff: Vec<Point> = buff.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let icons = [ + ("Attack", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&attack, true)), "#e74c3c"), + ("Defend", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&defend, true)), "#3498db"), + ("Heal", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&heal, true)), "#2ecc71"), + ("Buff", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&buff, true)), "#f1c40f"), + ("Ult", shapes::star(c, 18.0, 7.0, 8, 0.0), "#9b59b6"), + ]; + let mut doc = Document::new(100.0, 100.0); + for (name, path, hex) in icons { + let fill = Color::from_hex(hex).unwrap_or(Color::BLACK); + let edge = fill.lerp(&Color::BLACK, 0.35); + let id = doc.alloc_id(); + let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25)); + let Ok((art, size, _)) = normalize(art) else { continue }; + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(&mut doc, name, Some(size)); + } + doc.title = "Skill Icons".into(); + SymbolLibrary { name: "Skill Icons".into(), doc } +} + /// An instance of symbol `name` (what the resource gathering follows). fn instance(name: &str) -> Node { Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) @@ -340,6 +386,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<SymbolLibrary if let Some(found) = s.symbol_libraries.get(key) { return Some(found); } + if let Some(found) = concealed_library_id(s, key).and_then(|id| s.symbol_libraries.get(&id)) { + return Some(found); + } if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { return Some((builtin_info(b), builtin_library(key)?)); } @@ -354,14 +403,16 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc< fn list(s: &mut Session, _: &Value) -> Result<Value> { s.symbol_libraries.rescan(); + let concealed = concealed_library_ids(s, []); let libs: Vec<Value> = libraries(s) .into_iter() .map(|l| { let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len()); - json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.symbol_libraries.path(&l.id)}) + let (id, path) = (shown_id(&concealed, &l.id), s.symbol_libraries.shown_path(&l.id)); + json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path}) }) .collect(); - Ok(json!({ "libraries": libs, "userFolder": s.symbol_libraries.user_dir() })) + Ok(json!({ "libraries": libs, "userFolder": s.symbol_libraries.shown_user_dir() })) } fn get(s: &mut Session, p: &Value) -> Result<Value> { @@ -375,7 +426,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> { json!({"name": sym.name, "size": [w, h], "registration": d.symbol_registration(&sym.name).0, "exportType": d.symbol_export_type(&sym.name).id()}) }) .collect(); - Ok(json!({"id": info.id, "name": info.name, "category": info.category, "symbols": symbols})) + Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "symbols": symbols})) } fn add(s: &mut Session, p: &Value) -> Result<Value> { @@ -410,7 +461,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None }; let parent = if place { st.target_parent()? } else { None }; - let mut out = json!({ "library": info.id }); + let mut out = json!({ "library": shown_library_id(s, &info.id) }); if imported.added > 0 || place { let placed = s.edit("Add to Symbols", |d, sel| { let imported = clip.import_into(d, &choices, false)?; @@ -466,7 +517,7 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> { } SymbolLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e)) })?; - Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } #[cfg(test)] diff --git a/crates/engine/src/cmd/tabs.rs b/crates/engine/src/cmd/tabs.rs index 331227e3be..c047b94900 100644 --- a/crates/engine/src/cmd/tabs.rs +++ b/crates/engine/src/cmd/tabs.rs @@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> { "Set Tab Stops", ["Window", "Tabs"], None, - "{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty", + "{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); at most 256 stops, or no more than each targeted paragraph already holds, positions 0..=100000 pt; supplied align, leader and alignOn must be strings, a leader has at most 8 characters and alignOn exactly one; stops are sorted by position, and of stops at one position the first given is kept", has_selection, set ), @@ -41,7 +41,7 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> { let mut stops = vec![]; for s in arr { let position = s.get("position").and_then(Value::as_f64).ok_or_else(|| bad(C, "each stop needs a position"))?; - if !(0.0..=100_000.0).contains(&position) { + if !(0.0..=TabStop::MAX_POSITION).contains(&position) { return Err(bad(C, "positions must be between 0 and 100000 pt")); } let align = match s.get("align") { @@ -60,16 +60,25 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> { None | Some(Value::Null) => "", Some(Value::String(value)) => value.as_str(), Some(_) => return Err(bad(C, "`leader` must be a string")), + }; + let (label, max) = ("`leader`", TabStop::MAX_LEADER); + if leader.chars().count() > max { + return Err(bad(C, format!("{label} must be at most {max} characters"))); } - .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(Value::String(value)) => { + let mut chars = value.chars(); + let c = chars.next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?; + if chars.next().is_some() { + let label = "`alignOn`"; + return Err(bad(C, format!("{label} must be one character"))); + } + c + } Some(_) => return Err(bad(C, "`alignOn` must be a string")), }; - stops.push(TabStop { position, align, leader, align_on }); + stops.push(TabStop { position, align, leader: leader.to_string(), align_on }); } stops.sort_by(|a, b| a.position.total_cmp(&b.position)); stops.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6); @@ -77,10 +86,39 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> { } fn set(s: &mut Session, p: &Value) -> Result<Value> { + // More than the limit is taken only when every targeted paragraph already holds at least as + // many stops, so a paragraph that holds more can still lose them one at a time. The supplied + // list is counted before it is read. + let max = TabStop::MAX_STOPS; + let supplied = p.get("stops").and_then(Value::as_array).map_or(0, Vec::len); + if supplied > max && supplied > fewest_held(s, p)? { + return Err(bad("text.tabs.set", format!("at most {max} tab stops"))); + } let stops = parse_stops(p)?; apply(s, p, stops, "Tab Stops") } +/// The fewest tab stops a paragraph that `text.tabs.set` with `p` targets holds (0 with none). +fn fewest_held(s: &Session, p: &Value) -> Result<usize> { + let ids = text_targets(s, p, "text.tabs.set")?; + let range = TextRange::parse(p, "text.tabs.set")?; + let doc = &s.doc()?.doc; + let mut fewest: Option<usize> = None; + for id in &ids { + if let Some(NodeKind::Text(t)) = doc.node(*id).map(|node| &node.kind) { + let held = match para_span(range, t) { + None => t.para_styles().map(|pa| pa.tabs.len()).min(), + Some(r) => r.map(|i| t.para_at(i).tabs.len()).min(), + }; + fewest = match (fewest, held) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + } + } + Ok(fewest.unwrap_or(0)) +} + fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result<Value> { let ids = text_targets(s, p, "text.tabs.set")?; let range = TextRange::parse(p, "text.tabs.set")?; @@ -128,7 +166,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> { #[cfg(test)] mod tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::Session; @@ -139,6 +177,59 @@ mod tests { } } + /// A leader of more than eight characters, an `alignOn` of more than one character and a list + /// of more than 256 stops are errors, not cut short. + #[test] + fn long_leaders_long_align_on_and_too_many_stops_are_errors() { + let err = |stops: Value| super::parse_stops(&json!({ "stops": stops })).unwrap_err().to_string(); + assert!(err(json!([{"position": 40, "leader": "123456789"}])).contains("`leader` must be at most 8 characters")); + assert!(err(json!([{"position": 40, "alignOn": ",."}])).contains("`alignOn` must be one character")); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb"})).unwrap(); + let many: Vec<Value> = (0..257).map(|i| json!({"position": i})).collect(); + let e = s.execute("text.tabs.set", &json!({ "stops": many.clone() })).unwrap_err().to_string(); + assert!(e.contains("at most 256 tab stops"), "{e}"); + // The supplied list is counted, not the stops left once those at one position merge. + let same: Vec<Value> = (0..257).map(|_| json!({"position": 5})).collect(); + assert!(s.execute("text.tabs.set", &json!({ "stops": same })).unwrap_err().to_string().contains("at most 256 tab stops")); + assert_eq!(s.execute("text.tabs.set", &json!({ "stops": &many[..256] })).unwrap()["stops"], json!(256)); + let ok = super::parse_stops(&json!({"stops": [{"position": 0, "leader": "12345678", "alignOn": "€"}]})).unwrap(); + assert_eq!((ok[0].leader.as_str(), ok[0].align_on), ("12345678", '€')); + } + + /// A paragraph that already holds more than 256 stops (from a file) can lose them one at a + /// time: a list no longer than every targeted paragraph's own is taken, a longer one is not, and + /// a paragraph with fewer stops targeted beside it keeps the limit. + #[test] + fn stops_can_be_removed_from_a_paragraph_holding_more_than_the_limit() { + use vectorcraft_doc::{NodeId, NodeKind, TabAlign, TabStop}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap()["id"].as_u64().unwrap()); + let held: Vec<TabStop> = + (0..300).map(|i| TabStop { position: f64::from(i), align: TabAlign::Left, leader: String::new(), align_on: '.' }).collect(); + s.edit("Load", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.edit_paras(None, |pa| pa.tabs = held.clone()); + } + Ok(()) + }) + .unwrap(); + let list = |n: i32| json!({ "stops": (0..n).map(|i| json!({"position": i})).collect::<Vec<_>>() }); + assert!(s.execute("text.tabs.set", &list(301)).unwrap_err().to_string().contains("at most 256 tab stops")); + assert_eq!(s.execute("text.tabs.set", &list(299)).unwrap()["stops"], json!(299)); + assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"].as_array().unwrap().len(), 299); + // The second paragraph (bytes 4 on) now holds 2 stops: 298 for both paragraphs is refused, + // and 298 for the first alone is taken. + s.execute("text.tabs.set", &json!({"stops": [{"position": 1}, {"position": 2}], "start": 4, "end": 4})).unwrap(); + let mut both = list(298); + assert!(s.execute("text.tabs.set", &both).is_err()); + both["start"] = json!(0); + both["end"] = json!(0); + assert_eq!(s.execute("text.tabs.set", &both).unwrap()["stops"], json!(298)); + } + #[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 79dcee7135..edfab850f5 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -11,8 +11,8 @@ use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ - CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, id_param, - index, number_or, point_param, str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index, + number_or, object_param, point_param, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> { "Touch Type", [], None, - "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first logical character of a line or at a reading-direction boundary; supported in either reading direction; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)", + "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright)} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first logical character of a line or at a reading-direction boundary; supported in either reading direction; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)", has_doc, touch_type ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText, fitMinPercent? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the character before it, leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", has_doc, type_step ), @@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> { "Reset Tracking and Kerning", [], Some("Cmd+Alt+Q"), - "{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", + "{ids?: [id…]} set tracking to 0 and clear manual kerning (kerning and kerningBefore) without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning there, as type.step steps it), else in every selected type object, as one undo step → {ids}", has_selection, reset_tracking ), @@ -272,7 +272,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> { fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.editRange"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; let len = edit::runs_len(&t.runs); let (a, b) = range_of(p, len, C)?; @@ -337,7 +337,7 @@ fn clear_param(s: &Session, p: &Value, id: NodeId, c: &str) -> Result<Vec<NodeId fn start_list(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.startList"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; let len = edit::runs_len(&t.runs); let at = offset_or(p, "at", len, C)?.min(len); @@ -365,7 +365,7 @@ fn start_list(s: &mut Session, p: &Value) -> Result<Value> { } fn get_range(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("text.getRange", "missing `id`"))?; + let id = object_param(p, "id", "text.getRange")?.ok_or_else(|| bad("text.getRange", "missing `id`"))?; if switch_or(p, "story", false, "text.getRange")? { return get_story(s, p, id); } @@ -430,6 +430,8 @@ pub(crate) struct CharChange { leading: Option<Option<f64>>, tracking: Option<f64>, kerning: Option<Option<f64>>, + /// The space before a character that starts a line by itself (`kerningBefore`). + kerning_before: Option<f64>, optical_kerning: Option<bool>, baseline_shift: Option<f64>, h_scale: Option<f64>, @@ -691,7 +693,7 @@ fn auto_or_num(p: &Value, k: &str, cmd: &str) -> Result<Option<Option<f64>>> { impl CharChange { /// `setup` gives the superscript, subscript and small caps proportions. pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> { - check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?; + check_numbers(p, &["size", "tracking", "kerningBefore", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?; check_switches( p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak", "kashidas"], @@ -720,6 +722,7 @@ impl CharChange { Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") || v.eq_ignore_ascii_case("auto") => Some(None), Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)), }, + kerning_before: num("kerningBefore"), optical_kerning: match p.get("kerning") { Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true), Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false), @@ -777,6 +780,7 @@ impl CharChange { && self.leading.is_none() && self.tracking.is_none() && self.kerning.is_none() + && self.kerning_before.is_none() && self.optical_kerning.is_none() && self.baseline_shift.is_none() && self.h_scale.is_none() @@ -883,6 +887,9 @@ impl CharChange { if let Some(v) = self.kerning { st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0)); } + if let Some(v) = self.kerning_before { + st.kerning_before = v.clamp(-1000.0, 10000.0); + } if let Some(v) = self.optical_kerning { st.optical_kerning = v; } @@ -1254,7 +1261,7 @@ fn drawn_glyph( fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setGlyphAlternate"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let gid = match p.get("gid") { None => return Err(bad(C, "missing `gid` (a glyph id, or null for the default glyph)")), Some(Value::Null) => None, @@ -1344,7 +1351,7 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> { fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.glyphAlternates"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; let (ch, bytes, face) = glyph_target(&t, p, C)?; let default = face.glyph_for(ch); @@ -1359,7 +1366,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> { fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.touchType"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; check_numbers(p, &["start"], C)?; let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { @@ -1585,7 +1592,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> { fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.createInPath"; - let pid = id_param(p, "path").ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; + let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; let on_path = match str_param(p, "mode").unwrap_or("area") { "area" => false, "onPath" | "path" => true, @@ -1623,6 +1630,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> { path_effect: Default::default(), path_align: Default::default(), path_spacing: 0.0, + dynamic_text: false, wrap: Vec::new(), optical_margin: false, anti_alias: Default::default(), @@ -1636,7 +1644,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> { }; super::create::new_type_alignment(s, p, C, &mut t)?; if !on_path { - t.area.fit = super::create::new_area_fit(s, p, C)?; + super::create::new_area_fit(s, p, C, &mut t)?; } t.system_layout = s.doc()?.doc.setup.system_layout; if bool_or(p, "placeholder", false) { @@ -1693,17 +1701,16 @@ pub(crate) fn editing_story(s: &Session) -> Vec<NodeId> { s.active().map(|st| super::threads::story_of(&st.doc, id)).unwrap_or_default() } +/// A text range a type shortcut changes: its type object, its bytes, and the caret's byte when it +/// came from a caret ([`type_ranges`]). +pub(crate) type TypeRange = (NodeId, usize, usize, Option<usize>); + /// The text ranges a type shortcut changes: the range of `id`, else all the text of the type /// objects in `ids`, else the text the Type tool has selected (all the text of every frame of the /// story after Select All in threaded text, [`editing_story`]), else all the text of every selected /// type object. At a caret, `at_caret` gives the range from the plain text and the caret's byte -/// (None: nothing changes there). Each range comes with whether it came from a caret. -pub(crate) fn type_ranges( - s: &mut Session, - p: &Value, - c: &str, - at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>, -) -> Result<Vec<(NodeId, usize, usize, bool)>> { +/// (None: nothing changes there). Each range comes with the caret's byte when it came from a caret. +pub(crate) fn type_ranges(s: &mut Session, p: &Value, c: &str, at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>) -> Result<Vec<TypeRange>> { // (text, its range; None: all of it). let targets: Vec<(NodeId, Option<(usize, usize)>)> = match super::object_param(p, "id", c)? { // An object that isn't type is refused as `ids` of it is. @@ -1727,10 +1734,10 @@ pub(crate) fn type_ranges( let text = text_ref(s, id)?.plain_text(); let (a, b) = range.map_or((0, text.len()), |(a, b)| (a.min(text.len()), b.min(text.len()))); let (a, b, caret) = if a < b { - (a, b, false) + (a, b, None) } else { match at_caret(&text, a) { - Some((a, b)) => (a, b, true), + Some((x, y)) => (x, y, Some(a)), None => continue, } }; @@ -1762,24 +1769,31 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { Step::Tracking | Step::Kerning => prefs.tracking_increment, Step::BaselineShift => prefs.baseline_shift_increment, }; - // The ranges stepped. At a caret: kerning is the space after the character before it, leading - // the paragraph's; the rest wait for a selection. + // The ranges stepped. At a caret: kerning is the space after the character before it, or at + // the start of a line the space before the character after it (#5111), leading the + // paragraph's; the rest wait for a selection. let ranges = type_ranges(s, p, C, |text, a| match step { - Step::Kerning => Some((edit::prev_char(text, a), a)), + Step::Kerning => edit::caret_kerning_target(text, a).map(|(r, _)| (r.start, r.end)), Step::Leading => { let para = edit::paragraph_at(text, a); Some((para.start, para.end)) } _ => None, })?; + // At a caret, the kerning stepped: (whether it is the space before the character, its value). let mut caret_kerning = Vec::with_capacity(ranges.len()); for &(id, a, b, caret) in &ranges { - let value = if matches!(step, Step::Kerning) && caret { - let t = text_ref(s, id)?; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); - Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b)) - } else { - None + let value = match caret { + Some(c) if matches!(step, Step::Kerning) => { + let t = text_ref(s, id)?; + if edit::caret_kerning_target(&t.plain_text(), c).is_some_and(|(_, before)| before) { + Some((true, edit::style_at(&t.runs, a + 1).kerning_before)) + } else { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + Some((false, effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b))) + } + } + _ => None, }; caret_kerning.push(value); } @@ -1828,10 +1842,13 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?); } Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0), - Step::Kerning => { - let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0)); - st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); - } + Step::Kerning => match caret_kerning.get(range_index).copied().flatten() { + Some((true, current)) => st.kerning_before = (current + inc).clamp(-1000.0, 10000.0), + caret => { + let current = caret.map_or_else(|| st.kerning.unwrap_or(0.0), |(_, v)| v); + st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); + } + }, Step::BaselineShift => { st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?; } @@ -1848,17 +1865,22 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> { /// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in /// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret, -/// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there. -/// The automatic method remains selected. +/// only the kerning there changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns +/// there: of the character before it, or at the start of a line the space before the character +/// after it ([`edit::caret_kerning_target`]). The automatic method remains selected. fn reset_tracking(s: &mut Session, p: &Value) -> Result<Value> { - let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?; + let ranges = type_ranges(s, p, "type.resetTracking", |text, a| edit::caret_kerning_target(text, a).map(|(r, _)| (r.start, r.end)))?; if !ranges.is_empty() { s.edit("Reset Tracking and Kerning", |d, _| { for &(id, a, b, caret) in &ranges { let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; - edit::style_range(&mut t.runs, a, b, |st| { - st.kerning = None; - if !caret { + let before = caret.and_then(|c| edit::caret_kerning_target(&t.plain_text(), c)).map(|(_, before)| before); + edit::style_range(&mut t.runs, a, b, |st| match before { + Some(true) => st.kerning_before = 0.0, + Some(false) => st.kerning = None, + None => { + st.kerning = None; + st.kerning_before = 0.0; st.tracking = 0.0; } }); @@ -1914,6 +1936,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> { path_effect: Default::default(), path_align: Default::default(), path_spacing: 0.0, + dynamic_text: false, wrap: Vec::new(), optical_margin: false, anti_alias: Default::default(), @@ -1973,7 +1996,7 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> { fn discard_empty(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.discardEmpty"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; if edit::runs_len(&text_ref(s, id)?.runs) > 0 { return Ok(json!({"removed": false})); } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 89ec47b276..40d8af22ad 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -8,7 +8,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TabStop, TextStyleDef}; use super::clipboard::resources::import_text_styles; use super::typecmd::{refresh_bounds, text_targets}; @@ -125,7 +125,7 @@ macro_rules! style_cmds { } /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec<CommandSpec> { let mut v = style_cmds!( @@ -143,7 +143,21 @@ pub fn specs() -> Vec<CommandSpec> { |s, p| edit_style(s, p, Kind::Char), true, )); - v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", "")); + v.extend(style_cmds!( + Kind::Para, + "paraStyle", + "Paragraph Styles", + "Paragraph", + "; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position" + )); + v.push(spec( + "paraStyle.edit", + "Edit Paragraph Style", + &[], + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position", + |s, p| edit_style(s, p, Kind::Para), + true, + )); v.push(spec("textStyle.loadAll", "Load All Styles…", &["Window", "Type"], LOAD_PARAMS, |s, p| load(s, p, &[Kind::Char, Kind::Para]), true)); v } @@ -174,8 +188,10 @@ fn to_attrs<T: Serialize>(v: &T) -> Map<String, Value> { /// from a style instead leaves the text's own value alone. pub fn char_attrs(v: &CharStyle) -> Map<String, Value> { let mut m = to_attrs(v); - // A chosen glyph belongs to one character, not to a reusable character style. + // A chosen glyph belongs to one character, and the space before a line's first character to + // where it stands (#5111), not to a reusable character style. m.remove("glyphAlternate"); + m.remove("kerningBefore"); for (k, x) in [ ("font_version", json!(v.font_version)), ("fontAxes", json!(v.font_axes)), @@ -229,6 +245,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> { ("kinsoku_type", json!(v.kinsoku_type)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), + ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), ] { m.insert(k.into(), x); } @@ -516,6 +533,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma if m.contains_key("glyphAlternate") { return Err(bad(&c, "`glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it)")); } + if m.contains_key("kerningBefore") { + return Err(bad( + &c, + "`kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it)", + )); + } let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); for (key, value, lo, hi) in @@ -554,7 +577,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } char_attrs(&st) } - Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?), + Kind::Para => { + let mut st = with_attrs(&ParaStyle::default(), m, &c)?; + para_ranges(&st, m, kept, &c)?; + sort_tabs(&mut st, m, kept); + para_attrs(&st) + } }; Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect())) } @@ -562,6 +590,102 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } } +/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt), +/// as `text.setFormat` keeps them. +const PARA_DISTANCE: f64 = 1296.0; + +/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the +/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each +/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as +/// `attrs` gives them), and the number of tab stops with the position and leader of each stop +/// `kept` does not hold. A value `kept` has is not checked. +fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> { + let within = |key: &str, value: f64, lo: f64, hi: f64| { + if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) } + }; + let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key); + let nested_changed = |key: &str, field: &str| { + changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)) + }; + for (key, value) in [ + ("left_indent", st.left_indent), + ("right_indent", st.right_indent), + ("first_line_indent", st.first_line_indent), + ("space_before", st.space_before), + ("space_after", st.space_after), + ] { + if changed(key) { + within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?; + } + } + let h = &st.hyphenation; + for (field, value, lo, hi) in [ + ("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0), + ("after_first", f64::from(h.after_first), 1.0, 15.0), + ("before_last", f64::from(h.before_last), 1.0, 15.0), + ("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0), + ("zone", h.zone, 0.0, PARA_DISTANCE), + ] { + if nested_changed("hyphenation", field) { + within(&format!("hyphenation.{field}"), value, lo, hi)?; + } + } + // Read as given: a paragraph's attributes keep justification options in range as they load. + if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) { + let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?; + for (field, values, (lo, hi)) in [ + ("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING), + ("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING), + ("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING), + ] { + if !nested_changed("justification", field) { + continue; + } + let name = format!("justification.{field}"); + for value in values { + within(&name, value, lo, hi)?; + } + if !(values[0] <= values[1] && values[1] <= values[2]) { + return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); + } + } + if nested_changed("justification", "auto_leading") { + let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING; + within("justification.auto_leading", j.auto_leading, lo, hi)?; + } + } + if changed("tabs") { + let kept_tabs = kept_tab_stops(kept); + let max = TabStop::MAX_STOPS; + if st.tabs.len() > max.max(kept_tabs.len()) { + return Err(bad(c, format!("at most {max} tab stops"))); + } + for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { + within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; + let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); + if stop.leader.chars().count() > max { + return Err(bad(c, format!("{label} must be at most {max} characters"))); + } + } + } + Ok(()) +} + +/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out). +fn kept_tab_stops(kept: Option<&Map<String, Value>>) -> Vec<TabStop> { + let stops = kept.and_then(|k| k.get("tabs")).and_then(Value::as_array); + stops.into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect() +} + +/// `st`'s tab stops sorted by position, keeping the first of stops within 1e-6 pt of each other, +/// as `text.tabs.set` keeps them, when `attrs` changes them from `kept`. +fn sort_tabs(st: &mut ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>) { + if attrs.contains_key("tabs") && kept.and_then(|k| k.get("tabs")) != attrs.get("tabs") { + st.tabs.sort_by(|a, b| a.position.total_cmp(&b.position)); + st.tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6); + } +} + /// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a /// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes. fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> { @@ -917,10 +1041,29 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name -/// is empty, which are skipped. → (the styles, the names in `src` of those skipped) +/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose +/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range +/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in +/// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) { - const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"]; + const RANGED: [&str; 16] = [ + "size", + "h_scale", + "v_scale", + "leading", + "baseline_shift", + "tcyUpDown", + "tcyLeftRight", + "stroke_width", + "left_indent", + "right_indent", + "first_line_indent", + "space_before", + "space_after", + "hyphenation", + "justification", + "tabs", + ]; let (mut defs, mut skipped) = (vec![], vec![]); for def in kind.defs(src) { let name = def.name.as_str(); diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index ab0c7d342e..77ecd9d786 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -1336,7 +1336,8 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { /// The same for character styles: Auto kerning and the Roman baseline alignment, which the /// run's JSON leaves out, are captured and reach the style's users. A glyph choice belongs to -/// one character, so it is not a reusable style attribute. +/// one character, and the space before a line's first character to where it stands (#5111), so +/// neither is a reusable style attribute. #[test] fn char_style_redefined_to_the_defaults_updates_its_text() { use vectorcraft_doc::CharAlign; @@ -1356,6 +1357,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() { assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3])); let mut reusable = settable::<CharStyle>(); reusable.remove("glyphAlternate"); + reusable.remove("kerningBefore"); assert_eq!(defined(&s, 0), reusable, "Redefine captures every reusable attribute"); s.execute("charStyle.new", &json!({"name": "Copy", "id": local})).unwrap(); assert_eq!(defined(&s, 1), reusable, "New captures every reusable attribute"); @@ -1585,3 +1587,221 @@ fn para_style_range_capture_samples_start_paragraph() { } } } + +fn paras(s: &Session, id: u64) -> Vec<ParaStyle> { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.paragraph_styles(), + _ => panic!("not text"), + } +} + +/// `paraStyle.edit` renames a paragraph style and replaces its attributes in one undo step: every +/// paragraph using it takes the new values, a paragraph's local override stays, and the saved file +/// keeps the sparse definition. +#[test] +fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() { + use vectorcraft_doc::Composer; + let (mut s, id) = session_with_text("One\nTwo\nThree"); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"left_indent": 6.0, "composer": "everyLine", "tabs": [{"position": 36.0}]}})) + .unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Body", "id": id, "start": 0, "end": 7})).unwrap(); + s.execute("text.setFormat", &json!({"id": id, "start": 4, "end": 4, "leftIndent": 20.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let attrs = json!({"left_indent": 12.0, "composer": "singleLine", "tabs": [{"position": 36.0}], + "hyphenation": {"words_longer_than": 8}, "justification": {"word_spacing": [70.0, 90.0, 120.0]}}); + s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Text", "attrs": attrs})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let p = paras(&s, id); + assert_eq!( + p.iter().map(|p| (p.style_name.as_deref(), p.left_indent, p.composer)).collect::<Vec<_>>(), + [(Some("Text"), 12.0, Composer::SingleLine), (Some("Text"), 20.0, Composer::SingleLine), (None, 0.0, Composer::EveryLine)] + ); + assert_eq!(p[0].hyphenation.words_longer_than, 8); + assert_eq!(p[1].justification.word_spacing, [70.0, 90.0, 120.0]); + let def = s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Text").unwrap().attrs.clone(); + let mut keys: Vec<&str> = def.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!(keys, ["composer", "hyphenation", "justification", "left_indent", "tabs"]); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(saved.para_styles.iter().find(|d| d.name == "Text").unwrap().attrs, def); + let changed = s.doc().unwrap().doc.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, changed); + // The Normal style, an empty or a taken name and an unknown style are errors. + s.execute("paraStyle.new", &json!({"name": "Other"})).unwrap(); + for (params, why) in [ + (json!({"name": "Text", "to": " ", "attrs": {}}), "give the style a name"), + (json!({"name": "Text", "to": "Other", "attrs": {}}), "already exists"), + (json!({"name": "Missing", "to": "Missing", "attrs": {}}), "no style `Missing`"), + (json!({"name": NORMAL_PARA, "to": NORMAL_PARA, "attrs": {}}), "can't be edited"), + ] { + let error = s.execute("paraStyle.edit", ¶ms).unwrap_err().to_string(); + assert!(error.contains(why), "{params}: {error}"); + } +} + +/// A changed paragraph attribute outside the range `text.setFormat` keeps it to is an error for +/// `paraStyle.edit`, `paraStyle.setAttrs` and `paraStyle.new`, with no change to the document; the +/// ends of each range are accepted, and an out-of-range value the style already has can be kept. +#[test] +fn paragraph_style_attributes_are_checked_before_a_definition_changes() { + let (mut s, _) = session_with_text("Text"); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"left_indent": 6.0}})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for (attrs, key) in [ + (json!({"left_indent": -1296.1}), "left_indent"), + (json!({"right_indent": 1296.1}), "right_indent"), + (json!({"first_line_indent": 1e300}), "first_line_indent"), + (json!({"space_before": 1296.1}), "space_before"), + (json!({"space_after": -1296.1}), "space_after"), + (json!({"hyphenation": {"words_longer_than": 0}}), "hyphenation.words_longer_than"), + (json!({"hyphenation": {"words_longer_than": 4000000000_u64}}), "hyphenation.words_longer_than"), + (json!({"hyphenation": {"after_first": 16}}), "hyphenation.after_first"), + (json!({"hyphenation": {"before_last": 0}}), "hyphenation.before_last"), + (json!({"hyphenation": {"hyphen_limit": 26}}), "hyphenation.hyphen_limit"), + (json!({"hyphenation": {"zone": -1.0}}), "hyphenation.zone"), + (json!({"hyphenation": {"zone": 1296.1}}), "hyphenation.zone"), + (json!({"justification": {"word_spacing": [80.0, 100.0, 1000.1]}}), "justification.word_spacing"), + (json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}}), "justification.word_spacing"), + (json!({"justification": {"letter_spacing": [-100.1, 0.0, 0.0]}}), "justification.letter_spacing"), + (json!({"justification": {"letter_spacing": [0.0, 10.0, 5.0]}}), "justification.letter_spacing"), + (json!({"justification": {"glyph_scaling": [49.0, 100.0, 100.0]}}), "justification.glyph_scaling"), + (json!({"justification": {"auto_leading": 500.1}}), "justification.auto_leading"), + (json!({"tabs": [{"position": 100000.1}]}), "tabs.position"), + (json!({"tabs": [{"position": -1.0}]}), "tabs.position"), + ] { + for cmd in ["paraStyle.edit", "paraStyle.setAttrs", "paraStyle.new"] { + let params = match cmd { + "paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}), + "paraStyle.new" => json!({"name": "Other", "attrs": attrs}), + _ => json!({"name": "Body", "attrs": attrs}), + }; + let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}"); + } + } + // Malformed values are errors too. + for attrs in [json!({"hyphenation": {"words_longer_than": -1}}), json!({"justification": {"word_spacing": [1.0, 2.0]}}), json!({"tabs": 3})] { + assert!(s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": attrs})).is_err(), "{attrs}"); + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + + let ends = json!({ + "left_indent": -1296.0, "right_indent": 1296.0, "first_line_indent": 0.0, "space_before": 1296.0, "space_after": -1296.0, + "hyphenation": {"words_longer_than": 25, "after_first": 1, "before_last": 15, "hyphen_limit": 0, "zone": 1296.0}, + "justification": {"word_spacing": [0.0, 0.0, 1000.0], "letter_spacing": [-100.0, 0.0, 500.0], "glyph_scaling": [50.0, 100.0, 200.0], "auto_leading": 500.0}, + "tabs": [{"position": 0.0}, {"position": 100000.0}] + }); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": ends})).unwrap(); + // A style that already holds a value out of range (one read from a file) can be renamed with it. + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("left_indent".into(), json!(2000.0)); + s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Renamed", "attrs": {"left_indent": 2000.0}})).unwrap(); + assert!(s.doc().unwrap().doc.para_styles.iter().any(|d| d.name == "Renamed")); + // Such a Hyphenation, Justification or tab value is kept while another option of its group changes, + // and a changed option is still checked. + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let held = json!({ + "hyphenation": {"words_longer_than": 40, "after_first": 2}, + "justification": {"letter_spacing": [0.0, 0.0, 600.0], "auto_leading": 120.0}, + "tabs": [{"position": 200000.0}] + }); + let attrs = &mut doc.para_styles.iter_mut().find(|d| d.name == "Renamed").unwrap().attrs; + attrs.extend(held.as_object().unwrap().clone()); + let edited = json!({ + "hyphenation": {"words_longer_than": 40, "after_first": 3}, + "justification": {"letter_spacing": [0.0, 0.0, 600.0], "auto_leading": 150.0}, + "tabs": [{"position": 200000.0}, {"position": 72.0}] + }); + s.execute("paraStyle.setAttrs", &json!({"name": "Renamed", "attrs": edited})).unwrap(); + let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Renamed").unwrap().attrs.clone(); + assert_eq!(def(&s)["hyphenation"]["after_first"], json!(3)); + assert_eq!(def(&s)["justification"]["auto_leading"], json!(150.0)); + for (attrs, key) in [ + (json!({"hyphenation": {"words_longer_than": 40, "after_first": 16}}), "hyphenation.after_first"), + (json!({"justification": {"auto_leading": 501.0}}), "justification.auto_leading"), + (json!({"tabs": [{"position": 200000.0}, {"position": 72.0}, {"position": 100001.0}]}), "tabs.position"), + ] { + let error = s.execute("paraStyle.setAttrs", &json!({"name": "Renamed", "attrs": attrs})).unwrap_err().to_string(); + assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}"); + } +} + +/// A paragraph style's changed tab stops are checked stop by stop: a stop the style holds is kept +/// as it is, and a stop at a held position with another alignment is a changed stop. A changed +/// stop's leader has at most eight characters and its Align On one character, a changed list has +/// at most 256 stops (or as many as the style holds, here 300), and the stops are stored sorted by position, +/// keeping the first of stops at one position. +#[test] +fn paragraph_style_tab_stops_are_checked_by_stop_and_sorted() { + let (mut s, _) = session_with_text("Text"); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap(); + let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone(); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let held: Vec<Value> = + (0..300).map(|i| json!({"position": 200000.0 + f64::from(i), "align": "left", "leader": "123456789", "alignOn": "."})).collect(); + doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), Value::from(held.clone())); + let before = s.doc().unwrap().doc.clone(); + let mut moved = held.clone(); + moved[0]["align"] = json!("right"); + for (stops, why) in [ + (Value::from(moved), "`tabs.position`"), + (json!([{"position": 36.0, "leader": "123456789"}]), "`tabs.leader` must be at most 8 characters"), + (Value::from((0..301).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()), "at most 256 tab stops"), + (json!([{"position": 36.0, "alignOn": ",."}]), "expected a character"), + ] { + for cmd in ["paraStyle.edit", "paraStyle.setAttrs"] { + let params = match cmd { + "paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": {"tabs": stops}}), + _ => json!({"name": "Body", "attrs": {"tabs": stops}}), + }; + let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(error.contains(why), "{cmd}: {error}"); + } + } + let many = Value::from((0..257).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()); + let error = s.execute("paraStyle.new", &json!({"name": "Other", "attrs": {"tabs": many}})).unwrap_err().to_string(); + assert!(error.contains("at most 256 tab stops"), "{error}"); + assert_eq!(s.doc().unwrap().doc, before); + // The held stops stay while one is dropped and another attribute changes. + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": &held[1..], "left_indent": 4.0}})).unwrap(); + assert_eq!(def(&s)["tabs"].as_array().map(Vec::len), Some(299)); + let stops = json!([{"position": 72.0, "align": "right"}, {"position": 36.0}, {"position": 36.0000001, "align": "center"}, {"position": 0.0, "leader": "12345678"}]); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap(); + assert_eq!( + def(&s)["tabs"], + json!([{"position": 0.0, "align": "left", "leader": "12345678", "alignOn": "."}, {"position": 36.0, "align": "left", "alignOn": "."}, + {"position": 72.0, "align": "right", "alignOn": "."}]) + ); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": []}})).unwrap(); + assert_eq!(def(&s)["tabs"], json!([]), "an empty list stays set"); +} + +/// Load Paragraph Styles and Load All Styles skip a paragraph style whose indents, spacing, +/// Hyphenation or Justification options or tab stops are out of the range `paraStyle.new` takes, +/// and load the others with their stops. +#[test] +fn loading_skips_paragraph_styles_out_of_range() { + let file = [ + ("Good", json!({"left_indent": 6.0, "tabs": [{"position": 36.0, "align": "decimal", "alignOn": ","}]})), + ("Indent", json!({"left_indent": 2000.0})), + ("Space", json!({"space_after": -1300.0})), + ("Hyphens", json!({"hyphenation": {"words_longer_than": 40}})), + ("Spacing", json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}})), + ("Leader", json!({"tabs": [{"position": 10.0, "leader": "123456789"}]})), + ]; + let data = styles_file(&[], &file); + for cmd in ["paraStyle.load", "textStyle.loadAll"] { + let (mut s, _) = session_with_text("Title"); + let r = s.execute(cmd, &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap(); + let r = if cmd == "textStyle.loadAll" { r["paraStyles"].clone() } else { r }; + assert_eq!(r, json!({"added": ["Good"], "existing": [], "skipped": ["Indent", "Space", "Hyphens", "Spacing", "Leader"]}), "{cmd}"); + let good = super::style_attrs(&s.doc().unwrap().doc, true, "Good").unwrap(); + assert_eq!(good["tabs"], json!([{"position": 36.0, "align": "decimal", "alignOn": ","}]), "{cmd}"); + } +} diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index ae15ab8b91..6c80c962d6 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create", ["Type", "Threaded Text"], None, - "{} thread the selected area type and type on a path (and closed paths, which become area frames) in stacking order → {ids}", + "{} thread the selected area type and type on a path (and closed paths, which become area frames) in stacking order; a frame with Dynamic Text has it turned off and keeps the sizes it was drawn at → {ids, dynamicTextOff?: [id…] (the frames it was turned off on; left out when none)}", has_multi, create ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> { "Thread Text", [], None, - "{from, to?, rect?: [x, y, width, height], at?: [x, y], before?} thread area type or type on a path `from` (a click on its out port) into one more frame, put after it in its thread, or before it with `before: true` (a click on its in port: the story starts there and flows on into `from`): closed path, area type or type on a path `to`, a new rectangle `rect`, or a new frame of `from`'s kind, shape and size with its top-left at `at` (give one of the three) → {id}; the two frames are selected", + "{from, to?, rect?: [x, y, width, height], at?: [x, y], before?} thread area type or type on a path `from` (a click on its out port) into one more frame, put after it in its thread, or before it with `before: true` (a click on its in port: the story starts there and flows on into `from`): closed path, area type or type on a path `to`, a new rectangle `rect`, or a new frame of `from`'s kind, shape and size with its top-left at `at` (give one of the three); a frame with Dynamic Text has it turned off and keeps the sizes it was drawn at → {id, dynamicTextOff?: [id…] (the frames it was turned off on; left out when none)}; the two frames are selected", has_doc, add ), @@ -126,6 +126,11 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { } #[cfg(test)] COPIED.with(|c| c.set(c.get() + 1)); + // Type on a path in a thread is not Dynamic Text: its frames keep the sizes it draws them + // at, before the story is taken from them. + if thread.iter().filter(|id| text_of(doc, **id).is_some()).count() >= 2 { + dynamic_text_off(doc, &thread); + } // The story: live frames' runs, plus the text of frames deleted by this edit. let mut story: Vec<TextRun> = vec![]; let mut sources: Vec<TextObject> = vec![]; @@ -264,15 +269,28 @@ fn thread_setting<T: PartialEq>(before: &Document, doc: &Document, live: &[NodeI changed.or(live.first()).and_then(now) } -/// Turn Auto Size off for the frames of each thread of two or more frames, as [`reflow`] does, -/// without re-flowing the story: for a document restored from a file as it was saved, so a later -/// change to a frame's settings keeps the frame's size. +/// Turn Dynamic Text off on the frames among `ids` that have it on, each keeping the sizes it is +/// drawn at ([`super::typemenu::bake_dynamic_text`]); the frames it turned off. +pub(crate) fn dynamic_text_off(doc: &mut Document, ids: &[NodeId]) -> Vec<NodeId> { + let on: Vec<NodeId> = ids.iter().copied().filter(|id| text_of(doc, *id).is_some_and(|t| t.dynamic_text)).collect(); + for id in &on { + if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) { + super::typemenu::bake_dynamic_text(t); + } + } + on +} + +/// Turn Auto Size and Dynamic Text off for the frames of each thread of two or more frames, as +/// [`reflow`] does, without re-flowing the story: for a document restored from a file as it was +/// saved, so a later change to a frame's settings keeps the frame's size. pub(crate) fn keep_frame_sizes(doc: &mut Document) { for thread in doc.text_threads.clone() { let live: Vec<NodeId> = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); if live.len() < 2 { continue; } + dynamic_text_off(doc, &live); for id in live { if text_of(doc, id).is_some_and(|t| t.area.fit == vectorcraft_doc::AreaFit::AutoHeight) && let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) @@ -534,6 +552,8 @@ fn create(s: &mut Session, _: &Value) -> Result<Value> { return Err(bad(C, "select area type and closed paths (at least one area type object)")); } let out = ids.clone(); + // The frames that lose Dynamic Text: those of the new thread and the threads it takes in. + let off: Vec<u64> = with_threads(d, &ids).into_iter().filter(|i| text_of(d, *i).is_some_and(|t| t.dynamic_text)).map(|i| i.0).collect(); s.edit("Thread Text", |d, _| { for id in &ids { if text_of(d, *id).is_none() { @@ -562,7 +582,11 @@ fn create(s: &mut Session, _: &Value) -> Result<Value> { touch(d, ids[0]); Ok(()) })?; - Ok(json!({ "ids": out.iter().map(|i| i.0).collect::<Vec<_>>() })) + let mut reply = json!({ "ids": out.iter().map(|i| i.0).collect::<Vec<_>>() }); + if !off.is_empty() { + reply["dynamicTextOff"] = json!(off); + } + Ok(reply) } /// `text.thread.add`: the loaded text of a port, placed. @@ -573,7 +597,8 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let before = switch_or(p, "before", false, C)?; let d = &s.doc()?.doc; let src = text_of(d, from).ok_or_else(|| bad(C, "`from` must be area type or type on a path"))?; - let style = src.first_style(); + // A new frame takes the style `from` is drawn in: threading turns its Dynamic Text off. + let style = vectorcraft_text::drawn(src).first_style(); // The frame to thread into: an existing object (`to`), or a new one beside `from`. let (to, new) = match (given("to"), given("rect"), given("at")) { (Some(v), None, None) => { @@ -610,6 +635,8 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { _ => return Err(bad(C, "give one of `to`, `rect` or `at`")), }; let appearance = d.node(from).map(|n| n.appearance.clone()); + // The frames that lose Dynamic Text: those of `from`'s thread and `to`. + let off: Vec<u64> = with_threads(d, &[from, to]).into_iter().filter(|i| text_of(d, *i).is_some_and(|t| t.dynamic_text)).map(|i| i.0).collect(); let id = s.edit("Thread Text", |d, sel| { let to = match new { Some(t) => { @@ -645,7 +672,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { sel.set([from, to]); Ok(to) })?; - Ok(json!({ "id": id.0 })) + let mut reply = json!({ "id": id.0 }); + if !off.is_empty() { + reply["dynamicTextOff"] = json!(off); + } + Ok(reply) } /// An empty frame of `kind` (area type or type on a path) placed by `xf`, with the type options of @@ -654,6 +685,7 @@ fn empty_frame(src: &TextObject, style: vectorcraft_doc::CharStyle, kind: TextKi let mut t = src.clone(); t.runs = vec![TextRun { text: String::new(), style, inline: None }]; t.set_all_paras(src.para_at(0).clone()); + t.dynamic_text = false; t.kind = kind; t.xf = xf; refresh_bounds(&mut t); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 6d29550fa0..06368c6c7d 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, PathData, Vec2}; use super::edit::selected_roots; use super::pathops::{length_given, number_given, shape_node}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, id_param, index, number_or, ok, - str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, number_or, object_param, + ok, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -304,11 +304,13 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> { /// Recompute the layout caches (bounds and baselines) after a text edit. Every engine text edit ends here (typing /// through `text.editRange` too), inside its `Session::edit`, so this is where Auto Size area type -/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text: part of the same undo -/// step as the edit. +/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text, and Dynamic Text's Block +/// (`dynamic_text` on area type, [`block::block_fit`]) sizes each line to the frame: part of the +/// same undo step as the edit. pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); + block::block_fit(t); auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -320,6 +322,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { t.normalize_paras(); + block::block_fit(t); auto_height(t); let stamp = vectorcraft_text::LayoutStamp::now(); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); @@ -1026,7 +1029,7 @@ pub(crate) fn reshape_area_with(t: &mut TextObject, f: impl FnOnce(&mut TextObje } /// Area type's text, if `n` is area type. -fn area_text(n: Option<&Node>) -> Option<&TextObject> { +pub(crate) fn area_text(n: Option<&Node>) -> Option<&TextObject> { match n.map(|n| &n.kind) { Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) => Some(t), _ => None, @@ -1059,10 +1062,15 @@ fn size_area(t: &mut TextObject, w: Option<f64>, h: Option<f64>) -> bool { reshape_area_with(t, |t| t.transform_area(a)) } -/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText or `{"shrinkText": {"minPercent"}}`, -/// `fitMinPercent`), starting from `cur`. None when `p` sets neither (or only `fitMinPercent` -/// while the fit isn't Shrink Text). -pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaFit>> { +/// A fit `p` asks for: the Area Type Options fit, and whether Dynamic Text's Block +/// ([`TextObject::dynamic_text`]) is on. Block's fit is [`AreaFit::None`]: it replaces Auto Size +/// and Shrink Text to Fit. +pub(crate) type FitChoice = (AreaFit, bool); + +/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText|block or `{"shrinkText": {"minPercent"}}`, +/// `fitMinPercent`), starting from `cur` (`block`: Block is on). None when `p` sets neither (or only +/// `fitMinPercent` while the fit isn't Shrink Text). +pub(crate) fn fit_param(p: &Value, cur: AreaFit, block: bool, c: &str) -> Result<Option<FitChoice>> { check_numbers(p, &["fitMinPercent"], c)?; let min = p.get("fitMinPercent").and_then(Value::as_f64); let cur_min = match cur { @@ -1071,21 +1079,48 @@ pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaF }; let fit = match p.get("fit") { None | Some(Value::Null) => match (cur, min) { - (AreaFit::ShrinkText { .. }, Some(m)) => AreaFit::ShrinkText { min_percent: m }, + (AreaFit::ShrinkText { .. }, Some(m)) if !block => AreaFit::ShrinkText { min_percent: m }, _ => return Ok(None), }, + Some(Value::String(id)) if is_block_id(id) => return Ok(Some((AreaFit::None, true))), Some(Value::String(id)) => { - AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText, got {id}")))? + AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText|block, got {id}")))? } Some(v) => match serde_json::from_value::<AreaFit>(v.clone()).map_err(|e| bad(c, format!("bad fit: {e}")))? { AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: min.unwrap_or(min_percent) }, f => f, }, }; - Ok(Some(match fit { - AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) }, - f => f, - })) + Ok(Some(( + match fit { + AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) }, + f => f, + }, + false, + ))) +} + +/// Whether a `fit` id names Dynamic Text's Block (case, spaces, dashes and underscores ignored). +fn is_block_id(id: &str) -> bool { + matches!(id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "block" | "dynamictext") +} + +/// The `fit` id area type reports: `block` while Dynamic Text's Block is on, else its fit's. +pub(crate) fn fit_id(t: &TextObject) -> &'static str { + if t.dynamic_text { "block" } else { t.area.fit.id() } +} + +/// Dynamic Text's Block gaps `p` gives: `wordGap` (% of a word space, 0..1000) and `lineGap` (pt, +/// -1296..1296). A value that is not a number, or is outside its range, is an error. +pub(crate) fn block_gaps(p: &Value, c: &str) -> Result<(Option<f64>, Option<f64>)> { + let gap = |key: &str, (lo, hi): (f64, f64)| -> Result<Option<f64>> { + match number_given(p, key, c)? { + Some(v) if !(v.is_finite() && (lo..=hi).contains(&v)) => Err(bad(c, format!("`{key}` must be from {lo} to {hi}, not {v}"))), + v => Ok(v), + } + }; + use vectorcraft_doc::AreaOptions as O; + Ok((gap("wordGap", O::WORD_GAP)?, gap("lineGap", O::LINE_GAP)?)) } /// Area type's options as `text.areaOptions` reports them: the Area Type Options with `fit` as @@ -1095,7 +1130,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> { let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?; let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); if let Some(o) = v.as_object_mut() { - o.insert("fit".into(), json!(t.area.fit.id())); + o.insert("fit".into(), json!(fit_id(t))); o.insert("flow".into(), json!(t.area.flow)); // The gutter between rows, the gutter's when the rows have none of their own. o.insert("rowGutter".into(), json!(t.area.row_gutter.unwrap_or(t.area.gutter))); @@ -1104,6 +1139,9 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> { _ => AreaFit::DEFAULT_MIN_PERCENT, }; o.insert("fitMinPercent".into(), json!(min)); + let (word_gap, line_gap) = t.area.block_gaps(); + o.insert("wordGap".into(), json!(word_gap)); + o.insert("lineGap".into(), json!(line_gap)); if let Some((w, h, _)) = area_size(t) { o.insert("width".into(), json!(w)); o.insert("height".into(), json!(h)); @@ -1132,8 +1170,9 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> { // Checked once up front (its errors don't depend on the frame); each frame resolves `fit` // against its own setting below. let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default(); - fit_param(p, cur.fit, C)?; - let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null()); + fit_param(p, cur.fit, false, C)?; + let (word_gap, line_gap) = block_gaps(p, C)?; + let fit_given = ["fit", "fitMinPercent", "wordGap", "lineGap"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0)); let (w, h) = (size("width"), size("height")); let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect(); @@ -1142,7 +1181,7 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> { } // Each area type takes the options given over its own (#3759): setting one option on several // frames leaves their other options as they were. - let merged = |own: &vectorcraft_doc::AreaOptions| -> Result<vectorcraft_doc::AreaOptions> { + let merged = |own: &vectorcraft_doc::AreaOptions, block: bool| -> Result<(vectorcraft_doc::AreaOptions, bool)> { let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?; if let Some(o) = v.as_object_mut() { for (k, val) in &given { @@ -1162,17 +1201,29 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> { opts.inset = finite(opts.inset).clamp(0.0, 10_000.0); opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0); // Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames). - opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit); - Ok(opts) + let (fit, block) = fit_param(p, own.fit, block, C)?.unwrap_or((own.fit, block)); + opts.fit = fit; + opts.word_gap = word_gap.unwrap_or(own.word_gap); + opts.line_gap = line_gap.unwrap_or(own.line_gap); + Ok((opts, block)) }; let d = &s.doc()?.doc; - let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids + let planned: Vec<(NodeId, (vectorcraft_doc::AreaOptions, bool))> = ids .iter() - .filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area))) - .map(|(id, own)| merged(own).map(|o| (id, o))) + .filter_map(|id| area_text(d.node(*id)).map(|t| (*id, t))) + .map(|(id, t)| merged(&t.area, t.dynamic_text).map(|o| (id, o))) .collect::<Result<_>>()?; - let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| { + // Dynamic Text's Block is refused for threaded frames, as `type.dynamicText` refuses it. + let frames: Vec<String> = + planned.iter().filter(|(id, (_, block))| *block && !super::threads::story_of(d, *id).is_empty()).map(|(id, _)| id.0.to_string()).collect(); + if !frames.is_empty() { + let frames = frames.join(", "); + return Err(bad(C, format!("area type in a thread cannot use Dynamic Text: {frames}"))); + } + let apply = |t: &mut TextObject, (opts, block): &(vectorcraft_doc::AreaOptions, bool)| { t.area = opts.clone(); + // Block off keeps the sizes it wrote into the characters. + t.dynamic_text = *block; // Auto Size sets the height (Illustrator's dialog turns the Height field off). let h = if opts.fit == AreaFit::AutoHeight { None } else { h }; // A resized frame has laid its text out again; otherwise the new options do here. @@ -1222,7 +1273,7 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> { }; let mut items = Vec::with_capacity(raw.len()); for it in raw { - let id = id_param(it, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(it, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let mut refs = super::select::checked_refs(it.get("anchors"), C)?; refs.sort_unstable(); refs.dedup(); @@ -1253,7 +1304,7 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> { fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.reshapePath"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let mut refs = super::select::checked_refs(p.get("anchors"), C)?; refs.sort_unstable(); refs.dedup(); @@ -1284,7 +1335,7 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> { fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.setPathHandle"; - let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0); let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?; let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in"); @@ -1313,6 +1364,9 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> { #[cfg(test)] mod area_tests; +mod block; +#[cfg(test)] +mod block_tests; /// Width of the first line and of the space it can fill, with `tracking` on the first paragraph. /// The third value is where the first line ends in the plain text. diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 571c9c3469..5545e1be94 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -397,6 +397,49 @@ fn roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on() { assert!(text(&s).para_at(1).roman_hanging); } +/// Paragraph panel menu › Korean Line Break Anywhere: new type has it off and saves that; +/// `text.setFormat {koreanLineBreakAnywhere}` sets it per paragraph in one undo step and refuses a +/// value that is not true or false, a paragraph saved before the option opens with it on, and +/// paragraph styles carry it. `text.setRangeStyle`, a character command, does not take it. +#[test] +fn korean_line_break_anywhere_is_set_per_paragraph_and_saved_only_when_off() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "가나다\n라마"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).korean_line_break_anywhere, "new type has it off"); + assert_eq!(serde_json::to_value(text(&s).para_at(0)).unwrap()["korean_line_break_anywhere"], false); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the first paragraph (the caret's range). + s.execute("text.setFormat", &json!({"koreanLineBreakAnywhere": true, "start": 0, "end": 0})).unwrap(); + assert!(text(&s).para_at(0).korean_line_break_anywhere && !text(&s).para_at(1).korean_line_break_anywhere); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("korean_line_break_anywhere").is_none()); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(serde_json::to_value(text(&s).para_at(0)).unwrap()).unwrap(); + assert!(back.korean_line_break_anywhere); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(0).korean_line_break_anywhere); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(0).korean_line_break_anywhere); + // Saved before the option: on, the line breaks it was laid out with. + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(old.korean_line_break_anywhere); + assert!(s.execute("text.setFormat", &json!({"ids": [id], "koreanLineBreakAnywhere": "yes"})).is_err()); + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "koreanLineBreakAnywhere": false})).is_err()); + assert!(text(&s).para_at(0).korean_line_break_anywhere, "a refused call changes nothing"); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Anywhere", "attrs": {"korean_line_break_anywhere": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Anywhere", "id": id})).unwrap(); + assert!(text(&s).para_at(1).korean_line_break_anywhere); + s.execute("paraStyle.new", &json!({"name": "Words", "attrs": {"korean_line_break_anywhere": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Words", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).korean_line_break_anywhere && !text(&s).para_at(1).korean_line_break_anywhere); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs new file mode 100644 index 0000000000..06453f4983 --- /dev/null +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -0,0 +1,304 @@ +//! Dynamic Text's Block for area type ([`TextObject::dynamic_text`] on area type): each line as +//! typed is set to the frame's width by changing its font size, after every edit +//! ([`super::refresh_bounds`]). + +use vectorcraft_doc::{TextKind, TextObject, TextRun}; + +/// The font size range a line's first character is fitted within, in document points (the +/// Character panel's). +const SIZES: (f64, f64) = (0.1, 1296.0); + +/// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures +/// the lines and runs at most one more area layout. +pub(crate) const BLOCK_PASSES: usize = 4; + +/// One line as typed: `start..content` is its text, `content..end` the `\n` or U+2028 that ends it +/// (empty for the last line). `para` is the index of its paragraph, and `para_start` whether it +/// starts that paragraph. +#[derive(Clone, Copy, Debug)] +struct TypedLine { + start: usize, + content: usize, + end: usize, + para: usize, + para_start: bool, +} + +/// The lines as typed: the text split after each `\n` and U+2028. +fn typed_lines(text: &str) -> Vec<TypedLine> { + let mut out = vec![]; + let (mut start, mut para, mut para_start) = (0, 0, true); + for (i, c) in text.char_indices() { + if c == '\n' || c == '\u{2028}' { + let end = i + c.len_utf8(); + out.push(TypedLine { start, content: i, end, para, para_start }); + start = end; + para_start = c == '\n'; + if c == '\n' { + para += 1; + } + } + } + out.push(TypedLine { start, content: text.len(), end: text.len(), para, para_start }); + out +} + +/// The stored size of the character at `byte` (the run that holds it, not the one before it). +pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return r.style.size; + } + off = end; + } + vectorcraft_text::edit::style_at(runs, byte).size +} + +/// The stored size of each line's first character, in one pass over the runs. +fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec<f64> { + let mut out = Vec::with_capacity(lines.len()); + let (mut ri, mut off) = (0, 0); + for l in lines { + while let Some(r) = runs.get(ri) { + if l.start < off + r.text.len() { + break; + } + off += r.text.len(); + ri += 1; + } + out.push(runs.get(ri).map_or_else(|| size_at(runs, l.start), |r| r.style.size)); + } + out +} + +/// Each line's content width (trailing spaces left out) by its first byte, with `t` laid out as +/// point type, where no line wraps, with the word spacing `t`'s layout uses. +fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collections::HashMap<usize, f64> { + let mut probe = t.clone(); + for p in probe.para_styles_mut() { + p.justification = t.layout_justification(p); + } + probe.kind = TextKind::Point; + let laid = vectorcraft_text::layout(db, &probe); + let mut out = std::collections::HashMap::with_capacity(laid.lines.len()); + for m in &laid.lines { + out.entry(m.start).or_insert(m.x1 - m.x0); + } + out +} + +/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing +/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down +/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its +/// size rounded down to tenths, and None when that is its size, so fitting again changes nothing. +/// Room taken entirely by indents gives the smallest size. +fn refit(size: f64, width: f64, avail: f64, slope: f64) -> Option<f64> { + if width <= avail + 1e-6 && width + 0.1 * slope > avail { + let rounded = tenths(size); + return ((rounded - size).abs() > 1e-9).then_some(rounded); + } + Some(tenths(size + (avail.max(0.0) - width) / slope)) +} + +/// A size in document points rounded down to a whole number of tenths and kept within [`SIZES`]. +fn tenths(points: f64) -> f64 { + ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) +} + +/// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word +/// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line +/// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to +/// 1,296 pt, the line's other characters keeping their proportions to it) at which its width +/// equals the frame's width less the inset, the gutters and the paragraph's indents, and each +/// character's leading is its size plus the line gap. An empty line or one of only spaces keeps +/// its size. Nothing changes when the frame has no width along the lines or the type's transform +/// has no size. A line that still wraps at its first fit is made smaller, in at most +/// [`BLOCK_PASSES`] more passes. True when the text changed. +pub(crate) fn block_fit(t: &mut TextObject) -> bool { + if !t.dynamic_text { + return false; + } + let TextKind::Area { frame } = &t.kind else { return false }; + let (_, line_gap) = t.area.block_gaps(); + let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let before = t.runs.clone(); + + // The room along a line in one cell of the frame, before indents. + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + if !(cell.is_finite() && cell > 1e-9) { + return t.runs != before; + } + + let db = vectorcraft_text::FontDb::global(); + let text = t.plain_text(); + let lines = typed_lines(&text); + let widths = line_widths(db, t); + let sizes = first_sizes(&t.runs, &lines); + // Per line: (factor applied to its sizes, the room it fills, the last size measured and its + // width), or None to keep its size. + let mut fits: Vec<Option<(f64, f64, f64, f64)>> = lines + .iter() + .zip(&sizes) + .map(|(l, size)| { + if l.content == l.start { + return None; + } + let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?; + let para = t.para_at(l.para); + let first = if l.para_start { para.first_line_indent } else { 0.0 }; + let avail = cell - para.left_indent - para.right_indent - first; + let size = size * points; + if !(size.is_finite() && size > 0.0) { + return None; + } + Some((refit(size, width, avail, width / size).map_or(1.0, |n| n / size), avail, size, width)) + }) + .collect(); + + let gap = line_gap / points; + let min_leading = SIZES.0 / points; + // Always from the sizes the refit started with, so each pass sets a line's size once: the runs + // are split where the lines end and each piece scaled by its line's factor, in one pass. + let apply = |t: &mut TextObject, from: &[TextRun], fits: &[Option<(f64, f64, f64, f64)>]| { + let mut out = Vec::with_capacity(from.len() + lines.len()); + let (mut off, mut li) = (0, 0); + for r in from { + let end = off + r.text.len(); + let mut at = off; + loop { + while lines.get(li).is_some_and(|l| l.end <= at && li + 1 < lines.len()) { + li += 1; + } + let stop = lines.get(li).map_or(end, |l| l.end.clamp(at, end)); + let stop = if stop == at { end } else { stop }; + let f = fits.get(li).copied().flatten().map_or(1.0, |(f, ..)| f); + let mut piece = TextRun { text: r.text.get(at - off..stop - off).unwrap_or_default().to_string(), ..r.clone() }; + if at > off { + piece.style.glyph_alternate = None; + } + let st = &mut piece.style; + st.size *= f; + st.baseline_shift *= f; + st.tcy_up_down *= f; + st.tcy_left_right *= f; + st.leading = Some((st.size + gap).max(min_leading)); + if let Some(art) = &mut piece.inline { + art.baseline_shift *= f; + } + out.push(piece); + at = stop; + if at >= end { + break; + } + } + off = end; + } + vectorcraft_text::edit::normalize(&mut out); + t.runs = out; + }; + let start = t.runs.clone(); + apply(t, &start, &fits); + + // Each pass measures the lines again: a line whose width did not follow its size (a tab to a + // fixed stop) is fitted again from its measured width, and when every line measures right, a + // line the frame's shape or a list marker still wraps is made smaller, by what the line the + // layout gave it holds. + // Per line: the smallest size measured too wide, which a later pass never goes back to. + let mut too_wide = vec![f64::INFINITY; lines.len()]; + for _ in 0..BLOCK_PASSES { + let now_widths = line_widths(db, t); + let mut again = false; + for (((l, fit), size), wide) in lines.iter().zip(fits.iter_mut()).zip(&sizes).zip(too_wide.iter_mut()) { + let Some((f, avail, last_size, last_width)) = fit else { continue }; + let size = size * points; + let now = size * *f; + let Some(width) = now_widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9) else { continue }; + if width > *avail + 1e-6 { + *wide = wide.min(now); + } + // The slope between the last two sizes measured, where they differ: a line whose width + // has a part that stays as the size changes is fitted in one step. + let slope = Some((width - *last_width) / (now - *last_size)) + .filter(|s| (now - *last_size).abs() > 1e-9 && s.is_finite() && *s > 1e-9) + .unwrap_or(width / now); + (*last_size, *last_width) = (now, width); + let next = refit(now, width, *avail, slope).map(|n| if n >= *wide - 1e-9 { tenths(*wide - 0.1) } else { n }); + if let Some(next) = next.filter(|n| (n - now).abs() > 1e-9) { + *f = next / size; + again = true; + } + } + if !again { + let laid = vectorcraft_text::layout(db, t); + // Per typed line: how many laid-out lines it took, and the room of its first. + let mut parts: Vec<(usize, f64)> = vec![(0, 0.0); lines.len()]; + for m in &laid.lines { + let i = lines.partition_point(|l| l.start <= m.start).saturating_sub(1); + if let Some(p) = parts.get_mut(i) { + if p.0 == 0 { + p.1 = m.avail.1 - m.avail.0; + } + p.0 += 1; + } + } + for (((l, fit), (count, room)), size) in lines.iter().zip(fits.iter_mut()).zip(&parts).zip(&sizes) { + let Some((f, ..)) = fit else { continue }; + if *count < 2 { + continue; + } + let size = size * points; + let now = size * *f; + if now <= SIZES.0 + 1e-9 { + continue; + } + let width = now_widths.get(&l.start).copied().unwrap_or(f64::INFINITY); + let smaller = if room.is_finite() && *room > 0.0 && *room < width { tenths(now * room / width) } else { now }; + *f = smaller.min(tenths(now - 0.1)) / size; + again = true; + } + } + if !again { + break; + } + apply(t, &start, &fits); + } + t.runs != before +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn typed_lines_split_after_returns_and_forced_breaks() { + let l = typed_lines("ab\ncd\u{2028}e\n"); + let spans: Vec<_> = l.iter().map(|l| (l.start, l.content, l.end, l.para, l.para_start)).collect(); + assert_eq!(spans, vec![(0, 2, 3, 0, true), (3, 5, 8, 1, true), (8, 9, 10, 1, false), (10, 10, 10, 2, true)]); + assert_eq!(typed_lines("").len(), 1); + } + + #[test] + fn a_fitting_line_keeps_its_size_in_tenths() { + // 100 pt wide at 12 pt, 100.5 pt of room: a tenth larger would not fit. + assert_eq!(refit(12.0, 100.0, 100.5, 100.0 / 12.0), None); + assert_eq!(refit(12.34, 100.0, 100.5, 100.0 / 12.34), Some(12.3), "a size between tenths is rounded down"); + // Room for twice the width: twice the size. + assert_eq!(refit(12.0, 100.0, 200.0, 100.0 / 12.0), Some(24.0)); + // A part of the width that stays (a slope below width / size) needs more size. + assert_eq!(refit(12.0, 100.0, 150.0, 5.0), Some(22.0)); + } + + #[test] + fn sizes_round_down_to_tenths_within_the_range() { + assert_eq!(tenths(23.99), 23.9); + assert_eq!(tenths(24.0 - 1e-9), 24.0); + assert_eq!(tenths(0.01), 0.1); + assert_eq!(tenths(5000.0), 1296.0); + } +} diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs new file mode 100644 index 0000000000..ec458a0c9b --- /dev/null +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -0,0 +1,454 @@ +//! Dynamic Text's Block for area type: `type.dynamicText`, Area Type Options › Block and the refit +//! after edits. + +use serde_json::{Value, json}; +use vectorcraft_doc::{AreaFit, NodeId, NodeKind, TextKind, TextObject}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn area(s: &mut Session, w: f64, h: f64, text: &str) -> u64 { + let id = s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": {"width": w, "height": h}, "text": text})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + id +} + +fn text(s: &Session, id: u64) -> TextObject { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + k => panic!("not text: {k:?}"), + } +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The size of the character at `byte`. +fn size_at(t: &TextObject, byte: usize) -> f64 { + super::block::size_at(&t.runs, byte) +} + +/// Each laid-out line's (start byte, content width, room): the room is the frame's span less the +/// indents. +fn lines(t: &TextObject) -> Vec<(usize, f64, f64)> { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.iter().map(|l| (l.start, l.x1 - l.x0, l.avail.1 - l.avail.0)).collect() +} + +/// Every typed line is one laid-out line whose width is within one 0.1 pt size step of its room. +fn assert_block(t: &TextObject) { + let typed: Vec<usize> = std::iter::once(0).chain(t.plain_text().match_indices(['\n', '\u{2028}']).map(|(i, c)| i + c.len())).collect(); + let laid = lines(t); + assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), typed, "one laid-out line per typed line: {laid:?}"); + for &(start, width, room) in &laid { + let size = size_at(t, start); + if width <= 1e-9 || size >= 1296.0 - 1e-9 || size <= 0.1 + 1e-9 { + continue; + } + assert!(width <= room + 0.01, "line at {start} is wider than its room: {width} > {room}"); + assert!(width >= room * (size - 0.1) / size - 0.01, "line at {start} at {size} pt is short of its room: {width} < {room}"); + } +} + +#[test] +fn block_sets_each_typed_line_to_the_frame_width_by_its_size() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + let n = undo_len(&s); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r, json!({"on": true, "ids": [id], "fitScale": 1.0, "wordGap": 100.0, "lineGap": 0.0})); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!(t.area.fit, AreaFit::None); + assert_block(&t); + let (big, long, mid) = (size_at(&t, 0), size_at(&t, 4), size_at(&t, 31)); + assert!(big > mid && mid > long, "a shorter line is set larger: {big} {mid} {long}"); + for size in [big, long, mid] { + assert!(((size * 10.0).round() - size * 10.0).abs() < 1e-6, "{size} is a whole number of tenths"); + } + // Each character's leading is its size (line gap 0). + assert!(t.runs.iter().all(|r| r.style.leading == Some(r.style.size)), "{:?}", t.runs); + // Inspect reports it. + let doc = s.execute("document.inspect", &json!({})).unwrap(); + let node = doc["layers"][0]["children"].as_array().unwrap().iter().find(|k| k["id"] == id).unwrap().clone(); + assert_eq!((node["dynamicText"].as_bool(), node["fit"].as_str()), (Some(true), Some("block"))); +} + +#[test] +fn block_keeps_the_proportions_inside_a_line_and_fits_again_after_edits() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one two three\nfour"); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "size": 24})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert_block(&t); + let ratio = size_at(&t, 0) / size_at(&t, 4); + assert!((ratio - 2.0).abs() < 0.02, "the first word stays twice the size of the rest: {ratio}"); + let four = size_at(&t, 14); + // Typing into the first line makes it smaller, in the edit's own undo step; the second line stays. + let first = size_at(&t, 4); + let n = undo_len(&s); + s.execute("text.editRange", &json!({"id": id, "start": 13, "end": 13, "insert": " and more words"})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + let t = text(&s, id); + assert_block(&t); + assert!(size_at(&t, 4) < first, "{} < {first}", size_at(&t, 4)); + assert_eq!(size_at(&t, t.plain_text().find("four").unwrap()), four); + // A narrower frame sets every line smaller. + s.execute("text.areaOptions", &json!({"width": 150})).unwrap(); + let narrow = text(&s, id); + assert_block(&narrow); + let f = size_at(&narrow, narrow.plain_text().find("four").unwrap()) / four; + assert!((f - 0.5).abs() < 0.02, "half the width, half the size: {f}"); + // Undo brings the wider frame's sizes back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).runs, t.runs); +} + +#[test] +fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes() { + let mut s = session(); + // The tab goes to a stop that stays where it is as the size changes. + let id = area(&mut s, 300.0, 400.0, "Fit me\nand\tme too"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let fitted = text(&s, id).runs; + let laid = lines(&text(&s, id)); + assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), vec![0, 7], "{laid:?}"); + assert!(laid.iter().all(|l| l.1 <= l.2 + 0.01 && l.1 > l.2 * 0.95), "each line fills its room: {laid:?}"); + let n = undo_len(&s); + assert_eq!(s.execute("type.dynamicText", &json!({"on": true})).unwrap()["on"], true); + assert_eq!(undo_len(&s), n, "already on: no undo step"); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r["on"], false); + assert_eq!(undo_len(&s), n + 1); + let t = text(&s, id); + assert!(!t.dynamic_text); + assert_eq!(t.runs, fitted, "off keeps the sizes it was drawn at"); + // Edits no longer fit the lines. + s.execute("text.areaOptions", &json!({"width": 100})).unwrap(); + assert_eq!(text(&s, id).runs, fitted); + assert_eq!(s.execute("type.dynamicText", &json!({"on": false})).unwrap()["on"], false); + assert_eq!(undo_len(&s), n + 2, "already off: no undo step"); +} + +#[test] +fn convert_to_point_type_turns_block_off_keeping_its_sizes() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let sizes = |t: &TextObject| t.runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.leading)).collect::<Vec<_>>(); + let fitted = sizes(&text(&s, id)); + let n = undo_len(&s); + s.execute("type.convertToPointType", &json!({})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!(matches!(t.kind, TextKind::Point)); + assert!(!t.dynamic_text, "point type has Dynamic Text off"); + assert_eq!(sizes(&t), fitted, "point type keeps the sizes Block set"); + assert!(serde_json::to_value(&t).unwrap().get("dynamicText").is_none(), "saved without dynamicText"); + // Back to area type, the frame is not refitted: Block stays off. + s.execute("type.convertToAreaType", &json!({})).unwrap(); + let t = text(&s, id); + assert!(matches!(t.kind, TextKind::Area { .. })); + assert!(!t.dynamic_text, "Block does not come on again"); + assert_eq!(sizes(&t), fitted); + // Undo gives the Block frame back. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. })); + assert_eq!(sizes(&t), fitted); +} + +#[test] +fn bad_params_and_other_type_are_refused() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "Fit me"); + for bad in [ + json!({"on": "yes"}), + json!({"on": 1}), + json!({"wordGap": "wide"}), + json!({"wordGap": -1}), + json!({"wordGap": 1001}), + json!({"lineGap": 1297}), + json!({"lineGap": -1297}), + json!({"lineGap": true}), + ] { + assert!(s.execute("type.dynamicText", &bad).is_err(), "{bad}"); + } + assert!(!text(&s, id).dynamic_text); + let point = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [point]})).unwrap(); + let e = s.execute("type.dynamicText", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select type on a path or area type"), "{e}"); + // With point type selected too, only the area type changes. + s.execute("select.set", &json!({"ids": [id, point]})).unwrap(); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([id])); + assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text); + // A gap with only type on a path selected is an error, and nothing changes. + let path = s.execute("path.create", &json!({"d": "M60 550 L340 550"})).unwrap()["id"].as_u64().unwrap(); + let along = s.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [along]})).unwrap(); + let n = undo_len(&s); + for gap in [json!({"wordGap": 300}), json!({"on": false, "lineGap": 2})] { + let e = s.execute("type.dynamicText", &gap).unwrap_err().to_string(); + assert!(e.contains("need area type"), "{e}"); + } + assert_eq!(undo_len(&s), n); + assert!(!text(&s, along).dynamic_text); +} + +#[test] +fn gaps_set_word_spacing_and_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "two words\nthree more words"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let plain = text(&s, id); + let r = s.execute("type.dynamicText", &json!({"wordGap": 300, "lineGap": 6})).unwrap(); + assert_eq!((r["on"].as_bool(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some(true), Some(300.0), Some(6.0))); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!((t.area.word_gap, t.area.line_gap), (300.0, 6.0)); + // The layout uses the gap as the Desired word spacing; the paragraph keeps its own. + assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 100.0, 133.0]); + assert_eq!(t.layout_justification(t.para_at(0)).word_spacing, [80.0, 300.0, 300.0]); + assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs); + assert_block(&t); + assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room"); + // (own, used by the layout) word spacing of the first paragraph. + let spacing = |s: &Session| { + let t = text(s, id); + (t.para_at(0).justification.word_spacing, t.layout_justification(t.para_at(0)).word_spacing) + }; + // Minimum and Maximum move out only as far as the current gap needs, and the paragraph's own + // values apply again when Block is off. + s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 1000.0, 1000.0])); + s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0])); + s.execute("type.dynamicText", &json!({"wordGap": 0})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [0.0, 0.0, 133.0])); + s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0])); + // A paragraph's own values, outside the default range and equal to Desired too, stay through + // gap changes and refits after edits. + s.execute("text.setFormat", &json!({"wordSpacing": [20, 20, 150]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true, "wordGap": 20})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0])); + s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 1000.0, 1000.0])); + s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap(); + s.execute("text.editRange", &json!({"id": id, "start": 0, "end": 0, "insert": "a "})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 100.0, 150.0])); + s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0])); + // A gap alone on a frame without Block turns it on. + let other = area(&mut s, 200.0, 200.0, "x y"); + let r = s.execute("type.dynamicText", &json!({"lineGap": -2})).unwrap(); + assert_eq!(r["on"], true); + let t = text(&s, other); + assert!(t.dynamic_text); + assert_eq!((t.area.word_gap, t.area.line_gap), (100.0, -2.0)); +} + +#[test] +fn area_type_options_offer_block_with_its_gaps() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too"); + let q = s.execute("text.areaOptions", &json!({})).unwrap(); + assert_eq!((q["wordGap"].as_f64(), q["lineGap"].as_f64()), (Some(100.0), Some(0.0))); + // Gaps alone are kept for Block, without turning it on or changing the text. + let (n, runs) = (undo_len(&s), text(&s, id).runs); + s.execute("text.areaOptions", &json!({"wordGap": 200})).unwrap(); + let t = text(&s, id); + assert_eq!((undo_len(&s), t.dynamic_text, t.area.word_gap), (n + 1, false, 200.0)); + assert_eq!(t.runs, runs); + let r = s.execute("text.areaOptions", &json!({"fit": "block", "lineGap": 4})).unwrap(); + assert_eq!((r["fit"].as_str(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some("block"), Some(200.0), Some(4.0))); + assert!(text(&s, id).dynamic_text); + assert_block(&text(&s, id)); + // The reply passed back (as the dialog does) changes nothing; naming Block again keeps the gaps. + let n = undo_len(&s); + assert_eq!(s.execute("text.areaOptions", &r).unwrap(), r); + s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap(); + assert_eq!(undo_len(&s), n); + s.execute("text.areaOptions", &json!({"lineGap": 2})).unwrap(); + let t = text(&s, id); + assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 200.0, 2.0)); + assert!(s.execute("text.areaOptions", &json!({"lineGap": 5000})).is_err()); + assert!(s.execute("text.areaOptions", &json!({"wordGap": 2000})).is_err()); + assert!(s.execute("text.areaOptions", &json!({"wordGap": "wide"})).is_err()); + assert!(s.execute("text.areaOptions", &json!({"fit": "squash"})).unwrap_err().to_string().contains("shrinkText|block")); + // Shrink Text to Fit replaces Block, keeping the sizes. + let runs = text(&s, id).runs; + s.execute("text.areaOptions", &json!({"fit": "shrinkText"})).unwrap(); + let t = text(&s, id); + assert!(!t.dynamic_text); + assert_eq!(t.runs, runs); + // Block replaces Shrink Text to Fit and Auto Size. + s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap(); + assert_eq!(text(&s, id).area.fit, AreaFit::None); + // New area type can start with it. + let made = s + .execute( + "text.create", + &json!({"x": 10, "y": 300, "size": 12, "area": {"width": 200, "height": 200, "fit": "block", "wordGap": 150}, "text": "made"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + let t = text(&s, made); + assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 150.0, 0.0)); + assert_block(&t); +} + +#[test] +fn block_round_trips_through_the_native_format() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too"); + s.execute("type.dynamicText", &json!({"wordGap": 120, "lineGap": 3})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let bytes = vectorcraft_format::save(&doc, false); + let back = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 120.0, 3.0)); + assert_eq!(t.runs, text(&s, id).runs, "the fitted sizes are saved in the characters"); + // Saved as `dynamicText` with the gaps beside the area options; missing gaps read as their + // defaults, which are left out when saved. + let saved = serde_json::to_value(&**t).unwrap(); + assert_eq!((&saved["dynamicText"], &saved["area"]["wordGap"], &saved["area"]["lineGap"]), (&json!(true), &json!(120.0), &json!(3.0))); + let plain = serde_json::from_value::<vectorcraft_doc::AreaOptions>(json!({})).unwrap(); + assert_eq!((plain.word_gap, plain.line_gap), (100.0, 0.0)); + let plain: Value = serde_json::to_value(&plain).unwrap(); + assert!(plain.get("wordGap").is_none() && plain.get("lineGap").is_none(), "{plain}"); + // Turned off, it opens off with the sizes it had. + s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(!t.dynamic_text); + assert_eq!(t.runs, text(&s, id).runs); +} + +#[test] +fn edge_cases_fit_without_failing() { + let mut s = session(); + // Empty text, an empty line and a line of spaces keep their sizes. + let empty = area(&mut s, 300.0, 400.0, ""); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(size_at(&text(&s, empty), 0), 12.0); + let gaps = area(&mut s, 300.0, 400.0, "top\n\n \nbottom line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, gaps); + assert_eq!((size_at(&t, 4), size_at(&t, 5)), (12.0, 12.0)); + assert_block(&t); + // One word. + let word = area(&mut s, 300.0, 400.0, "Word"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_block(&text(&s, word)); + // A wide frame stops at 1,296 pt; a very long line in a narrow frame stops at 0.1 pt and wraps. + let wide = area(&mut s, 100_000.0, 400.0, "i"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(size_at(&text(&s, wide), 0), 1296.0); + let narrow = area(&mut s, 1.0, 400.0, &"long words ".repeat(40)); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, narrow); + assert_eq!(size_at(&t, 0), 0.1); + assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "at 0.1 pt the line still does not fit"); + // A frame inset so far that it has no width keeps the sizes. + let inset = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(size_at(&text(&s, inset), 0), 12.0); +} + +#[test] +fn block_fits_columns_lists_vertical_and_right_to_left_type() { + let mut s = session(); + // Two columns: each line is set to a column's width. + let cols = area(&mut s, 400.0, 600.0, "left column\nsecond"); + s.execute("text.areaOptions", &json!({"columns": 2, "gutter": 20})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, cols); + assert_block(&t); + assert!(lines(&t).iter().all(|l| (l.2 - 190.0).abs() < 1e-6), "{:?}", lines(&t)); + // A bulleted list: each item stays one line, the marker and its tab taking their room before + // the text (the room the layout reports takes in the marker's too). + let list = area(&mut s, 300.0, 400.0, "first item\nsecond item here"); + s.execute("text.setFormat", &json!({"list": "bullet"})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, list); + let laid = lines(&t); + assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), vec![0, 11], "{laid:?}"); + assert!(laid.iter().all(|l| l.1 <= l.2), "{laid:?}"); + assert!(size_at(&t, 0) > size_at(&t, 11), "the shorter item is larger"); + // Right-to-left text. + let rtl = area(&mut s, 300.0, 400.0, "שלום עולם\nטקסט ארוך יותר בשורה"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_block(&text(&s, rtl)); + // Vertical type: each column of text is set to the frame's height. + let v = s + .execute( + "text.create", + &json!({"x": 40, "y": 40, "size": 12, "vertical": true, "area": {"width": 300, "height": 200}, "text": "縦書き\nもっと長い縦書きの行"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [v]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, v); + assert!(t.vertical); + assert_block(&t); + assert!(lines(&t).iter().all(|l| (l.2 - 200.0).abs() < 1e-6), "{:?}", lines(&t)); +} + +#[test] +fn threaded_frames_are_refused_and_threading_turns_block_off() { + let mut s = session(); + let a = area(&mut s, 200.0, 300.0, "Fit me\nand me too"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let fitted = text(&s, a).runs; + let b = s.execute("shape.rectangle", &json!({"x": 400, "y": 40, "width": 200, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let n = undo_len(&s); + s.execute("text.thread.create", &json!({})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + let t = text(&s, a); + assert!(!t.dynamic_text, "threading turns Block off"); + assert_eq!(t.runs, fitted, "the text keeps its sizes"); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let e = s.execute("type.dynamicText", &json!({"on": true})).unwrap_err().to_string(); + assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}"); + let runs = text(&s, a).runs; + let e = s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap_err().to_string(); + assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}"); + assert_eq!(text(&s, a).runs, runs, "Area Type Options refuses it too, changing nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(text(&s, a).dynamic_text, "undo brings it back with the thread gone"); + assert!(matches!(text(&s, a).kind, TextKind::Area { .. })); +} + +#[test] +fn long_text_fits_in_a_bounded_number_of_layouts() { + let mut s = session(); + let story: String = (0..300).map(|i| format!("line number {i} {}\n", "x".repeat(i % 17))).collect(); + let id = area(&mut s, 300.0, 100_000.0, &story); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let used = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + assert_block(&text(&s, id)); + // The command fits the object to compare and to apply (each a measure, at most two layouts a + // pass and the caches), plus the reply's own. + let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 4; + assert!(used <= bound, "{used} layouts"); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 8d40002b3d..e2f08d9cd6 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -1,13 +1,13 @@ //! Type menu long tail (Change Case, Smart Punctuation, Convert To Area/Point Type, Type on a Path -//! Options, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) and the text -//! commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting). +//! Options, Dynamic Text, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) +//! and the text commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting). use serde_json::{Value, json}; -use vectorcraft_doc::{CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun}; use vectorcraft_geom::{Affine, Rect, shapes}; use super::object::choice; -use super::typecmd::refresh_bounds; +use super::typecmd::{area_text, block_gaps, refresh_bounds}; use super::{ CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, switch_or, targets, text_param, @@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> { "Convert To Point Type", ["Type"], None, - "{ids?|id?} area type → point type; soft line wraps become line breaks, and a frame of threaded text leaves its thread with the text it holds → {ids}", + "{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}", has_selection, to_point ), @@ -60,6 +60,42 @@ pub fn specs() -> Vec<CommandSpec> { has_selection, path_options ), + cmd!( + "type.pathCenter.top", + "Center on Top", + ["Type", "Type on a Path"], + None, + "{ids?|id?} slide the selected type on a closed path along it so that the middle of the span between its start and end brackets lands on the path's topmost point as the object is drawn (after its transform, so a rotated, scaled or skewed path is measured as it appears; on a level stretch such as a rectangle's top edge, its middle; with several separate topmost points, the middle of the shortest part of the path that holds them all), keeping the span's length (a full turn stays a full turn), and set the first paragraph's alignment to Center unless it is Center or Justify Center, so the type is centered there. Point type and area type in the selection are left as they are. Type on an open or compound path, type in a thread, and type on a path with no length or no height are refused with an error that names them, and nothing changes. When every object is already centered there, nothing changes and no undo step is recorded → {ids, start, end} (the first object's brackets)", + has_closed_path_type, + path_center_top + ), + cmd!( + "type.pathCenter.bottom", + "Center on Bottom", + ["Type", "Type on a Path"], + None, + "{ids?|id?} as type.pathCenter.top, on the path's bottommost point as drawn. The type is not flipped: on the bottom of a path that runs clockwise it reads upside down until Type on a Path Options › Flip turns it → {ids, start, end} (the first object's brackets)", + has_closed_path_type, + path_center_bottom + ), + cmd!( + "type.dynamicText", + "Dynamic Text", + ["Type"], + None, + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + has_dynamic_type, + dynamic_text + ), + cmd!( + "type.dynamicTextPreset", + "Dynamic Text Presets", + ["Type", "Dynamic Text Presets"], + None, + "{preset: \"circle\"|\"arch\"|\"bow\", position?: \"above\"|\"center\"|\"below\", flip?: bool, ids?|id?} put the selected point type and type on a path on a new path of the preset's shape with Dynamic Text on, so the text is sized to fill it (see type.dynamicText). Circle: a circle as wide as the text, the text running clockwise round all of it from its bottom; Arch: an arc of a circle bulging upward over 120°, as wide as the text; Bow: the same arc bulging downward. The width is, for point type, the length on the page of the longer side of the text's bounds, and for type on a path the longer side of its path's bounds on the page (so the same preset again leaves it as it is); the new path is centered where they were, and the shape is upright on the page when the object is rotated or scaled. position (omitted: above) sets Type on a Path Options › Align to Path: above stands the type on the path (descender), center centers it on the path (center), below hangs it from the path (ascender); flip true then turns the text to the other side of its path, running the other way. Type on a Path Options › effect and spacing stay. Area type in the selection is left as it is; a selection holding type on a path in a thread is refused. When nothing changes, no undo step is recorded → {ids, fitScale (the first object's factor)}", + has_preset_type, + dynamic_text_preset + ), cmd!( "type.fillPlaceholder", "Fill with Placeholder Text", @@ -293,11 +329,23 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> { continue; } let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - let b = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + // The frame is worked out in line space, where the lines are; vertical type turns it + // into text space with the lines. + let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); + // Across, the frame spans the lines as they are aligned: from their starts to their ends + // without the tracking after their last characters (`LineInfo::trailing`), not to the + // ink, which tracking can pull past an advance. Area type aligns them alike. + let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); + if x0.is_finite() && x1.is_finite() && x0 <= x1 { + (b.x0, b.x1) = (x0, x1); + } + // Line breaking counts that tracking: the slack holds the most of it. + let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); let size = t.first_style().size; // A little slack on the right so the text doesn't rewrap. let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); - let slack = size * 0.5; + let slack = size * 0.5 + trailing; // Slack goes where the alignment leaves room, so the text doesn't move or rewrap. let (sl, sr) = match t.para_at(0).justify { Justify::Center | Justify::JustifyCenter => (slack * 0.5, slack * 0.5), @@ -305,7 +353,7 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> { Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => (slack, 0.0), _ => (0.0, slack), }; - let frame = Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)); + let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; refresh_bounds(t); } @@ -341,6 +389,8 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { // Point type is in no thread: its first paragraph starts in it. t.first_para_continues = false; let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + // The lines are in line space; the frame's bounds are taken there too. + let fb = lay.line_xf.inverse().transform_rect_bbox(fb); let plain = t.plain_text(); let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8); // Soft wraps → explicit breaks (replace the space before the wrap when there is one). @@ -383,8 +433,14 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1, _ => x0, }; + // Point type has no Dynamic Text: Block is turned off, keeping the sizes it set, so + // converting back to area type does not turn it on again. + t.dynamic_text = false; t.kind = TextKind::Point; - t.xf *= Affine::translate((ox, baseline)); + // The origin is in the area type's line space; point type's line space puts its own + // origin there (vertical point type turns its lines about a different point). + let point_xf = if lay.vertical { vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).line_xf } else { Affine::IDENTITY }; + t.xf *= lay.line_xf * Affine::translate((ox, baseline)) * point_xf.inverse(); refresh_bounds(t); } Ok(()) @@ -392,6 +448,136 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { Ok(ids_json(&ids)) } +/// Whether type on a path `t` runs along one closed path (no open or compound path). +fn on_one_closed_path(t: &TextObject) -> bool { + matches!(&t.kind, TextKind::OnPath { path, .. } if path.subpaths.len() == 1 && path.is_closed()) +} + +/// Why `type.pathCenter.top` and `.bottom` refuse type on a path `ids`: those on an open or +/// compound path, then those in a thread; None when they take every one. +fn path_center_refusal(d: &Document, ids: &[NodeId]) -> Option<String> { + let open = ids.iter().filter(|id| !path_text(d.node(**id)).is_some_and(on_one_closed_path)).map(|id| id.0.to_string()).collect::<Vec<_>>(); + if !open.is_empty() { + let open = open.join(", "); + return Some(format!("type on an open or compound path cannot be centered on its top or bottom: {open}")); + } + let frames = threaded_ids(d, ids); + (!frames.is_empty()).then(|| format!("type on a path in a thread cannot be centered on its top or bottom: {frames}")) +} + +/// `type.pathCenter.top` and `.bottom` are enabled for a selection holding type on a path, all of +/// it on one closed path and none of it in a thread. +fn has_closed_path_type(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + let d = &st.doc; + let selected: Vec<NodeId> = st.selection.objects.to_vec(); + let paths: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| path_text(d.node(*id)).is_some()).collect(); + if paths.is_empty() { + return Err("select type on a closed path".into()); + } + path_center_refusal(d, &paths).map_or(Ok(()), Err) +} + +/// The brackets that center type on a path `t` on its path's topmost point (`bottom`: its +/// bottommost) as `t.xf` draws it, its span keeping its length; None for a path with no length or +/// no height. +fn centered_brackets(t: &TextObject, bottom: bool) -> Option<(f64, Option<f64>)> { + let TextKind::OnPath { path, end, .. } = &t.kind else { return None }; + let (from, to) = t.kind.path_span()?; + let arc = vectorcraft_geom::ArcPath::new(path); + if arc.is_empty() { + return None; + } + let flip = if bottom { Affine::FLIP_Y } else { Affine::IDENTITY }; + let middle = arc.topmost(flip * t.xf)? / arc.len(); + let run = to - from; + let start = (middle - run * 0.5).rem_euclid(1.0).clamp(0.0, 1.0); + // Without an end bracket the type runs once round; a full turn's end stays on its start. + let end = end.map(|_| if run >= 1.0 - 1e-12 { start } else { (start + run).rem_euclid(1.0).clamp(0.0, 1.0) }); + Some((start, end)) +} + +/// Whether brackets `a` and `b`, fractions of a closed path's length, are at one place within +/// rounding (0 and 1 are one place). +fn same_bracket(a: f64, b: f64) -> bool { + let d = (a - b).rem_euclid(1.0); + d.min(1.0 - d) <= 1e-9 +} + +fn path_center_top(s: &mut Session, p: &Value) -> Result<Value> { + path_center(s, p, false) +} + +fn path_center_bottom(s: &mut Session, p: &Value) -> Result<Value> { + path_center(s, p, true) +} + +/// Type › Type on a Path › Center on Top and Center on Bottom: slide the selected type on closed +/// paths along them so the middle of each span lands on the path's top (`bottom`: its bottom) as +/// drawn, and center the first paragraph, in one undo step; none when nothing changes. +fn path_center(s: &mut Session, p: &Value, bottom: bool) -> Result<Value> { + let c = if bottom { "type.pathCenter.bottom" } else { "type.pathCenter.top" }; + let centered = |j: Justify| matches!(j, Justify::Center | Justify::JustifyCenter); + // Each object the command changes, with its new brackets when they move and whether its first + // paragraph is set to Center. + let (ids, changes) = { + let d = &s.doc()?.doc; + let ids: Vec<NodeId> = texts(s, p, c)?.into_iter().filter(|i| path_text(d.node(*i)).is_some()).collect(); + if ids.is_empty() { + return Err(bad(c, "select type on a closed path")); + } + if let Some(why) = path_center_refusal(d, &ids) { + return Err(bad(c, why)); + } + let (mut changes, mut flat) = (vec![], vec![]); + for id in &ids { + let Some(t) = path_text(d.node(*id)) else { continue }; + let TextKind::OnPath { start, end, .. } = &t.kind else { continue }; + let Some((to_start, to_end)) = centered_brackets(t, bottom) else { + flat.push(id.0.to_string()); + continue; + }; + let stays = same_bracket(*start, to_start) + && match (end, to_end) { + (None, None) => true, + (Some(a), Some(b)) => same_bracket(*a, b), + _ => false, + }; + let align = !centered(t.para_at(0).justify); + if !stays || align { + changes.push((*id, (!stays).then_some((to_start, to_end)), align)); + } + } + if !flat.is_empty() { + let flat = flat.join(", "); + return Err(bad(c, format!("type on a path with no length or no height cannot be centered: {flat}"))); + } + (ids, changes) + }; + if !changes.is_empty() { + s.edit(if bottom { "Center on Bottom" } else { "Center on Top" }, |d, _| { + for (id, brackets, align) in &changes { + let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + if let (Some(b), TextKind::OnPath { start, end, .. }) = (brackets, &mut t.kind) { + (*start, *end) = *b; + } + if *align { + t.edit_paras(Some(0..1), |para| para.justify = Justify::Center); + } + refresh_bounds(t); + } + Ok(()) + })?; + } + let d = &s.doc()?.doc; + let (start, end) = ids.first().and_then(|id| path_text(d.node(*id))).map_or((0.0, None), |t| match &t.kind { + TextKind::OnPath { start, end, .. } => (*start, *end), + _ => (0.0, None), + }); + Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "start": start, "end": end})) +} + /// The options `type.pathOptions` sets; with none of them given it queries. const PATH_OPTIONS: [&str; 6] = ["start", "end", "flip", "effect", "alignToPath", "spacing"]; @@ -502,6 +688,324 @@ fn path_options(s: &mut Session, p: &Value) -> Result<Value> { options(s) } +/// Whether type `id` is a frame of a thread. +fn threaded(d: &Document, id: NodeId) -> bool { + !super::threads::story_of(d, id).is_empty() +} + +/// Type on a path or area type: the type Dynamic Text works on. +fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> { + path_text(n).or_else(|| area_text(n)) +} + +/// `type.dynamicText` is enabled for a selection holding type on a path or area type, none of it +/// in a thread. +fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + let d = &st.doc; + let selected: Vec<NodeId> = st.selection.objects.to_vec(); + let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_type(d.node(*id)).is_some()).collect(); + if types.is_empty() { + return Err("select type on a path or area type".into()); + } + threaded_refusal(d, &types).map_or(Ok(()), Err) +} + +/// Why Dynamic Text is refused for `ids`: the frames among them that are in a thread, type on a +/// path first; None when none is. +fn threaded_refusal(d: &Document, ids: &[NodeId]) -> Option<String> { + let (paths, areas): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| path_text(d.node(*id)).is_some()); + let frames = threaded_ids(d, &paths); + if !frames.is_empty() { + return Some(format!("type on a path in a thread cannot use Dynamic Text: {frames}")); + } + let frames = threaded_ids(d, &areas); + (!frames.is_empty()).then(|| format!("area type in a thread cannot use Dynamic Text: {frames}")) +} + +/// The ids among `ids` of frames of threads, as a list for a message; empty when there are none. +fn threaded_ids(d: &Document, ids: &[NodeId]) -> String { + ids.iter().filter(|id| threaded(d, **id)).map(|id| id.0.to_string()).collect::<Vec<_>>().join(", ") +} + +/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on +/// when a gap is given) on the selected type on a path and area type (Block, with its gaps), in +/// one undo step, and none when nothing changes. Turning it off keeps the sizes the text was drawn +/// at ([`bake_dynamic_text`]). +fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "type.dynamicText"; + let (word_gap, line_gap) = block_gaps(p, C)?; + let (ids, on, planned) = { + let d = &s.doc()?.doc; + let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_type(d.node(*i)).is_some()).collect(); + let first = *ids.first().ok_or_else(|| bad(C, "select type on a path or area type"))?; + if let Some(why) = threaded_refusal(d, &ids) { + return Err(bad(C, why)); + } + let gap_given = word_gap.is_some() || line_gap.is_some(); + if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some()) { + return Err(bad(C, "wordGap and lineGap need area type in the selection")); + } + let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?; + // Each object as the command leaves it, and only those it changes. + let mut planned: Vec<(NodeId, TextObject)> = vec![]; + for id in &ids { + let Some(t) = dynamic_type(d.node(*id)) else { continue }; + let mut after = t.clone(); + if matches!(t.kind, TextKind::Area { .. }) { + after.area.word_gap = word_gap.unwrap_or(t.area.word_gap); + after.area.line_gap = line_gap.unwrap_or(t.area.line_gap); + } + match (on, t.dynamic_text) { + (true, true) => refresh_bounds(&mut after), + (true, false) => { + after.dynamic_text = true; + // Block replaces Auto Size and Shrink Text to Fit. + if matches!(t.kind, TextKind::Area { .. }) { + after.area.fit = AreaFit::None; + } + refresh_bounds(&mut after); + } + (false, true) => { + bake_dynamic_text(&mut after); + } + (false, false) => {} + } + if after != *t { + planned.push((*id, after)); + } + } + (ids, on, planned) + }; + if !planned.is_empty() { + s.edit("Dynamic Text", |d, _| { + for (id, after) in &planned { + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = after.clone(); + } + } + Ok(()) + })?; + } + let d = &s.doc()?.doc; + let fit = + ids.first().and_then(|id| path_text(d.node(*id))).map_or(1.0, |t| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale); + let mut reply = json!({"on": on, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit}); + if let Some(t) = ids.iter().find_map(|id| area_text(d.node(*id))) { + let (w, l) = t.area.block_gaps(); + reply["wordGap"] = json!(w); + reply["lineGap"] = json!(l); + } + Ok(reply) +} + +/// Turn Dynamic Text off on `t`, keeping the sizes its layout draws it at: every run's size, +/// leading and baseline shifts take the fit factor ([`vectorcraft_text::scaled`]). False when it +/// was already off. +pub(crate) fn bake_dynamic_text(t: &mut TextObject) -> bool { + if !t.dynamic_text { + return false; + } + let f = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale; + if f.is_finite() && f != 1.0 { + *t = vectorcraft_text::scaled(t, f); + } + t.dynamic_text = false; + refresh_bounds(t); + true +} + +/// The shapes of `type.dynamicTextPreset`. +const PRESETS: [&str; 3] = ["circle", "arch", "bow"]; + +/// Point type and type on a path among `ids` and their descendants: the type +/// `type.dynamicTextPreset` puts on a path. +fn preset_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> { + text_ids(d, ids) + .into_iter() + .filter(|id| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::Point | TextKind::OnPath { .. }))) + .collect() +} + +/// `type.dynamicTextPreset` is enabled for a selection holding point type or type on a path, and +/// no type on a path in a thread. +fn has_preset_type(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + let d = &st.doc; + let ids = preset_ids(d, &st.selection.objects); + if ids.is_empty() { + return Err("select point type or type on a path".into()); + } + let frames = threaded_ids(d, &ids); + if !frames.is_empty() { + return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}")); + } + Ok(()) +} + +/// The path of Dynamic Text preset `preset` (one of [`PRESETS`]) `w` wide, centered on `c`, with +/// the start bracket the text starts at. Circle: a circle `w` across, run clockwise from its +/// bottom; Arch and Bow: a 120° arc of a circle whose chord is `w`, bulging up or down, run from +/// left to right. +fn preset_path(preset: &str, c: vectorcraft_geom::Point, w: f64) -> (vectorcraft_geom::PathData, f64) { + let h = w / 2.0; + if preset == "circle" { + // `shapes::ellipse` runs clockwise on screen from its left: its bottom is 3/4 of the way. + return (shapes::ellipse(Rect::new(c.x - h, c.y - h, c.x + h, c.y + h)), 0.75); + } + // A chord of `w` under 120°: radius w/√3, and the arc rises a half radius above its chord. + let r = w / 3f64.sqrt(); + let arch = preset == "arch"; + let cy = if arch { c.y - r / 4.0 + r } else { c.y + r / 4.0 - r }; + let circle = Rect::new(c.x - r, cy - r, c.x + r, cy + r); + // `shapes::ellipse_arc` runs counterclockwise on screen: right to left over the top. + let mut path = if arch { + shapes::ellipse_arc(circle, 30.0, 150.0, shapes::EllipseMode::Arc) + } else { + shapes::ellipse_arc(circle, 210.0, 330.0, shapes::EllipseMode::Arc) + }; + if arch { + path.reverse(); + } + (path, 0.0) +} + +/// `t` (point type or type on a path) on the path of `preset` with Dynamic Text on, Align to Path +/// `align`, and flipped when `flip`. The shape is made upright on the page and mapped back through +/// the object's transform, so a rotated or scaled object still shows a circle, an arch or a bow. +/// Point type: the path is as wide as the longer side of the text's layout bounds is long on the +/// page, centered on them; with no layout area (empty text), four ems of its first character +/// wide, centered on its estimated bounds. Type on a path: as wide as the longer side of its +/// path's bounds on the page, centered on them, so the same preset again gives the same path. +/// When the object's transform can't be undone, or undoing it gives a path that isn't finite, the +/// shape is made in the text's own space. +fn with_preset(t: &TextObject, preset: &str, align: vectorcraft_doc::PathAlign, flip: bool) -> TextObject { + let invertible = t.xf.is_finite() && t.xf.determinant() != 0.0 && t.xf.inverse().is_finite(); + // The transform the shape was made upright through, with the shape. + let ((path, start, w), xf) = invertible + .then(|| preset_shape(t, preset, t.xf).map(|s| (s, t.xf))) + .flatten() + .or_else(|| preset_shape(t, preset, Affine::IDENTITY).map(|s| (s, Affine::IDENTITY))) + .unwrap_or_else(|| { + let (path, start) = preset_path(preset, vectorcraft_geom::Point::ZERO, 48.0); + ((path, start, 48.0), Affine::IDENTITY) + }); + let mut out = t.clone(); + out.kind = TextKind::OnPath { path, start, end: None }; + out.path_align = align; + out.dynamic_text = true; + if flip { + out.flip_on_path(); + } + // The same preset again measures the path it made, which can differ in the last bits: a path + // within a billionth of its width of the old one on the page keeps the old one, so nothing + // changes. + if let (TextKind::OnPath { path: old, .. }, TextKind::OnPath { path: new, .. }) = (&t.kind, &mut out.kind) + && same_path(&old.transformed(xf), &new.transformed(xf), w * 1e-9) + { + *new = old.clone(); + } + refresh_bounds(&mut out); + out +} + +/// The path of `preset` for `t` made upright through transform `xf` (see [`with_preset`]), in the +/// text's space, with its start bracket and its width on the page; None when the path isn't +/// finite. +fn preset_shape(t: &TextObject, preset: &str, xf: Affine) -> Option<(vectorcraft_geom::PathData, f64, f64)> { + // How long `(x, y)` in the text's space is on the page. + let on_page = |x: f64, y: f64| (xf * vectorcraft_geom::Point::new(x, y) - xf * vectorcraft_geom::Point::ZERO).hypot(); + // The center on the page, and the width measured (0 when nothing can be measured). + let (c, longer) = match &t.kind { + TextKind::OnPath { path, .. } => path + .transformed(xf) + .bounds() + .filter(|b| b.is_finite()) + .map_or((xf * vectorcraft_geom::Point::ZERO, 0.0), |b| (b.center(), b.width().max(b.height()))), + _ => { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds; + match Some(lay).filter(|b| b.area() > 0.0 && b.is_finite()) { + Some(b) => (xf * b.center(), on_page(b.width(), 0.0).max(on_page(0.0, b.height()))), + None => (xf * Some(t.estimate_bounds()).filter(|b| b.is_finite()).map_or(vectorcraft_geom::Point::ZERO, |b| b.center()), 0.0), + } + } + }; + // Without a measured width: four ems of the first character, else 48 pt. + let size = t.first_style().size; + let w = if longer.is_finite() && longer > 1e-6 { + longer + } else if size.is_finite() && size > 0.0 && on_page(size * 4.0, 0.0) > 1e-6 { + on_page(size * 4.0, 0.0) + } else { + 48.0 + }; + let (path, start) = preset_path(preset, c, w); + let path = path.transformed(xf.inverse()); + let finite = path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()); + (finite && w.is_finite()).then_some((path, start, w)) +} + +/// Whether paths `a` and `b` have the same subpaths, closed alike, with every anchor and handle +/// within `eps` of each other. +fn same_path(a: &vectorcraft_geom::PathData, b: &vectorcraft_geom::PathData, eps: f64) -> bool { + let near = |p: vectorcraft_geom::Point, q: vectorcraft_geom::Point| (p - q).hypot() <= eps; + a.subpaths.len() == b.subpaths.len() + && a.subpaths.iter().zip(&b.subpaths).all(|(s, t)| { + s.closed == t.closed + && s.anchors.len() == t.anchors.len() + && s.anchors.iter().zip(&t.anchors).all(|(x, y)| x.kind == y.kind && near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out)) + }) +} + +/// Type › Dynamic Text Presets: put the selected point type and type on a path on a new path of +/// the preset's shape with Dynamic Text on, in one undo step, and none when nothing changes. +fn dynamic_text_preset(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "type.dynamicTextPreset"; + let key = "preset"; + let preset = choice(p, C, key, &PRESETS)?.ok_or_else(|| bad(C, format!("`{key}` must be one of {}", PRESETS.join(", "))))?; + let align = match choice(p, C, "position", &["above", "center", "below"])? { + Some("center") => vectorcraft_doc::PathAlign::Center, + Some("below") => vectorcraft_doc::PathAlign::Ascender, + _ => vectorcraft_doc::PathAlign::Descender, + }; + let flip = switch_or(p, "flip", false, C)?; + let (ids, changed) = { + let d = &s.doc()?.doc; + let ids = preset_ids(d, &targets(s, p)?); + if ids.is_empty() { + return Err(bad(C, "select point type or type on a path")); + } + let frames = threaded_ids(d, &ids); + if !frames.is_empty() { + return Err(bad(C, format!("type on a path in a thread cannot use Dynamic Text: {frames}"))); + } + let changed: Vec<(NodeId, TextObject)> = ids + .iter() + .filter_map(|id| match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some((*id, with_preset(t, preset, align, flip))).filter(|(_, new)| new != &**t), + _ => None, + }) + .collect(); + (ids, changed) + }; + if !changed.is_empty() { + s.edit("Dynamic Text", |d, _| { + for (id, new) in &changed { + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = new.clone(); + } + } + Ok(()) + })?; + } + let d = &s.doc()?.doc; + let fit = + ids.first().and_then(|id| path_text(d.node(*id))).map_or(1.0, |t| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale); + Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit})) +} + // ---------- placeholder / insert ---------- /// VectorCraft's own placeholder copy (not the classical Latin text). diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index f4db493d66..560da3942c 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -23,7 +23,9 @@ static NEW_VIEW: ParamSchema = ParamSchema::new( Param::new("name", Type::String).default_note("the first free \"View N\"").null_omitted(), Param::new("center", Type::Point), Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None }).doc("1 = 100%"), - Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"), + Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }) + .defaults_to("0") + .doc("clockwise on screen, as view.rotate turns the view"), ], "save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once)", ) @@ -46,7 +48,8 @@ static EDIT_VIEWS: ParamSchema = ParamSchema::new( "rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}", ); -static LIST_VIEWS: ParamSchema = ParamSchema::new(&[], "").returns("{views: [{name, center, zoom, rotation}]}").writes(Writes::Nothing); +static LIST_VIEWS: ParamSchema = + ParamSchema::new(&[], "").returns("{views: [{name, center, zoom, rotation (degrees clockwise)}]}").writes(Writes::Nothing); static TRANSPARENCY_GRID: ParamSchema = ParamSchema::new( &[Param::new("on", Type::Boolean).default_note("toggle").null_omitted()], @@ -86,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> { "New View…", ["View"], None, - "{name?: string (default: the first free \"View N\"), center: [x, y], zoom: number > 0 (1 = 100%), rotation?: number deg (default: 0)} save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once) → {name, index}", + "{name?: string (default: the first free \"View N\"), center: [x, y], zoom: number > 0 (1 = 100%), rotation?: number deg (default: 0) (clockwise on screen, as view.rotate turns the view)} save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once) → {name, index}", has_doc, new_view, schema: &NEW_VIEW @@ -101,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> { edit_views, schema: &EDIT_VIEWS ), - cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views, schema: &LIST_VIEWS), + cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation (degrees clockwise)}]}", has_doc, list_views, schema: &LIST_VIEWS), cmd!( query "view.transparencyGrid", "Show Transparency Grid", diff --git a/crates/engine/src/cmd/wand.rs b/crates/engine/src/cmd/wand.rs index 6e89a7544d..218871972f 100644 --- a/crates/engine/src/cmd/wand.rs +++ b/crates/engine/src/cmd/wand.rs @@ -8,7 +8,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::select::selectable_ids; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, id_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param}; /// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in /// points, opacity in percent. @@ -137,7 +137,7 @@ fn paintable(doc: &Document) -> Vec<NodeId> { if matches!(n.kind, NodeKind::Compound { .. }) { compounds.push(n.id); out.push(n.id); - } else if !n.is_container() { + } else if !n.is_container() && !n.is_ruler_guide() { out.push(n.id); } }); @@ -152,7 +152,7 @@ fn paintable(doc: &Document) -> Vec<NodeId> { } fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> { - let id = id_param(p, "id").ok_or_else(|| bad("select.magicWand", "missing id"))?; + let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?; let st = s.doc()?; let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone(); let w = s.menu.wand.clone(); diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 9e641a6e6a..d1c66d9d3c 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -645,7 +645,7 @@ fn flatten(rgba: &[u8], matte: [u8; 3]) -> impl Iterator<Item = [u8; 3]> + '_ { /// The File Info text `s.metadata` lets into the files: `(keyword, text)`. fn metadata(doc: &Document, s: &WebSettings) -> Vec<(&'static str, String)> { - doc.metadata.png_text(&doc.title).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect() + doc.metadata.png_text(doc.info_title()).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect() } /// Encode straight RGBA pixels (`w`×`h`) as `s` says; `doc` gives the metadata. diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 8d0d2b8eee..95b44776f0 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -25,10 +25,10 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo /// `(command, param)` pairs the journal records only so a replay reproduces the original run /// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the /// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the -/// Artboard tool had selected for its commands; the artboards and art Cut and Copy took with that +/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 26] = [ +const REPLAY_ONLY: [(&str, &str); 29] = [ ("file.new", "created"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), @@ -36,6 +36,9 @@ const REPLAY_ONLY: [(&str, &str); 26] = [ ("edit.pasteInPlace", "artboard"), ("edit.pasteInFront", "artboard"), ("edit.pasteInBack", "artboard"), + ("edit.pasteInPlace", "artboards"), + ("edit.pasteInFront", "artboards"), + ("edit.pasteInBack", "artboards"), ("object.align", "artboard"), ("object.distribute", "artboard"), ("object.distributeSpacing", "artboard"), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 3f0a641e2e..73c8ba8efe 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -430,6 +430,148 @@ impl ScriptScope { } Ok((real, bytes)) } + + /// The first granted folder, as people read it (`None` for a script given as text). + pub(crate) fn folder(&self) -> Option<PathBuf> { + self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone())) + } + + /// Does the absolute path `path` name a granted folder or a place inside one, by its names + /// alone, without regard to case? A path that does not is refused before the file system is + /// asked anything about it. + fn names_inside(&self, path: &Path) -> bool { + let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase(); + path.is_absolute() + && self.roots.iter().any(|r| { + let root = crate::cmd::findfiles::plain(r.clone()); + let mut names = path.components(); + root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) + }) + } + + /// The real path of the file or folder at `path`, which must be absolute: refused as + /// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every + /// granted folder, in which case the file system is not asked about it. + pub(crate) fn locate(&self, path: &Path) -> Result<PathBuf, ScriptRead> { + if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + return Err(ScriptRead::Refused); + } + probed(); + if check_read(&path.to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + let real = match std::fs::canonicalize(path) { + Ok(real) => real, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if std::fs::symlink_metadata(path).is_ok() || !self.missing_inside(path) { + return Err(ScriptRead::Refused); + } + return Err(ScriptRead::Missing); + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + }; + if !self.roots.iter().any(|r| inside(&real, r)) { + return Err(ScriptRead::Refused); + } + Ok(real) + } + + /// Is the missing `path` inside a granted folder: does the nearest folder above it that exists + /// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is + /// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too, + /// so a script cannot tell whether the folder a link leads to exists. + fn missing_inside(&self, path: &Path) -> bool { + path.ancestors() + .skip(1) + .find(|a| std::fs::symlink_metadata(a).is_ok()) + .and_then(|a| std::fs::canonicalize(a).ok()) + .is_some_and(|real| self.roots.iter().any(|r| inside(&real, r))) + } + + /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. + pub(crate) fn stat(&self, path: &Path) -> Result<ScriptEntry, ScriptRead> { + let real = self.locate(path)?; + let meta = std::fs::metadata(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; + let link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()); + #[cfg(windows)] + let hidden = std::os::windows::fs::MetadataExt::file_attributes(&meta) & 2 != 0; + #[cfg(not(windows))] + let hidden = real.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')); + Ok(ScriptEntry { + dir: meta.is_dir(), + file: meta.is_file(), + len: meta.len(), + created: meta.created().ok(), + modified: meta.modified().ok(), + hidden, + readonly: meta.permissions().readonly(), + link, + }) + } + + /// The names in the folder at `path` that `keep` keeps, with whether each is a folder, in the + /// order of their names. A name whose links lead out of every granted folder, or out of the + /// automation read roots in force, is left out. More + /// than `max` names kept, or more than [`MAX_LISTED`] names looked at, is + /// [`ScriptRead::TooLarge`]. + pub(crate) fn list(&self, path: &Path, max: usize, keep: impl Fn(&str) -> bool) -> Result<Vec<(String, bool)>, ScriptRead> { + let real = self.locate(path)?; + let entries = std::fs::read_dir(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; + let mut out = Vec::new(); + for (n, entry) in entries.enumerate() { + if n >= MAX_LISTED { + return Err(ScriptRead::TooLarge); + } + let Ok(entry) = entry else { continue }; + let name = entry.file_name().to_string_lossy().into_owned(); + if !keep(&name) { + continue; + } + let Ok(target) = std::fs::canonicalize(entry.path()) else { continue }; + if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() { + continue; + } + if out.len() >= max { + return Err(ScriptRead::TooLarge); + } + out.push((name, target.is_dir())); + } + out.sort(); + Ok(out) + } +} + +/// The most names [`ScriptScope::list`] looks at in one folder. +pub(crate) const MAX_LISTED: usize = 65_536; + +/// A file or folder as [`ScriptScope::stat`] gives it. +#[derive(Clone, Debug)] +pub(crate) struct ScriptEntry { + pub dir: bool, + /// A regular file. + pub file: bool, + pub len: u64, + pub created: Option<std::time::SystemTime>, + pub modified: Option<std::time::SystemTime>, + pub hidden: bool, + pub readonly: bool, + /// The path itself is a symbolic link. + pub link: bool, +} + +thread_local! { + /// How many paths [`ScriptScope::locate`] has asked the file system about on this thread. + static PROBES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +fn probed() { + PROBES.with(|p| p.set(p.get().saturating_add(1))); +} + +/// How many paths [`ScriptScope::locate`] has asked the file system about on this thread. +#[cfg(test)] +pub(crate) fn script_probes() -> usize { + PROBES.with(std::cell::Cell::get) } #[cfg(test)] diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index c474e25756..58832adf29 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -99,12 +99,17 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts, symbols: &SymbolBoxes) -> NodeKind::Text(t) => { v["text"] = json!(t.plain_text()); // Area type and type on a path: does the text fit (the red overflow "+")? Area type - // also reports its fit and Shrink Text's factor (1 unshrunk). + // also reports its fit (`block` for Dynamic Text's Block) and Shrink Text's factor (1 + // unshrunk), and type on a path its factor (1 when off); both report Dynamic Text. if !matches!(t.kind, vectorcraft_doc::TextKind::Point) { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); v["overflow"] = json!(lay.overflow); if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) { - v["fit"] = json!(t.area.fit.id()); + v["fit"] = json!(crate::cmd::typecmd::fit_id(t)); + v["fitScale"] = json!(lay.fit_scale); + v["dynamicText"] = json!(t.dynamic_text); + } else { + v["dynamicText"] = json!(t.dynamic_text); v["fitScale"] = json!(lay.fit_scale); } } @@ -112,6 +117,8 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts, symbols: &SymbolBoxes) -> _ => {} } if let Some(ch) = n.children() { + // A layer's ruler guides are listed by `guide.list`, not as its objects. + let ch: Vec<&std::sync::Arc<Node>> = ch.iter().filter(|c| !c.is_ruler_guide()).collect(); let total = ch.len(); let take_n = opts.child_limit.map_or(total, |l| l.min(total as u64) as usize); if opts.depth.is_none_or(|d| d > 0) { @@ -203,6 +210,10 @@ fn ancestors(d: &Document, id: vectorcraft_doc::NodeId) -> Vec<u64> { } fn collect_kind<'a>(n: &'a Node, kind: &str, path: &mut Vec<u64>, out: &mut Vec<Hit<'a>>) { + // Ruler guides are not objects (`guide.list` lists them). + if n.is_ruler_guide() { + return; + } if n.kind_label().eq_ignore_ascii_case(kind) { out.push((n, path.clone())); } @@ -274,8 +285,8 @@ fn document_base(s: &Session) -> Value { json!({ "uid": st.uid, "title": st.title(), - // The File Info title (`file.info`), where `title` comes from the file name once the document has one. - "fileInfoTitle": d.title, + // The File Info title (`file.info`): the title the file gave itself, else the document's name. `title` is the tab's name. + "fileInfoTitle": d.info_title(), "path": st.path, "dirty": st.is_dirty(), "revision": st.revision, @@ -295,7 +306,7 @@ fn document_base(s: &Session) -> Value { // The key object Align aligns to and Distribute Spacing spaces from (`select.key`). "key": st.selection.key.map(|k| k.0), // The ruler guide that is the key instead (`select.key {guide}`): an index into `guide.list`. - "keyGuide": st.selection.key_guide, + "keyGuide": st.selection.key_guide.and_then(|id| crate::cmd::guide_indexes(d, &[id]).first().copied()), "history": st.history.undo.iter().map(|h| h.label.clone()).collect::<Vec<_>>(), "redo": st.history.redo.iter().rev().map(|h| h.label.clone()).collect::<Vec<_>>(), "objects": d.node_count(), @@ -432,7 +443,8 @@ pub fn find_nodes(doc: &Document, filter: &FindFilter, limit: u64) -> (Vec<Value ids: Vec<NodeId>, } fn walk(nodes: &[Arc<Node>], w: &mut Walk) { - for n in nodes.iter().rev() { + // Ruler guides are not objects (`guide.list` lists them). + for n in nodes.iter().rev().filter(|n| !n.is_ruler_guide()) { if w.filter.hits(n, &w.symbols) { w.ids.push(n.id); if (w.out.len() as u64) < w.limit { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 091348a6bd..cd3a103a86 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -171,10 +171,6 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option<std::path::PathBuf>, - /// The plug-in ids whose grant in the plug-in store should be gone but could not be removed: - /// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful - /// [`Session::store_grant`] for the id takes it out. - ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option<cmd::plugin::HandedIn>, @@ -258,6 +254,8 @@ pub struct Session { pub recovery: cmd::recovery::Recovery, /// The running script's job, while there is one: the mutation lease ([`script`]). pub(crate) script_key: Option<script::JobKey>, + /// The named script engines this session keeps ([`script`]). + pub(crate) script_engines: script::EnginesKey, /// Stops the running script at its next instruction; the same flag for every run. pub(crate) script_stop: vectorcraft_js::Interrupt, /// The report of the run that ended last. @@ -280,6 +278,9 @@ pub struct Session { pub(crate) in_tool_actions: bool, /// While [`Session::preview`] runs its command: its edits are the interaction's own. previewing: bool, + /// The images Remove Background decoded during the interaction's preview steps, emptied when + /// it ends ([`cmd::DecodedImages`]). + pub(crate) decoded_images: cmd::DecodedImages, /// Envelope Options with no envelope selected: the options and fidelity new envelopes get /// (`None`: the reference app's defaults, fidelity 50); not saved. pub(crate) envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, @@ -301,6 +302,8 @@ pub struct Session { pub(crate) press_point: Option<Option<(usize, cmd::gradient::StopOwner)>>, /// A guide being dragged out of a ruler ([`Session::ruler_guide`]). pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>, + /// The rulers' origin being dragged out of their corner ([`Session::ruler_origin_drag`]). + pub(crate) ruler_origin: Option<vectorcraft_tools::rulerguide::OriginDrag>, /// Which selected type overflows its frame, for the ports every tool but the Type tools shows. pub(crate) port_marks: vectorcraft_tools::text::PortMarks, /// The last search for the files of missing fonts (`text.findFontFiles`), until another @@ -347,6 +350,15 @@ pub(crate) fn adding_fonts() -> std::sync::MutexGuard<'static, ()> { FONTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } +/// Whether the tests that run every command with `{}` run command `id`. `plugin.clearCache` is +/// left out: without an id it empties the cache of every plug-in installed in the process, which +/// includes the caches that the plug-in storage tests check while they run. +/// `tests/plugin_clear_cache.rs` runs it with `{}` in a test binary of its own. +#[cfg(test)] +pub(crate) fn runs_with_empty_params(id: &str) -> bool { + id != "plugin.clearCache" +} + #[cfg(test)] use tests::{ adjust as tests_adjust, clip as tests_clip, colormgmt as tests_colormgmt, expand as tests_expand, large_edits as tests_large_edits, diff --git a/crates/engine/src/sanity.rs b/crates/engine/src/sanity.rs index b28cc23ca8..22e0ce956f 100644 --- a/crates/engine/src/sanity.rs +++ b/crates/engine/src/sanity.rs @@ -45,7 +45,7 @@ pub(crate) fn doc_sane(d: &Document, sel: &Selection) -> bool { && d.ruler_origin.x.abs() <= MAX_COORD && d.ruler_origin.y.abs() <= MAX_COORD && d.artboards.iter().all(|a| rect_in_range(a.rect)) - && d.guides.iter().all(|g| g.pos.is_finite() && g.pos.abs() <= MAX_COORD) + && d.ruler_guides().iter().all(|g| g.pos.is_finite() && g.pos.abs() <= MAX_COORD) && objects_in_range(d, &sel.objects) } diff --git a/crates/engine/src/schemas.rs b/crates/engine/src/schemas.rs index 61ec8f0fd6..fb08bb649c 100644 --- a/crates/engine/src/schemas.rs +++ b/crates/engine/src/schemas.rs @@ -26,10 +26,10 @@ use crate::cmd::{CommandSpec, bad, command_specs}; use crate::{EngineError, Result}; /// The API level of the commands' parameters. -pub const API_VERSION: u32 = 2; +pub const API_VERSION: u32 = 3; /// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s. -pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653)]; +pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a)]; /// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]). pub fn schema_hash() -> u64 { diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 1faf624f16..a674396f4b 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -290,12 +290,12 @@ impl Dialogs { } } -/// Adds `alert`, `confirm` and `prompt` to the realm. -pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError> { +/// Adds `alert`, `confirm` and `prompt` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { use Arg::{Bool, Text, TextOrUndefined}; let call = |kind: DialogKind| -> HostFunction { - let h = host.clone(); - Rc::new(move |args| open(&h, kind, &args)) + let l = link.clone(); + Rc::new(move |args| open(&*super::current(&l)?, kind, &args)) }; realm.define_host_function("alert", vec![Text, TextOrUndefined, Bool], call(DialogKind::Alert))?; realm.define_host_function("confirm", vec![Text, Bool, TextOrUndefined], call(DialogKind::Confirm))?; diff --git a/crates/engine/src/script/dollar.rs b/crates/engine/src/script/dollar.rs index 3e6b005844..fcf6dbf542 100644 --- a/crates/engine/src/script/dollar.rs +++ b/crates/engine/src/script/dollar.rs @@ -4,14 +4,15 @@ //! the locale the global `localize` reads //! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/>). //! -//! Every value here belongs to one run: a run starts with the locale of the interface, the -//! environment values of [`ENV_NAMES`] read from the process, localization off and a timer at zero, -//! and what a script changes ends with its run. `$.setenv` never changes the process's environment. +//! Every value here belongs to one run, in a named engine too ([`RunState`]): a run starts with the +//! locale of the interface, the environment values of [`ENV_NAMES`] read from the process, +//! localization off and a timer at zero, and what a script changes ends with its run. `$.setenv` +//! never changes the process's environment. //! //! These are VectorCraft's own values and rules: `$.appEncoding` is always UTF-8; `$.build` and -//! `$.version` give VectorCraft's version, `$.engineName` is `VectorCraft` and `$.buildDate` is -//! `null`; `$.flags` takes only 512, which turns localization on; `$.level` and `$.memCache` are 0 -//! and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the +//! `$.version` give VectorCraft's version, `$.engineName` is the name `#targetengine` gave, or +//! `VectorCraft` without one, and `$.buildDate` is `null`; `$.flags` takes only 512, which turns +//! localization on; `$.level` and `$.memCache` are 0 and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the //! realm reads scripts as strict mode code; `$.bp` and `$.colorPicker` throw, since scripts have no //! debugger and cannot show a dialog; `$.gc` does nothing, since the interpreter collects its own //! garbage; `$.getenv` and `$.setenv` know only [`ENV_NAMES`], with values of at most @@ -25,7 +26,7 @@ use std::time::Duration; use vectorcraft_js::{Data, HostError, HostItem, Localization, ScriptItem}; -use super::{Host, function}; +use super::{Link, current, function}; /// The longest `$.sleep`, in milliseconds. pub const MAX_SLEEP_MS: f64 = 1_000.0; @@ -36,12 +37,34 @@ pub const MAX_ENV_BYTES: usize = 64; /// The value of `$.flags` that turns localization on, the only one a script may set. pub const LOCALIZE_FLAG: f64 = 512.0; -/// What `$` knows of a run. +/// What `$` knows of its realm. pub(crate) struct RunInfo { - /// The locale the run starts with, such as `de_DE`. - pub locale: String, /// The realm reads scripts as strict mode code. pub strict: bool, + /// The name `#targetengine` gave the realm's engine. + pub engine: Option<String>, +} + +/// The values of `$` that belong to one run, which the run's host holds. +pub(crate) struct RunState { + /// The locale the run starts with, such as `de_DE`. + locale: String, + env: RefCell<Vec<(&'static str, Option<String>)>>, + /// The time since the run started at which `$.hiresTimer` was last read. + timer: Cell<Duration>, +} + +impl RunState { + pub(crate) fn new(locale: &str) -> RunState { + RunState { locale: locale.to_string(), env: RefCell::new(process_env()), timer: Cell::new(Duration::ZERO) } + } +} + +/// Sets `localization` as a run starts: `locale`, this system's platform and localization off. +pub(super) fn start_run(localization: &Localization, locale: &str) { + localization.set_enabled(false); + localization.set_locale(locale); + localization.set_platform(platform()); } /// The locale for an interface language code such as `de`, `pt-br` or `zh-hant`: the language, @@ -148,14 +171,10 @@ fn text(s: impl Into<String>) -> Data { Data::String(s.into()) } -/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`. -pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> { +/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`. They +/// act for the run that `link` holds when they are called. +pub(super) fn members(link: &Link, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> { let version = env!("CARGO_PKG_VERSION"); - let host_locale = info.locale.clone(); - localization.set_locale(&info.locale); - localization.set_platform(platform()); - let env = Rc::new(RefCell::new(process_env())); - let timer = Rc::new(Cell::new(Duration::ZERO)); let getter = |f: Rc<dyn Fn() -> Data>| HostItem::Getter(function(move |_| Ok(f()))); let property = |get: Rc<dyn Fn() -> Data>, set: Rc<dyn Fn(Data) -> Result<(), HostError>>| HostItem::Property { get: function(move |_| Ok(get())), @@ -167,13 +186,13 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza let fail = |message: &'static str| HostItem::Function(function(move |_| Err(HostError::Error(message.to_string())))); let locale = { - let (l, s) = (localization.clone(), localization.clone()); + let (l, s, run) = (localization.clone(), localization.clone(), link.clone()); property( Rc::new(move || text(l.locale())), Rc::new(move |v| { let locale = match v { - Data::Null | Data::Undefined => host_locale.clone(), - Data::String(t) if t.is_empty() => host_locale.clone(), + Data::Null | Data::Undefined => current(&run)?.dollar.locale.clone(), + Data::String(t) if t.is_empty() => current(&run)?.dollar.locale.clone(), Data::String(t) => script_locale(&t).ok_or_else(|| HostError::Range(BAD_LOCALE.to_string()))?, _ => return Err(HostError::Type(BAD_LOCALE.to_string())), }; @@ -224,31 +243,34 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza let mem_cache = property(Rc::new(|| Data::Number(0.0)), Rc::new(|_| Err(HostError::Error("$.memCache: the memory cache size cannot be set".into())))); let hires_timer = { - let (h, last) = (host.clone(), timer.clone()); + let l = link.clone(); getter(Rc::new(move || { + let Ok(h) = current(&l) else { return Data::Number(0.0) }; let Some(now) = h.elapsed() else { return Data::Number(0.0) }; - let since = now.saturating_sub(last.replace(now)); + let since = now.saturating_sub(h.dollar.timer.replace(now)); #[allow(clippy::cast_precision_loss)] Data::Number(since.as_micros() as f64) })) }; let getenv = { - let (h, env) = (host.clone(), env.clone()); + let l = link.clone(); function(move |a| { let name = one_string(&a, "getenv")?; + let h = current(&l)?; h.charge_call(name.len() as u64 + 2)?; - let env = env.borrow(); + let env = h.dollar.env.borrow(); let found = env.iter().find(|(n, _)| *n == name).and_then(|(_, v)| v.clone()); Ok(found.map_or(Data::Null, Data::String)) }) }; let setenv = { - let (h, env) = (host.clone(), env.clone()); + let l = link.clone(); function(move |a| { let name = one_string(&a, "setenv")?; let Some(Data::String(v)) = a.get(1) else { return Err(HostError::Type("$.setenv: give a value, as a string".into())) }; + let h = current(&l)?; h.charge_call((name.len() + v.len()) as u64 + 4)?; - let mut env = env.borrow_mut(); + let mut env = h.dollar.env.borrow_mut(); let Some(slot) = env.iter_mut().find(|(n, _)| *n == name) else { return Err(HostError::Error(format!("$.setenv: only {} can be set", ENV_NAMES.join(", ")))); }; @@ -260,8 +282,9 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza }) }; let sleep = { - let h = host.clone(); + let l = link.clone(); function(move |a| { + let h = current(&l)?; let ms = match a.first() { Some(Data::Number(n)) if (0.0..=MAX_SLEEP_MS).contains(n) => *n, Some(Data::Number(_)) => return Err(HostError::Range(format!("$.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS}"))), @@ -282,7 +305,7 @@ pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localiza ("buildDate".into(), value(Data::Null)), ("colorPicker".into(), fail("$.colorPicker: scripts cannot show a dialog yet")), ("decimalPoint".into(), decimal), - ("engineName".into(), value(text("VectorCraft"))), + ("engineName".into(), value(text(info.engine.unwrap_or_else(|| "VectorCraft".into())))), ("error".into(), HostItem::Script(ScriptItem::LastError)), ("flags".into(), flags), ("gc".into(), HostItem::Function(function(|_| Ok(Data::Undefined)))), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs new file mode 100644 index 0000000000..ec848a973e --- /dev/null +++ b/crates/engine/src/script/files.rs @@ -0,0 +1,1043 @@ +//! `File` and `Folder`: a script's objects for files and folders, as the help pages describe them +//! (<https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/>, +//! <https://extendscript.docsforadobe.dev/file-system-access/file-object/> and +//! <https://extendscript.docsforadobe.dev/file-system-access/folder-object/>). The classes are +//! built-ins of the realm ([`Realm::define_file_classes`]); the host functions here make every +//! path check and every read. +//! +//! An object holds an absolute path: a relative path is taken from `Folder.current`, `~` is the home +//! folder, `%xx` escapes are read as UTF-8, and on Windows both `/` and `\` separate names and +//! `/c/…` names drive C. Naming a path does not look anything up. +//! +//! VectorCraft's own rules: +//! +//! - A script reads only inside its [`ScriptScope`]: a script run from a file reads in that file's +//! folder and the folders below it, and a script given as text reads nothing. A path whose names +//! lie outside, a Windows network or device path (`\\host\share`, `\\?\`, `\\.\`), and a path that +//! leads out through a link are refused before or instead of opening anything: `exists` is false, +//! the dates are `null`, `getFiles` gives `null`, and `error` is [`ACCESS_DENIED`]. The automation +//! read roots apply as well, so a run with roots in force reads only inside both. +//! - `File(path)` without `new` gives a `Folder` for an existing folder, and `Folder(path)` gives a +//! `File` for an existing file, only where the path may be read. +//! - Opening reads the whole file, at most [`MAX_FILE_BYTES`], checked from its size before any of +//! it is read; a run reads at most [`MAX_RUN_BYTES`] in all and ends past that, and has at most +//! [`MAX_OPEN`] files open at once. +//! - The encoding of an opened file is the one its byte order mark gives (UTF-8, UTF-16LE or +//! UTF-16BE), otherwise the one the script set, otherwise UTF-8 when the bytes are valid UTF-8, +//! otherwise CP1252. `read`, `readln` and `readch` count characters and `seek` and `tell` bytes; +//! `readln` and `readch` take CR, LF, CRLF and LFCR as one line end, and `readch` gives a line end +//! as `"\n"`. A character the encoding cannot decode fails the read with [`UNDECODABLE`] and +//! leaves the position where it was. +//! - `getFiles` lists at most [`MAX_ENTRIES`] entries, sorted by name, and looks at most +//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?` without regard to case, +//! in at most [`MAX_MASK_STEPS`] steps for one listing. +//! - A path longer than [`MAX_PATH_CHARS`] characters is refused before it is split into names. +//! - Writing (`open` with `w`, `e` or `a`, `write`, `copy`, `remove`, `rename`, `create` and the +//! property setters), the file and folder dialogs and `execute` are not available: they return +//! `false` or `null` and set `error`. `execute` is counted in the report's `fileExecutes`. +//! - In a wasm build every lookup fails with [`NO_WEB`]. + +use std::collections::HashMap; +use std::path::Path; +use std::rc::Rc; +use std::sync::atomic::{AtomicU32, Ordering}; + +use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; + +use super::{Host, bump}; +use crate::file_access::{ScriptRead, ScriptScope}; + +/// The most bytes of one file a script opens. +pub const MAX_FILE_BYTES: usize = 8 << 20; +/// The most bytes of files one run opens, all of them counted together. +pub const MAX_RUN_BYTES: usize = 32 << 20; +/// The most entries `getFiles` gives. +pub const MAX_ENTRIES: usize = 2048; +/// The most files a run has open at once. +pub const MAX_OPEN: usize = 256; +/// The most characters of a path a script gives. +pub const MAX_PATH_CHARS: usize = 32_767; +/// The most steps one `getFiles` listing spends matching its mask against names. +pub const MAX_MASK_STEPS: usize = 1 << 24; + +pub(crate) const ACCESS_DENIED: &str = "Script file access denied"; +pub(crate) const TOO_LARGE: &str = "Script file exceeds 8 MiB"; +pub(crate) const NOT_OPEN: &str = "Script file is not open"; +pub(crate) const UNDECODABLE: &str = "Script file cannot be decoded"; +pub(crate) const NOT_REGULAR: &str = "Script file is not a regular file"; +pub(crate) const NOT_FOUND: &str = "Script file does not exist"; +pub(crate) const READ_FAILED: &str = "Script file could not be read"; +pub(crate) const LISTING_TOO_LARGE: &str = "Script folder has more than 2,048 entries"; +pub(crate) const BAD_MODE: &str = "Script file open mode must be r, w, e or a"; +pub(crate) const NO_WRITES: &str = "Script file writing is not available"; +pub(crate) const NO_PICKER: &str = "Script file dialogs are not available"; +pub(crate) const NO_EXECUTE: &str = "Script files cannot be opened in another application"; +pub(crate) const NO_WEB: &str = "Script file access is unavailable on the web"; +pub(crate) const TOO_MANY_OPEN: &str = "Script has 256 files open"; +pub(crate) const PATH_TOO_LONG: &str = "Script file path exceeds 32,767 characters"; +pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many steps to match"; +const OVER_RUN_BYTES: &str = "the script opened more file data than one run may open (32 MiB)"; + +/// The id of the next file a script opens. Ids are unique across runs, so a `File` that a named +/// engine kept from an earlier run does not name a file a later run opened. +static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1); + +/// The script's file state: its scope, where `Folder.current` starts, the files it has open and how +/// much it has read. +pub(crate) struct Disk { + scope: ScriptScope, + home: String, + start: String, + open: HashMap<u32, Open>, + temps: u32, + bytes: usize, +} + +impl Disk { + /// The state of a run whose own files are read in `scope`. + pub(crate) fn new(scope: &ScriptScope) -> Self { + let home = home_folder(); + let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); + Self { scope: scope.clone(), home, start, open: HashMap::new(), temps: 0, bytes: 0 } + } + + /// The path `text` names from the folder `base`, a platform path; `text`'s URI escapes are + /// decoded when `uri` is set. + fn pathname(&self, text: &str, base: &str, uri: bool) -> Pathname { + let root = Pathname::root(WINDOWS); + let home = Pathname::parse(&self.home, &root, &root, WINDOWS, false); + let base = Pathname::parse(base, &home, &home, WINDOWS, false); + Pathname::parse(text, &base, &home, WINDOWS, uri) + } + + /// The path `path` as the scope takes it, or why it is refused by its form alone. + fn checked<'a>(&self, path: &'a str) -> Result<&'a Path, &'static str> { + if cfg!(target_arch = "wasm32") { + return Err(NO_WEB); + } + if too_long(path) { + return Err(PATH_TOO_LONG); + } + let p = Path::new(path); + if !p.is_absolute() || (WINDOWS && (path.starts_with(r"\\") || path.starts_with("//"))) { + return Err(ACCESS_DENIED); + } + Ok(p) + } + + fn stat(&self, path: &str) -> Result<Option<crate::file_access::ScriptEntry>, &'static str> { + match self.scope.stat(self.checked(path)?) { + Ok(e) => Ok(Some(e)), + Err(ScriptRead::Missing) => Ok(None), + Err(ScriptRead::Refused | ScriptRead::TooLarge) => Err(ACCESS_DENIED), + Err(ScriptRead::Failed(_)) => Err(READ_FAILED), + } + } + + fn open_file(&mut self, path: &str, encoding: &str) -> Result<u32, HostError> { + let fail = |m: &str| Err(HostError::Error(m.to_string())); + if self.open.len() >= MAX_OPEN { + return fail(TOO_MANY_OPEN); + } + let entry = match self.stat(path) { + Ok(Some(e)) => e, + Ok(None) => return fail(NOT_FOUND), + Err(m) => return fail(m), + }; + if !entry.file { + return fail(NOT_REGULAR); + } + if entry.len > MAX_FILE_BYTES as u64 { + return fail(TOO_LARGE); + } + if self.bytes.saturating_add(entry.len as usize) > MAX_RUN_BYTES { + return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); + } + let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok((_, bytes)) => bytes, + Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), + Err(ScriptRead::Missing) => return fail(NOT_FOUND), + Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), + Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), + }; + if self.bytes.saturating_add(bytes.len()) > MAX_RUN_BYTES { + return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); + } + self.bytes += bytes.len(); + let file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + while id == 0 || self.open.contains_key(&id) { + id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + } + self.open.insert(id, file); + Ok(id) + } +} + +/// Whether paths are read as Windows reads them. +const WINDOWS: bool = cfg!(windows); + +/// Does `path` have more than [`MAX_PATH_CHARS`] characters? +fn too_long(path: &str) -> bool { + path.len() > MAX_PATH_CHARS && path.chars().nth(MAX_PATH_CHARS).is_some() +} + +/// The home folder, as the environment gives it. +fn home_folder() -> String { + let var = if WINDOWS { "USERPROFILE" } else { "HOME" }; + std::env::var(var).unwrap_or_else(|_| if WINDOWS { r"C:\".to_string() } else { "/".to_string() }) +} + +/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none. +/// On the web every one is `null`, and no platform folder is looked up. +fn locations(home: &str) -> Data { + if cfg!(target_arch = "wasm32") { + return Data::Object(PLACES.iter().map(|k| (k.to_string(), Data::Null)).collect()); + } + let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); + let join = |a: &str, b: &str| Path::new(a).join(b).to_string_lossy().into_owned(); + let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_string_lossy().into_owned())); + let temp = temp_folder().to_string_lossy().into_owned(); + let (user_data, app_data, common, system, trash) = if WINDOWS { + (env("APPDATA"), env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) + } else if cfg!(target_os = "macos") { + ( + Some(join(home, "Library/Application Support")), + Some("/Library/Application Support".to_string()), + Some("/Library/Application Support".to_string()), + Some("/System".to_string()), + Some(join(home, ".Trash")), + ) + } else { + let data = env("XDG_DATA_HOME").unwrap_or_else(|| join(home, ".local/share")); + (Some(data.clone()), Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) + }; + let s = |v: Option<String>| v.map_or(Data::Null, Data::String); + let places = vec![ + ("appData", app_data), + ("appPackage", exe.clone()), + ("commonFiles", common), + ("desktop", Some(join(home, "Desktop"))), + ("myDocuments", Some(join(home, "Documents"))), + ("startup", exe), + ("system", system), + ("temp", Some(temp)), + ("trash", trash), + ("userData", user_data), + ]; + Data::Object(places.into_iter().map(|(k, v)| (k.to_string(), s(v))).collect()) +} + +/// The names [`locations`] gives. +const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; + +/// The folder for temporary files: the platform's, or on the web the root, where nothing is read. +fn temp_folder() -> std::path::PathBuf { + if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/") } else { std::env::temp_dir() } +} + +/// The start of an absolute path. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Root { + /// `/`. + Unix, + /// A Windows drive letter, in upper case. + Drive(char), + /// A Windows share: `\\host\share`. + Share(String, String), + /// A Windows `\\?\` or `\\.\` path, kept as given. + Device(String), +} + +/// An absolute path: its root and its names, with `.` and `..` resolved. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Pathname { + root: Root, + names: Vec<String>, +} + +impl Pathname { + fn root(windows: bool) -> Self { + Self { root: if windows { Root::Drive('C') } else { Root::Unix }, names: Vec::new() } + } + + /// The path `text` names, relative ones taken from `base` and `~` from `home`, with its URI + /// escapes decoded when `uri` is set. + fn parse(text: &str, base: &Pathname, home: &Pathname, windows: bool, uri: bool) -> Self { + let decoded = if uri { decode(text) } else { text.to_string() }; + let t = if windows { decoded.replace('\\', "/") } else { decoded }; + let (start, rest): (Pathname, &str) = if windows && (t.starts_with("//?/") || t.starts_with("//./")) { + return Self { root: Root::Device(t.replace('/', "\\")), names: Vec::new() }; + } else if let Some(r) = t.strip_prefix("//").filter(|_| windows) { + let mut parts = r.splitn(3, '/'); + let host = parts.next().unwrap_or_default().to_string(); + let share = parts.next().unwrap_or_default().to_string(); + (Self { root: Root::Share(host, share), names: Vec::new() }, parts.next().unwrap_or_default()) + } else if windows && t.len() >= 2 && t.as_bytes()[0].is_ascii_alphabetic() && t.as_bytes()[1] == b':' { + (Self { root: Root::Drive(t.as_bytes()[0].to_ascii_uppercase() as char), names: Vec::new() }, t.get(2..).unwrap_or_default()) + } else if let Some(r) = t.strip_prefix('/') { + let (first, after) = r.split_once('/').unwrap_or((r, "")); + if windows && first.len() == 1 && first.as_bytes()[0].is_ascii_alphabetic() { + (Self { root: Root::Drive(first.as_bytes()[0].to_ascii_uppercase() as char), names: Vec::new() }, after) + } else if windows { + let root = match &base.root { + Root::Drive(_) | Root::Share(..) => base.root.clone(), + _ => Root::Drive('C'), + }; + (Self { root, names: Vec::new() }, r) + } else { + (Self { root: Root::Unix, names: Vec::new() }, r) + } + } else if t == "~" || t.starts_with("~/") { + (home.clone(), t.get(1..).unwrap_or_default()) + } else { + (base.clone(), t.as_str()) + }; + let mut out = start; + for name in rest.split('/') { + match name { + "" | "." => {} + ".." => { + out.names.pop(); + } + n => out.names.push(n.to_string()), + } + } + out + } + + /// The path as the platform writes it. + fn fs(&self) -> String { + match &self.root { + Root::Unix => format!("/{}", self.names.join("/")), + Root::Drive(c) => format!("{c}:\\{}", self.names.join("\\")), + Root::Share(host, share) => self.names.iter().fold(format!(r"\\{host}\{share}"), |s, n| format!("{s}\\{n}")), + Root::Device(raw) => raw.clone(), + } + } + + /// The path in URI notation, each name escaped. + fn uri(&self) -> String { + let start = match &self.root { + Root::Unix => String::new(), + Root::Drive(c) => format!("/{}", c.to_ascii_lowercase()), + Root::Share(host, share) => format!("//{}/{}", encode(host), encode(share)), + Root::Device(raw) => return raw.replace('\\', "/"), + }; + let names: String = self.names.iter().map(|n| format!("/{}", encode(n))).collect(); + if start.is_empty() && names.is_empty() { "/".to_string() } else { start + &names } + } + + fn parent(&self) -> Option<Self> { + let mut p = self.clone(); + p.names.pop().map(|_| p) + } + + /// `self` relative to the folder `base`, in URI notation; the whole URI when they have different + /// roots. + fn relative_to(&self, base: &Pathname, windows: bool) -> String { + if self.root != base.root { + return self.uri(); + } + let same = |a: &String, b: &String| if windows { a.to_lowercase() == b.to_lowercase() } else { a == b }; + let common = self.names.iter().zip(&base.names).take_while(|(a, b)| same(a, b)).count(); + let mut parts: Vec<String> = vec!["..".to_string(); base.names.len() - common]; + parts.extend(self.names.iter().skip(common).map(|n| encode(n))); + if parts.is_empty() { ".".to_string() } else { parts.join("/") } + } + + /// The parts of `File` and `Folder` objects that come from the path alone. + fn data(&self) -> Data { + let s = |v: String| Data::String(v); + Data::Object(vec![ + ("fs".into(), s(self.fs())), + ("uri".into(), s(self.uri())), + ("name".into(), s(self.names.last().map(|n| encode(n)).unwrap_or_default())), + ("display".into(), s(self.names.last().cloned().unwrap_or_default())), + ("path".into(), s(self.parent().map(|p| p.uri()).unwrap_or_default())), + ("parent".into(), self.parent().map_or(Data::Null, |p| Data::String(p.fs()))), + ]) + } +} + +/// `s` with every character but letters, digits and `/-_.!~*'()` written as `%xx` escapes of its +/// UTF-8 bytes (RFC 2396). +fn encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || b"/-_.!~*'()".contains(&b) { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +/// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8. +fn decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = |c: u8| (c as char).to_digit(16); + match (b[i], b.get(i + 1).copied().and_then(hex), b.get(i + 2).copied().and_then(hex)) { + (b'%', Some(h), Some(l)) => { + out.push((h * 16 + l) as u8); + i += 3; + } + (c, ..) => { + out.push(c); + i += 1; + } + } + } + String::from_utf8(out).unwrap_or_else(|_| s.to_string()) +} + +/// A `getFiles` mask, where `*` stands for any run of characters and `?` for one, without regard +/// to case, read once for a whole listing. +struct Mask { + /// The mask in lower case, each run of `*` written as one. + chars: Vec<char>, + /// How many of its characters are not `*`: a name with fewer characters does not match. + fixed: usize, +} + +impl Mask { + fn new(mask: &str) -> Self { + let mut chars: Vec<char> = Vec::new(); + for c in mask.to_lowercase().chars() { + if !(c == '*' && chars.last() == Some(&'*')) { + chars.push(c); + } + } + let fixed = chars.iter().filter(|c| **c != '*').count(); + Self { chars, fixed } + } + + /// Does `name` match, taking a step from `steps` for each character compared? `None` when the + /// steps run out first. + fn matches(&self, name: &str, steps: &mut usize) -> Option<bool> { + let n: Vec<char> = name.to_lowercase().chars().collect(); + if n.len() < self.fixed { + return Some(false); + } + matched(&self.chars, &n, steps) + } +} + +/// Does `n` match the lower-case mask `m`? `None` when `steps` run out first. +fn matched(m: &[char], n: &[char], steps: &mut usize) -> Option<bool> { + let (mut i, mut j, mut star, mut mark) = (0usize, 0usize, None, 0usize); + while j < n.len() { + *steps = steps.checked_sub(1)?; + match m.get(i) { + Some('*') => { + star = Some(i); + mark = j; + i += 1; + } + Some(c) if *c == '?' || *c == n[j] => { + i += 1; + j += 1; + } + _ => match star { + Some(s) => { + i = s + 1; + mark += 1; + j = mark; + } + None => return Some(false), + }, + } + } + Some(m[i..].iter().all(|c| *c == '*')) +} + +/// A character encoding an opened file is read in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Encoding { + Utf8, + Ascii, + Binary, + Latin1, + Cp1252, + Utf16Le, + Utf16Be, +} + +/// The characters CP1252 gives bytes 0x80 to 0x9F; the five it leaves undefined stand for +/// themselves. +const CP1252_HIGH: [u16; 32] = [ + 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, 0x0090, 0x2018, + 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, +]; + +impl Encoding { + fn parse(name: &str) -> Option<Self> { + Some(match name.trim().to_ascii_uppercase().as_str() { + "UTF-8" | "UTF8" => Self::Utf8, + "ASCII" | "US-ASCII" => Self::Ascii, + "BINARY" => Self::Binary, + "ISO-8859-1" | "ISO8859-1" | "LATIN1" | "LATIN-1" => Self::Latin1, + "CP1252" | "WINDOWS-1252" => Self::Cp1252, + "UTF-16LE" | "UTF16LE" => Self::Utf16Le, + "UTF-16" | "UTF16" | "UTF-16BE" | "UTF16BE" | "UCS-2" => Self::Utf16Be, + _ => return None, + }) + } + + fn name(self) -> &'static str { + match self { + Self::Utf8 => "UTF-8", + Self::Ascii => "ASCII", + Self::Binary => "BINARY", + Self::Latin1 => "ISO-8859-1", + Self::Cp1252 => "CP1252", + Self::Utf16Le => "UTF-16LE", + Self::Utf16Be => "UTF-16BE", + } + } +} + +/// An opened file: its bytes, the byte position and the encoding it is read in. +struct Open { + bytes: Vec<u8>, + pos: usize, + encoding: Encoding, + name: String, +} + +impl Open { + /// `bytes` opened with the encoding `asked` (empty: none asked); `None` when `asked` is not an + /// encoding and the file has no byte order mark. + fn new(bytes: Vec<u8>, asked: &str) -> Option<Self> { + let (encoding, pos) = if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) { + (Encoding::Utf8, 3) + } else if bytes.starts_with(&[0xFF, 0xFE]) { + (Encoding::Utf16Le, 2) + } else if bytes.starts_with(&[0xFE, 0xFF]) { + (Encoding::Utf16Be, 2) + } else if !asked.is_empty() { + (Encoding::parse(asked)?, 0) + } else if std::str::from_utf8(&bytes).is_ok() { + (Encoding::Utf8, 0) + } else { + (Encoding::Cp1252, 0) + }; + Some(Self { bytes, pos, encoding, name: encoding.name().to_string() }) + } + + /// The character at byte `at` and its length in bytes; `Ok(None)` at the end, `Err` where the + /// encoding cannot decode it. + fn char_at(&self, at: usize) -> Result<Option<(char, usize)>, ()> { + let Some(&b) = self.bytes.get(at) else { return Ok(None) }; + let encoding = self.encoding; + let unit = |i: usize| -> Option<u16> { + let pair = self.bytes.get(i..i + 2)?; + Some(if encoding == Encoding::Utf16Le { u16::from_le_bytes([pair[0], pair[1]]) } else { u16::from_be_bytes([pair[0], pair[1]]) }) + }; + let c = match encoding { + Encoding::Ascii if b < 0x80 => (b as char, 1), + Encoding::Ascii => return Err(()), + Encoding::Binary | Encoding::Latin1 => (b as char, 1), + Encoding::Cp1252 => { + let code = if (0x80..0xA0).contains(&b) { u32::from(CP1252_HIGH[usize::from(b - 0x80)]) } else { u32::from(b) }; + (char::from_u32(code).ok_or(())?, 1) + } + Encoding::Utf8 => { + let len = match b { + 0x00..=0x7F => 1, + 0xC2..=0xDF => 2, + 0xE0..=0xEF => 3, + 0xF0..=0xF4 => 4, + _ => return Err(()), + }; + let s = self.bytes.get(at..at + len).and_then(|s| std::str::from_utf8(s).ok()).ok_or(())?; + (s.chars().next().ok_or(())?, len) + } + Encoding::Utf16Le | Encoding::Utf16Be => { + let first = unit(at).ok_or(())?; + if (0xD800..0xDC00).contains(&first) { + let second = unit(at + 2).filter(|u| (0xDC00..0xE000).contains(u)).ok_or(())?; + let code = 0x10000 + ((u32::from(first) - 0xD800) << 10) + (u32::from(second) - 0xDC00); + (char::from_u32(code).ok_or(())?, 4) + } else { + (char::from_u32(u32::from(first)).ok_or(())?, 2) + } + } + }; + Ok(Some(c)) + } + + /// Up to `max` characters from the position (all of them for `None`). + fn read(&mut self, max: Option<usize>) -> Result<String, ()> { + let (mut at, mut out) = (self.pos, String::new()); + let mut n = 0; + while max.is_none_or(|m| n < m) { + let Some((c, len)) = self.char_at(at)? else { break }; + out.push(c); + at += len; + n += 1; + } + self.pos = at; + Ok(out) + } + + /// The position after a line end that began with `c` and continues at `at` (CR, LF, CRLF or + /// LFCR). A character there that cannot be decoded is left for the next read. + fn past_line_end(&self, c: char, at: usize) -> usize { + let other = if c == '\r' { '\n' } else { '\r' }; + match self.char_at(at) { + Ok(Some((n, len))) if n == other => at + len, + _ => at, + } + } + + /// The characters up to the next line end, which is passed over. + fn read_line(&mut self) -> Result<String, ()> { + let (mut at, mut out) = (self.pos, String::new()); + while let Some((c, len)) = self.char_at(at)? { + at += len; + if c == '\r' || c == '\n' { + at = self.past_line_end(c, at); + break; + } + out.push(c); + } + self.pos = at; + Ok(out) + } + + /// The next character; a line end is one `"\n"`. + fn read_char(&mut self) -> Result<String, ()> { + let Some((c, len)) = self.char_at(self.pos)? else { return Ok(String::new()) }; + let mut at = self.pos + len; + let c = if c == '\r' || c == '\n' { + at = self.past_line_end(c, at); + '\n' + } else { + c + }; + self.pos = at; + Ok(c.to_string()) + } +} + +/// `{text}` for a read that worked, `{error}` for one that did not. +fn text_result(r: Result<String, ()>) -> Data { + match r { + Ok(t) => Data::Object(vec![("text".into(), Data::String(t))]), + Err(()) => error(UNDECODABLE), + } +} + +fn error(message: &str) -> Data { + Data::Object(vec![("error".into(), Data::String(message.to_string()))]) +} + +fn arg_text(a: &[Data], i: usize) -> String { + match a.get(i) { + Some(Data::String(s)) => s.clone(), + _ => String::new(), + } +} + +fn arg_number(a: &[Data], i: usize) -> Option<f64> { + match a.get(i) { + Some(Data::Number(n)) => Some(*n), + _ => None, + } +} + +fn millis(t: Option<std::time::SystemTime>) -> Data { + t.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(Data::Null, |d| Data::Number(d.as_millis() as f64)) +} + +/// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds. +fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| { + let h = super::current(&l)?; + bump(&h.counts.file_calls); + let r = f(&h, &a)?; + h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; + Ok(r) + })) +} + +fn handle(a: &[Data]) -> u32 { + arg_number(a, 0).filter(|n| n.is_finite() && *n >= 0.0 && *n <= f64::from(u32::MAX)).map_or(0, |n| n as u32) +} + +fn with_open(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data { + match host.disk.borrow_mut().open.get_mut(&handle(a)) { + Some(file) => f(file), + None => error(NOT_OPEN), + } +} + +/// The first two arguments as path text, refused with a `RangeError` when either is too long. +fn two_paths(a: &[Data]) -> Result<(String, String), HostError> { + let (path, base) = (arg_text(a, 0), arg_text(a, 1)); + if too_long(&path) || too_long(&base) { + return Err(HostError::Range(PATH_TOO_LONG.to_string())); + } + Ok((path, base)) +} + +fn parse(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let (path, base) = two_paths(a)?; + let platform = matches!(a.get(2), Some(Data::Bool(true))); + let disk = host.disk.borrow(); + Ok(disk.pathname(&path, &base, !platform).data()) +} + +/// The platform path `a[0]` relative to the platform path `a[1]`. +fn relative(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let (path, base) = two_paths(a)?; + let disk = host.disk.borrow(); + let base = disk.pathname(&base, &disk.start, false); + Ok(Data::String(disk.pathname(&path, &disk.start, false).relative_to(&base, WINDOWS))) +} + +fn stat(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(match host.disk.borrow().stat(&arg_text(a, 0)) { + Err(m) => error(m), + Ok(None) => Data::Object(vec![("exists".into(), Data::Bool(false))]), + Ok(Some(e)) => Data::Object(vec![ + ("exists".into(), Data::Bool(true)), + ("dir".into(), Data::Bool(e.dir)), + ("file".into(), Data::Bool(e.file)), + ("length".into(), Data::Number(e.len as f64)), + ("created".into(), millis(e.created)), + ("modified".into(), millis(e.modified)), + ("hidden".into(), Data::Bool(e.hidden)), + ("readonly".into(), Data::Bool(e.readonly)), + ("alias".into(), Data::Bool(e.link)), + ]), + }) +} + +fn open(host: &Host, a: &[Data]) -> Result<Data, HostError> { + match host.disk.borrow_mut().open_file(&arg_text(a, 0), &arg_text(a, 1)) { + Ok(id) => Ok(Data::Object(vec![("id".into(), Data::Number(f64::from(id)))])), + Err(HostError::Error(m)) => Ok(error(&m)), + Err(e) => Err(e), + } +} + +fn close(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::Bool(host.disk.borrow_mut().open.remove(&handle(a)).is_some())) +} + +fn read(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let max = arg_number(a, 1).filter(|n| *n >= 0.0).map(|n| n as usize); + Ok(with_open(host, a, |f| text_result(f.read(max)))) +} + +fn readln(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(with_open(host, a, |f| text_result(f.read_line()))) +} + +fn readch(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(with_open(host, a, |f| text_result(f.read_char()))) +} + +fn seek(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let (Some(pos), Some(mode)) = (arg_number(a, 1), arg_number(a, 2)) else { return Err(HostError::Type(BAD_SEEK.into())) }; + Ok(with_open(host, a, |f| { + let base = match mode as u8 { + 1 => f.pos as f64, + 2 => f.bytes.len() as f64, + _ => 0.0, + }; + let to = base + pos.trunc(); + if !(0.0..=f.bytes.len() as f64).contains(&to) { + return Data::Bool(false); + } + f.pos = to as usize; + Data::Bool(true) + })) +} + +const BAD_SEEK: &str = "File.seek: takes a position and a mode"; + +fn tell(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(with_open(host, a, |f| Data::Number(f.pos as f64))) +} + +fn eof(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.pos >= f.bytes.len()))) +} + +fn encoding(host: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(with_open(host, a, |f| Data::String(f.name.clone()))) +} + +fn set_encoding(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let name = arg_text(a, 1); + Ok(with_open(host, a, |f| match Encoding::parse(&name) { + Some(e) => { + f.encoding = e; + f.name = e.name().to_string(); + Data::Object(vec![]) + } + None => error(UNDECODABLE), + })) +} + +fn list(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let disk = host.disk.borrow(); + let path = arg_text(a, 0); + let mask = Mask::new(&arg_text(a, 1)); + let checked = match disk.checked(&path) { + Ok(p) => p, + Err(m) => return Ok(error(m)), + }; + let steps = std::cell::Cell::new(MAX_MASK_STEPS); + let spent = std::cell::Cell::new(false); + let keep = |name: &str| { + let mut left = steps.get(); + let kept = mask.matches(name, &mut left); + steps.set(left); + spent.set(spent.get() || kept.is_none()); + kept.unwrap_or(false) + }; + let listed = disk.scope.list(checked, MAX_ENTRIES, keep); + if spent.get() { + return Ok(error(MASK_TOO_COSTLY)); + } + let found = match listed { + Ok(found) => found, + Err(ScriptRead::TooLarge) => return Ok(error(LISTING_TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), + }; + let entries = found + .into_iter() + .map(|(name, dir)| { + let fs = Path::new(&path).join(&name).to_string_lossy().into_owned(); + Data::Object(vec![("fs".into(), Data::String(fs)), ("dir".into(), Data::Bool(dir))]) + }) + .collect(); + Ok(Data::Object(vec![("entries".into(), Data::Array(entries))])) +} + +fn resolve(host: &Host, a: &[Data]) -> Result<Data, HostError> { + let disk = host.disk.borrow(); + let path = arg_text(a, 0); + let target = match disk.stat(&path) { + Err(m) => return Ok(error(m)), + Ok(Some(e)) if e.link => disk.checked(&path).ok().and_then(|p| disk.scope.locate(p).ok()), + Ok(_) => None, + }; + Ok(match target { + Some(real) => { + let dir = real.is_dir(); + let fs = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned(); + Data::Object(vec![("fs".into(), Data::String(fs)), ("dir".into(), Data::Bool(dir))]) + } + None => Data::Object(vec![("fs".into(), Data::Null)]), + }) +} + +fn execute(host: &Host, _: &[Data]) -> Result<Data, HostError> { + bump(&host.counts.file_executes); + Ok(error(NO_EXECUTE)) +} + +fn temp_name(host: &Host, _: &[Data]) -> Result<Data, HostError> { + let mut disk = host.disk.borrow_mut(); + disk.temps += 1; + let name = format!("vc{:05}.tmp", disk.temps); + Ok(Data::String(temp_folder().join(name).to_string_lossy().into_owned())) +} + +fn locations_of(host: &Host, _: &[Data]) -> Result<Data, HostError> { + Ok(locations(&host.disk.borrow().home)) +} + +fn encode_text(_: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::String(encode(&arg_text(a, 0)))) +} + +fn decode_text(_: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::String(decode(&arg_text(a, 0)))) +} + +fn encoding_available(_: &Host, a: &[Data]) -> Result<Data, HostError> { + Ok(Data::Bool(Encoding::parse(&arg_text(a, 0)).is_some())) +} + +/// The folder `Folder.current` starts at in the run `host` serves: the script's own folder. +fn start_folder(host: &Host, _: &[Data]) -> Result<Data, HostError> { + let disk = host.disk.borrow(); + Ok(Data::String(disk.pathname(&disk.start, &disk.start, false).fs())) +} + +/// Adds `File` and `Folder` to the realm, their host functions acting for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + let unchecked = |f: fn(&Host, &[Data]) -> Result<Data, HostError>| { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| { + let h = super::current(&l)?; + f(&h, &a) + })) + }; + let value = |s: &str| HostItem::Value(Data::String(s.to_string())); + let text = HostItem::Object(vec![ + ("notOpen".into(), value(NOT_OPEN)), + ("noWrites".into(), value(NO_WRITES)), + ("noPicker".into(), value(NO_PICKER)), + ("badMode".into(), value(BAD_MODE)), + ]); + let system = if WINDOWS { + "Windows" + } else if cfg!(target_os = "macos") { + "Macintosh" + } else { + "Unix" + }; + let items = vec![ + ("text".into(), text), + ("system".into(), value(system)), + ("lineFeed".into(), value(if WINDOWS { "Windows" } else { "Unix" })), + ("current".into(), unchecked(start_folder)), + ("locations".into(), call(link, locations_of)), + ("encode".into(), call(link, encode_text)), + ("decode".into(), call(link, decode_text)), + ("encodingAvailable".into(), call(link, encoding_available)), + ("parse".into(), call(link, parse)), + ("relative".into(), call(link, relative)), + ("tempName".into(), call(link, temp_name)), + ("stat".into(), call(link, stat)), + ("open".into(), call(link, open)), + ("close".into(), call(link, close)), + ("read".into(), call(link, read)), + ("readln".into(), call(link, readln)), + ("readch".into(), call(link, readch)), + ("seek".into(), call(link, seek)), + ("tell".into(), call(link, tell)), + ("eof".into(), call(link, eof)), + ("encoding".into(), call(link, encoding)), + ("setEncoding".into(), call(link, set_encoding)), + ("list".into(), call(link, list)), + ("resolve".into(), call(link, resolve)), + ("execute".into(), call(link, execute)), + ]; + realm.define_file_classes(items) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(text: &str, base: &str, windows: bool) -> Pathname { + let root = Pathname::root(windows); + let home = Pathname::parse(if windows { r"C:\Users\me" } else { "/home/me" }, &root, &root, windows, false); + let base = Pathname::parse(base, &home, &home, windows, false); + Pathname::parse(text, &base, &home, windows, true) + } + + #[test] + fn windows_paths_take_both_separators_drives_and_uri_names() { + let f = p(r"C:\art\one two.txt", r"C:\work", true); + assert_eq!((f.fs(), f.uri()), (r"C:\art\one two.txt".to_string(), "/c/art/one%20two.txt".to_string())); + assert_eq!(p("/d/x/y.txt", r"C:\work", true).fs(), r"D:\x\y.txt"); + assert_eq!(p("c:/a/./b/../c", r"C:\work", true).fs(), r"C:\a\c"); + assert_eq!(p("sub/f.txt", r"C:\work", true).fs(), r"C:\work\sub\f.txt"); + assert_eq!(p("~/notes.txt", r"C:\work", true).fs(), r"C:\Users\me\notes.txt"); + assert_eq!(p(r"\\host\share\x.txt", r"C:\work", true).fs(), r"\\host\share\x.txt"); + assert_eq!(p(r"\\?\C:\x.txt", r"C:\work", true).root, Root::Device(r"\\?\C:\x.txt".into())); + assert_eq!(p("caf%C3%A9.txt", r"C:\w", true).fs(), "C:\\w\\caf\u{e9}.txt"); + assert_eq!(p("..\\..\\..\\..", r"C:\w", true).fs(), r"C:\"); + assert_eq!(p("C:", r"D:\w", true).uri(), "/c"); + } + + #[test] + fn unix_paths_keep_backslashes_in_names() { + assert_eq!(p(r"a\b.txt", "/work", false).fs(), r"/work/a\b.txt"); + assert_eq!(p("/x/../y", "/work", false).fs(), "/y"); + assert_eq!(p("~", "/work", false).fs(), "/home/me"); + assert_eq!(p("/", "/work", false).uri(), "/"); + } + + #[test] + fn relative_uris_climb_to_the_common_folder() { + let base = p("/a/b", "/", false); + assert_eq!(p("/a/b/c d.txt", "/", false).relative_to(&base, false), "c%20d.txt"); + assert_eq!(p("/a/x.txt", "/", false).relative_to(&base, false), "../x.txt"); + assert_eq!(p("/a/b", "/", false).relative_to(&base, false), "."); + assert_eq!(p("D:/x", "C:/", true).relative_to(&p("C:/a", "C:/", true), true), "/d/x"); + } + + #[test] + fn uri_escapes_are_utf8_both_ways() { + assert_eq!(encode("caf\u{e9} 1"), "caf%C3%A9%201"); + assert_eq!(encode("a-_.!~*'()/b"), "a-_.!~*'()/b"); + assert_eq!(decode("caf%C3%A9%20x"), "caf\u{e9} x"); + assert_eq!(decode("100%"), "100%"); + assert_eq!(decode("%E9"), "%E9", "a lone Latin-1 escape is not UTF-8"); + } + + #[test] + fn masks_match_stars_and_question_marks_without_case() { + let matches = |mask: &str, name: &str| Mask::new(mask).matches(name, &mut { usize::MAX }) == Some(true); + assert!(matches("*.JSX", "a.jsx")); + assert!(matches("a?c*", "abcdef")); + assert!(!matches("*.txt", "a.jsx")); + assert!(matches("*", "")); + assert!(matches("*a*b", "xaxxb")); + assert!(matches("a***b", "ab")); + assert!(!matches("?", "")); + } + + #[test] + fn masks_stop_when_their_steps_run_out() { + let mask = Mask::new(&format!("*{}b", "a".repeat(100))); + let name = "a".repeat(200); + let mut steps = 1000; + assert_eq!(mask.matches(&name, &mut steps), None); + assert_eq!(steps, 0); + let mut steps = 1000; + assert_eq!(Mask::new("*.jsx").matches("a.jsx", &mut steps), Some(true)); + assert!(steps > 990); + } + + #[test] + fn decoding_counts_characters_and_takes_four_line_ends() { + let mut f = Open::new(b"\xEF\xBB\xBFa\xC3\xA9\r\nb\n\rc\rd\ne".to_vec(), "").unwrap(); + assert_eq!((f.name.as_str(), f.pos), ("UTF-8", 3), "the byte order mark is passed over"); + assert_eq!(f.read(Some(2)).unwrap(), "a\u{e9}"); + assert_eq!(f.pos, 6, "two characters, three bytes"); + assert_eq!(f.read_line().unwrap(), "", "CRLF is one line end"); + assert_eq!(f.read_line().unwrap(), "b", "LFCR is one line end"); + assert_eq!(f.read_line().unwrap(), "c"); + assert_eq!(f.read_char().unwrap(), "d"); + assert_eq!(f.read_char().unwrap(), "\n"); + assert_eq!(f.read(None).unwrap(), "e"); + assert_eq!(f.read_char().unwrap(), ""); + let mut b = Open::new(vec![0xE8, 0x41], "BINARY").unwrap(); + assert_eq!(b.read(None).unwrap(), "\u{e8}A"); + let mut a = Open::new(vec![0x41, 0xE8], "ascii").unwrap(); + assert!(a.read(None).is_err()); + assert_eq!(a.pos, 0, "a failed read leaves the position"); + let mut c = Open::new(vec![0x80, 0xE9], "").unwrap(); + assert_eq!(c.name, "CP1252"); + assert_eq!(c.read(None).unwrap(), "\u{20ac}\u{e9}"); + let mut u = Open::new(vec![0xFF, 0xFE, 0x3D, 0xD8, 0x00, 0xDE, 0x41, 0x00], "").unwrap(); + assert_eq!(u.name, "UTF-16LE"); + assert_eq!(u.read(None).unwrap(), "\u{1f600}A"); + assert!(Open::new(b"x".to_vec(), "KLINGON").is_none()); + let mut l = Open::new(vec![b'a', b'\n', 0xE8, b'\r', 0xE8], "ASCII").unwrap(); + assert_eq!(l.read_line().unwrap(), "a", "a line end before a byte ASCII cannot read still ends the line"); + assert!(l.read_line().is_err()); + assert_eq!(l.pos, 2); + l.pos = 3; + assert_eq!(l.read_char().unwrap(), "\n"); + assert_eq!(l.pos, 4); + } +} diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 70bfeac56a..4ec68dbbde 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -16,8 +16,13 @@ //! the `JSINCLUDE` environment variable. A later `#includepath` replaces the list. //! - Files are read through the script's [`ScriptScope`]: a refused path ends the run, except a //! `JSINCLUDE` folder outside the scope, which is passed over. -//! - `#target` takes any value and changes nothing. `#targetengine` and `#engine` are refused as -//! unsupported, and any other `#name` as unknown; `//@name` with another name stays a comment. +//! - `#target` takes any value and changes nothing. `#engine` is refused as unsupported, and any +//! other `#name` as unknown; `//@name` with another name stays a comment. +//! - `#targetengine name` names the engine the script runs in ([`Expanded::engine`]). Only the +//! script itself may have one, at most once, and only before its first code or `#include` line: +//! blanks, comments and the other preprocessor lines may come before it. The name is an unquoted +//! name of ASCII letters, digits and `_` that does not start with a digit, or a quoted one of 1 to +//! [`MAX_ENGINE_NAME_BYTES`] bytes without control characters, compared as written. //! - The last `#strict on` or `#strict off` of the script and the files it includes sets the checks //! for the whole run; without one they are off. A write to a property that has only a getter is //! checked as a read-only one, the objects that take no new properties are those that are not @@ -50,6 +55,8 @@ pub const MAX_TOTAL_BYTES: usize = 32 << 20; pub const MAX_PROBES: usize = 1024; /// The longest value a preprocessor line may have, in bytes. const MAX_VALUE_BYTES: usize = 4096; +/// The longest name `#targetengine` may give, in bytes of UTF-8. +pub const MAX_ENGINE_NAME_BYTES: usize = 64; /// Where the lines of an expanded source came from: file 0 is the file expanded, the others the /// files it included. @@ -81,6 +88,13 @@ impl SourceMap { let name = self.files.get(seg.file).cloned().unwrap_or_else(|| Arc::from("")); (seg.file, name, seg.line.saturating_add(line - seg.out_line), column) } + + /// The memory the map holds, in bytes: its lists and its file names, each name counted in full + /// even when another map shares it. + pub(crate) fn bytes(&self) -> usize { + let names: usize = self.files.iter().map(|f| f.len() + 2 * size_of::<usize>()).sum(); + self.files.capacity() * size_of::<Arc<str>>() + self.segments.capacity() * size_of::<Segment>() + names + } } /// How a preprocessor failure ends the run. @@ -107,12 +121,78 @@ pub(crate) struct Failure { } /// A source with its preprocessor lines read: the text to run, where its lines came from, the -/// name its `#script` line gave, and what its last `#strict` line set (`None` without one). +/// name its `#script` line gave, what its last `#strict` line set (`None` without one), and the +/// engine its `#targetengine` line named, with that line's line and column. pub(crate) struct Expanded { pub source: String, pub map: SourceMap, pub name: Option<String>, pub strict: Option<bool>, + pub engine: Option<(String, u32, u32)>, +} + +/// What the preprocessor lines of a file have named so far: its `#script` name and its engine, and +/// whether code or an `#include` line has come before. +#[derive(Default)] +struct Named { + name: Option<String>, + engine: Option<(String, u32, u32)>, + code_seen: bool, +} + +/// Are `units` only blanks and comments? +fn only_blanks_and_comments(units: &[u16]) -> bool { + let mut i = 0; + while let Some(&u) = units.get(i) { + match u { + 0x2F if units.get(i + 1) == Some(&0x2F) => { + while units.get(i).is_some_and(|&c| !matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029)) { + i += 1; + } + } + 0x2F if units.get(i + 1) == Some(&0x2A) => { + let Some(end) = units.get(i + 2..).and_then(|rest| rest.windows(2).position(|w| w == [0x2A, 0x2F])) else { return false }; + i += end + 4; + } + 0xFEFF => i += 1, + u if char::from_u32(u32::from(u)).is_some_and(char::is_whitespace) => i += 1, + _ => return false, + } + } + true +} + +/// The engine name of a `#targetengine` line's value `value` (as written, quotes included), or what +/// is wrong with it. +fn engine_name(value: &str) -> Result<String, &'static str> { + let name = match value.chars().next() { + None => return Err("needs a name"), + Some(q @ ('"' | '\'')) => { + let inner = value.get(1..).and_then(|v| v.strip_suffix(q)).ok_or("needs a closing quote after the name")?; + if inner.contains(q) { + return Err("takes one name"); + } + if inner.chars().any(char::is_control) { + return Err("needs a name without control characters"); + } + inner + } + _ => { + let mut chars = value.chars(); + let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_'); + if !first_ok || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') { + return Err("needs a name of letters, digits and _, or a quoted name"); + } + value + } + }; + if name.is_empty() { + return Err("needs a name"); + } + if name.len() > MAX_ENGINE_NAME_BYTES { + return Err("needs a name of at most 64 bytes"); + } + Ok(name.to_string()) } /// A file being run: its name for people and the folder its relative paths start from (none for a @@ -251,6 +331,11 @@ impl Files { self.include_path.join(";") } + /// The folders the run's own files are read from. + pub(crate) fn scope(&self) -> &ScriptScope { + &self.scope + } + /// The script's own text, `text`, with its preprocessor lines read. pub(crate) fn expand_script(&mut self, text: &str) -> Result<Expanded, Failure> { self.bytes = self.bytes.saturating_add(text.len()); @@ -342,8 +427,8 @@ impl Files { /// its `#script` line names the run. fn expand(&mut self, shown: Arc<str>, dir: Option<PathBuf>, text: &str, script: bool) -> Result<Expanded, Failure> { let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default(), strict: None }; - let mut name = None; - self.file(&mut out, shown, dir.as_deref(), text, script, &mut name)?; + let mut named = Named::default(); + self.file(&mut out, shown, dir.as_deref(), text, script, &mut named)?; let source = String::from_utf16(&out.units).map_err(|_| Failure { kind: FailKind::Syntax, message: "the script is not valid text".into(), @@ -352,20 +437,12 @@ impl Files { line: 0, column: 0, })?; - Ok(Expanded { source, map: out.map, name, strict: out.strict }) + Ok(Expanded { source, map: out.map, name: named.name, strict: out.strict, engine: named.engine }) } /// Adds file `shown` (in folder `dir`, with text `text`) to `out`, its included files in place /// of their lines. - fn file( - &mut self, - out: &mut Out, - shown: Arc<str>, - dir: Option<&Path>, - text: &str, - script: bool, - name: &mut Option<String>, - ) -> Result<(), Failure> { + fn file(&mut self, out: &mut Out, shown: Arc<str>, dir: Option<&Path>, text: &str, script: bool, named: &mut Named) -> Result<(), Failure> { let index = out.map.files.len(); out.map.files.push(shown.clone()); let units: Vec<u16> = text.encode_utf16().collect(); @@ -385,7 +462,11 @@ impl Files { units.get(..start).and_then(|u| u.iter().rposition(|&c| matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029))).map_or(0, |i| i + 1); let column = u32::try_from(start - line_start + 1).unwrap_or(u32::MAX); let at = |kind, message: String| fail(kind, message, d.line, column); - out.emit(units.get(cursor..start).unwrap_or_default()); + let before = units.get(cursor..start).unwrap_or_default(); + if !named.code_seen && !only_blanks_and_comments(before) { + named.code_seen = true; + } + out.emit(before); cursor = end; let label = format!("{}{}", d.form, d.name); if d.value.len() > MAX_VALUE_BYTES { @@ -397,11 +478,12 @@ impl Files { if value.is_empty() { return Err(at(FailKind::Syntax, format!("{label} needs a file name"))); } + named.code_seen = true; let (real, bytes) = self.open(value, dir, true).map_err(|(kind, message)| at(kind, message))?; let included = self.admit(&real, bytes, value).map_err(|(kind, message)| at(kind, message))?; self.chain.push(real.clone()); self.levels += 1; - let r = self.file(out, display(&real), folder_of(&real).as_deref(), &included, false, name); + let r = self.file(out, display(&real), folder_of(&real).as_deref(), &included, false, named); self.chain.pop(); self.levels -= 1; r?; @@ -416,7 +498,7 @@ impl Files { return Err(at(FailKind::Syntax, format!("{label} needs a name"))); } if script && index == 0 { - *name = Some(value.to_string()); + named.name = Some(value.to_string()); } } Some(DirectiveName::Target) => { @@ -429,7 +511,19 @@ impl Files { "on" => out.strict = Some(true), _ => return Err(at(FailKind::Syntax, format!("{label} takes on or off"))), }, - Some(DirectiveName::TargetEngine) => return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))), + Some(DirectiveName::TargetEngine) => { + if !script || index > 0 { + return Err(at(FailKind::Syntax, format!("{label} may only be in the script itself, not in a file it runs"))); + } + if named.engine.is_some() { + return Err(at(FailKind::Syntax, format!("the script has more than one {label} line"))); + } + if named.code_seen { + return Err(at(FailKind::Syntax, format!("{label} must come before the script's code and #include lines"))); + } + let engine = engine_name(&d.value).map_err(|why| at(FailKind::Syntax, format!("{label} {why}")))?; + named.engine = Some((engine, d.line, column)); + } None if d.name.eq_ignore_ascii_case("engine") => { return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))); } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 213cff53fd..0821a11e71 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -36,6 +36,15 @@ //! //! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the //! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`. +//! +//! `File` and `Folder` read files inside the script's own folder ([`files`]). +//! +//! A script with `#targetengine name` runs in that named engine, which the session keeps with the +//! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each +//! (VectorCraft's own limits). A script without the line, or with `main`, gets a new realm for each +//! run. An engine keeps no document and no run: its host functions reach the run through a link +//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the +//! documents back and keeps the engine's globals; an internal error drops the engine. pub mod console; pub mod dialogs; @@ -58,6 +67,7 @@ use crate::{ Clipboard, DocState, DrawMode, EngineError, Journal, NodeId, PaintDefaults, Result, Session, cmd, command_specs, guard, waits_for_tool_edit, }; +pub mod files; pub mod folder; /// The most bytes of source a run takes, as a file or as `source`. @@ -193,6 +203,207 @@ fn with_job<T>(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option<T> { JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.id).map(f)) } +/// The most named engines (`#targetengine`) a session keeps. +pub const MAX_ENGINES: usize = 8; +/// The heap a named engine may use, with what it keeps between runs. +pub const ENGINE_HEAP_BYTES: usize = 64 << 20; +/// The engine of a script without `#targetengine`, which `#targetengine main` also names: a new +/// one for each run, never kept. +pub const MAIN_ENGINE: &str = "main"; + +/// The run a script's host functions act for. A named engine keeps its functions between runs, so +/// they find the run through this link, which holds the run's [`Host`] only while the run goes on. +type Link = Rc<RefCell<Option<Rc<Host>>>>; + +/// The host of the run `link` holds, or an error when no run holds it. +fn current(link: &Link) -> std::result::Result<Rc<Host>, HostError> { + link.borrow().clone().ok_or_else(|| HostError::Error(NO_RUN.to_string())) +} + +/// A named engine: its interpreter, with the globals its runs left (`None` while a run has it), +/// the link its host functions use, its heap after its last run, and the source maps of the code +/// its earlier runs compiled. +struct Engine { + name: String, + realm: Option<Realm>, + link: Link, + heap: usize, + maps: Rc<RefCell<KeptMaps>>, +} + +/// A named engine taken for a run: its realm (`None` for an engine made now), its link and its +/// kept source maps. +type TakenEngine = (Option<Realm>, Link, Rc<RefCell<KeptMaps>>); + +/// The most bytes of source maps ([`include::SourceMap::bytes`]) a named engine keeps from its +/// earlier runs. +pub const KEPT_MAP_BYTES: usize = 8 << 20; + +/// A source map an engine kept from an earlier run: the realm's tag for the source +/// ([`Realm::error_tag`]), the map, and for the run's own script, that run's name, which stands for +/// a script given as text. +struct KeptMap { + tag: u32, + map: include::SourceMap, + script: Option<Arc<str>>, + bytes: usize, +} + +/// The source maps a named engine kept from its earlier runs, by tag, oldest first, in at most +/// [`KEPT_MAP_BYTES`]: the oldest go first to make room, and a map larger than that is not kept. +#[derive(Default)] +struct KeptMaps { + maps: std::collections::VecDeque<KeptMap>, + bytes: usize, +} + +impl KeptMaps { + fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option<Arc<str>>) { + let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len()); + let limit = kept_map_bytes(); + if bytes > limit || self.maps.back().is_some_and(|m| m.tag >= tag) { + return; + } + while self.bytes + bytes > limit { + let Some(old) = self.maps.pop_front() else { break }; + self.bytes -= old.bytes; + } + self.bytes += bytes; + self.maps.push_back(KeptMap { tag, map, script, bytes }); + } + + fn get(&self, tag: u32) -> Option<&KeptMap> { + self.maps.binary_search_by_key(&tag, |m| m.tag).ok().and_then(|i| self.maps.get(i)) + } +} + +/// The bytes of source maps a named engine keeps. +fn kept_map_bytes() -> usize { + #[cfg(test)] + if let Some(n) = TEST_KEPT_MAP_BYTES.with(Cell::get) { + return n; + } + KEPT_MAP_BYTES +} + +/// The named engines of one thread's sessions, by their key, each in the order they were made. +struct ThreadEngines { + thread: std::thread::ThreadId, + by_key: HashMap<u64, Vec<Engine>>, +} + +impl ThreadEngines { + fn new() -> Self { + let thread = std::thread::current().id(); + released().insert(thread, Vec::new()); + Self { thread, by_key: HashMap::new() } + } +} + +impl Drop for ThreadEngines { + fn drop(&mut self) { + released().remove(&self.thread); + } +} + +thread_local! { + /// The named engines of this thread's sessions. They are held here, and not in their session, + /// because they hold interpreters, which stay on this thread. + static ENGINES: RefCell<ThreadEngines> = RefCell::new(ThreadEngines::new()); +} + +static NEXT_ENGINES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// For each thread that holds engines, the keys of the ones sessions let go of on another thread. +/// The thread drops them the next time it uses its engines; a thread that has ended has no entry, +/// since its engines ended with it. +static RELEASED_ENGINES: std::sync::LazyLock<std::sync::Mutex<HashMap<std::thread::ThreadId, Vec<u64>>>> = + std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new())); + +fn released() -> std::sync::MutexGuard<'static, HashMap<std::thread::ThreadId, Vec<u64>>> { + RELEASED_ENGINES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Lets the engines with key `id` go, for `thread`, which holds them, to drop. +fn release_engines(thread: std::thread::ThreadId, id: u64) { + if let Some(ids) = released().get_mut(&thread) { + ids.push(id); + } +} + +/// A session's hold on its named engines: their key, and the thread that holds them once a run +/// made one. Dropping it drops them. The engines stay on that thread, so a session used on another +/// thread lets them go and starts there with none. +#[derive(Debug)] +pub struct EnginesKey(std::sync::Mutex<(u64, Option<std::thread::ThreadId>)>); + +impl EnginesKey { + pub(crate) fn new() -> Self { + Self(std::sync::Mutex::new((NEXT_ENGINES.fetch_add(1, std::sync::atomic::Ordering::Relaxed), None))) + } + + /// The key of the session's engines on this thread. + fn here(&self) -> u64 { + let mut key = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let thread = std::thread::current().id(); + match key.1 { + Some(t) if t != thread => { + release_engines(t, key.0); + *key = (NEXT_ENGINES.fetch_add(1, std::sync::atomic::Ordering::Relaxed), Some(thread)); + } + Some(_) => {} + None => key.1 = Some(thread), + } + key.0 + } +} + +impl Drop for EnginesKey { + fn drop(&mut self) { + let (id, thread) = *self.0.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(t) = thread.filter(|t| *t != std::thread::current().id()) { + release_engines(t, id); + return; + } + let gone = ENGINES.try_with(|engines| engines.try_borrow_mut().ok().and_then(|mut e| e.by_key.remove(&id))); + drop(gone); + } +} + +fn with_engines<T>(key: &EnginesKey, f: impl FnOnce(&mut Vec<Engine>) -> T) -> T { + let id = key.here(); + ENGINES.with(|engines| { + let gone: Vec<Vec<Engine>> = { + let mut here = engines.borrow_mut(); + let ids = released().get_mut(&here.thread).map(std::mem::take).unwrap_or_default(); + ids.iter().filter_map(|id| here.by_key.remove(id)).collect() + }; + drop(gone); + f(engines.borrow_mut().by_key.entry(id).or_default()) + }) +} + +/// Tests: the named engines this thread holds, for every session. +#[cfg(test)] +pub(crate) fn engines_on_this_thread() -> usize { + ENGINES.with(|engines| engines.borrow().by_key.values().map(Vec::len).sum()) +} + +/// Tests: whether engines can still be let go for `thread`, which holds an entry while it lives. +#[cfg(test)] +pub(crate) fn releases_kept_for(thread: std::thread::ThreadId) -> bool { + released().contains_key(&thread) +} + +/// The heap of a named engine. +fn engine_heap() -> usize { + #[cfg(test)] + if let Some(n) = TEST_ENGINE_HEAP.with(Cell::get) { + return n; + } + ENGINE_HEAP_BYTES +} + /// The state a script changes that a rollback puts back. struct World { docs: Vec<DocState>, @@ -502,6 +713,8 @@ struct Host { dialogs: dialogs::Dialogs, /// The files the run reads: its includes and `$.evalFile`'s. files: RefCell<include::Files>, + /// What `File` and `Folder` have open and have read. + disk: RefCell<files::Disk>, /// Where the lines of the script's expanded source came from. script_map: RefCell<include::SourceMap>, /// The same for each source `$.evalFile` gave, in order. @@ -509,6 +722,14 @@ struct Host { /// The file, line and column of each error `$.evalFile` raised for a file it could not run, in /// order: the error's mark ([`HostError::Marked`]) is its index. eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>, + /// The realm's tag for the script ([`Realm::script_tag`]) once the run has started it, and + /// [`vectorcraft_js::UNKNOWN_SOURCE`] before. + script_tag: Cell<u32>, + /// The run's name as its report gives it, which [`Host::name`] shortens for console lines. + report_name: Arc<str>, + /// The source maps the named engine of the run kept from its earlier runs; `None` for a run + /// without one. + kept_maps: Option<Rc<RefCell<KeptMaps>>>, /// When the run started, where the platform has a clock. started: Option<std::time::Instant>, /// The time since [`Host::started`] at which a `$.sleep` ends. @@ -517,6 +738,10 @@ struct Host { can_wait: Rc<Cell<bool>>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). eval_strict: Cell<Option<bool>>, + /// The values of `$` that belong to the run. + dollar: dollar::RunState, + /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. + args: RefCell<(Data, u64)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -527,6 +752,10 @@ struct Counts { command_list_reads: Cell<u64>, vc_log: Cell<u64>, console_writes: Cell<u64>, + /// Calls of `File` and `Folder` that reach the host ([`files`]). + file_calls: Cell<u64>, + /// `execute` calls, which open nothing. + file_executes: Cell<u64>, } impl Counts { @@ -537,6 +766,8 @@ impl Counts { "commandListReads": self.command_list_reads.get(), "vcLog": self.vc_log.get(), "consoleWrites": self.console_writes.get(), + "fileCalls": self.file_calls.get(), + "fileExecutes": self.file_executes.get(), }) } } @@ -574,6 +805,23 @@ pub(crate) fn slowest(times: &HashMap<&'static str, (u64, u128, u128)>) -> Vec<c } impl Host { + /// Gives the named engine of the run the source maps of the code the run compiled: its script + /// and each file `$.evalFile` gave. A run that never started its script compiled nothing. + fn keep_maps(&self) { + let (Some(kept), tag) = (&self.kept_maps, self.script_tag.get()) else { return }; + if tag == vectorcraft_js::UNKNOWN_SOURCE { + return; + } + let mut kept = kept.borrow_mut(); + kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone())); + for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() { + match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) { + Some(t) => kept.keep(t, map, None), + None => break, + } + } + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -693,6 +941,10 @@ impl Host { struct Job { realm: Realm, host: Rc<Host>, + /// The link the realm's host functions find `host` through. + link: Link, + /// The named engine the realm belongs to, which gets it back when the run ends. + engine: Option<String>, /// Between slices the working copy; during the last slice's commit the state before the run. world: World, /// The documents open when the run began, by [`DocState::uid`]. @@ -1005,10 +1257,11 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) { /// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file /// being run and `$.includePath` the `#includepath` list. Its other members are /// [`dollar::members`]. -fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> { +fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> { let writer = |end: bool| { - let h = host.clone(); + let l = link.clone(); HostItem::TextFunction(function(move |a| { + let h = current(&l)?; let text: String = a.iter().map(|d| if let Data::String(s) = d { s.as_str() } else { "" }).collect(); h.charge_call(text.len() as u64 + 2)?; bump(&h.counts.console_writes); @@ -1017,21 +1270,24 @@ fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vecto })) }; let getter = |read: fn(&include::Files) -> String| { - let h = host.clone(); + let l = link.clone(); HostItem::Getter(function(move |_| { + let h = current(&l)?; let text = read(&h.files.borrow()); h.charge_call(text.len() as u64 + 2)?; Ok(Data::String(text)) })) }; let eval_file = { - let h = host.clone(); - let end = host.clone(); - let strict = host.clone(); + let (l, end, strict) = (link.clone(), link.clone(), link.clone()); HostItem::Evaluator { - source: function(move |a| eval_file(&h, a)), - end: Rc::new(move || end.files.borrow_mut().end_eval()), - strict_writes: Rc::new(move || strict.eval_strict.get()), + source: function(move |a| eval_file(&*current(&l)?, a)), + end: Rc::new(move || { + if let Ok(h) = current(&end) { + h.files.borrow_mut().end_eval(); + } + }), + strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())), } }; let mut items = vec![ @@ -1041,7 +1297,7 @@ fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vecto ("fileName".into(), getter(include::Files::file_name)), ("includePath".into(), getter(include::Files::include_path)), ]; - items.extend(dollar::members(host, info, localization)); + items.extend(dollar::members(link, info, localization)); items } @@ -1088,32 +1344,46 @@ fn function(f: impl Fn(Vec<Data>) -> std::result::Result<Data, HostError> + 'sta Rc::new(f) } -fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> { +/// The `vc` object, made once for each realm: its members act for the run `link` holds when they +/// are called. +fn vc_object(link: &Link) -> Vec<(String, HostItem)> { + let args = { + let l = link.clone(); + function(move |_| { + let h = current(&l)?; + let (args, size) = &*h.args.borrow(); + h.charge_call(*size)?; + Ok(args.clone()) + }) + }; let run = { - let h = host.clone(); - function(move |a| vc_run(&h, a)) + let l = link.clone(); + function(move |a| vc_run(¤t(&l)?, a)) }; let document = { - let h = host.clone(); + let l = link.clone(); function(move |_| { + let h = current(&l)?; h.charge_call(64)?; bump(&h.counts.document_reads); vc_document(&h) }) }; let commands = { - let h = host.clone(); + let l = link.clone(); let list = Rc::new(vc_commands()); let size = data_size(&list); function(move |_| { + let h = current(&l)?; h.charge_call(size)?; bump(&h.counts.command_list_reads); Ok((*list).clone()) }) }; let log = { - let h = host.clone(); + let l = link.clone(); function(move |a| { + let h = current(&l)?; h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?; bump(&h.counts.vc_log); vc_log(&h, a) @@ -1125,7 +1395,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> { ("document".into(), HostItem::Getter(document)), ("commands".into(), HostItem::Getter(commands)), ("log".into(), HostItem::Function(log)), - ("args".into(), HostItem::Value(args)), + ("args".into(), HostItem::FrozenGetter(args)), ( "api".into(), HostItem::Object(vec![("version".into(), HostItem::Value(Data::String(API_VERSION.into()))), ("has".into(), HostItem::Function(has))]), @@ -1146,7 +1416,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `message`, with what to do about a failure that comes from a script written for another program. fn explained(kind: &RunErrorKind, message: &str) -> String { - const HOST_OBJECTS: &[&str] = &["app", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); if *kind == RunErrorKind::Thrown && names_host_object { @@ -1170,31 +1440,55 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) { (RunError { kind, message, line: f.line, column: f.column }, file) } -/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]) with host error mark `mark` -/// ([`Realm::error_mark`]), at the line and column of the file it is in, with that file's name -/// unless it is the script's own. -fn located(host: &Host, tag: u32, mark: Option<u32>, e: &RunError) -> (RunError, Option<Arc<str>>) { - let map = |m: &include::SourceMap, own: bool| { +/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, +/// with that file's name unless it is the run's own script. +fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<str>>) { + let map = |m: &include::SourceMap| { let (index, file, line, column) = m.locate(e.line, e.column); let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column }, (!own || index > 0).then_some(file)) + (RunError { kind: e.kind.clone(), message, line, column }, index, file) }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. - if let Some((file, line, column)) = mark.and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { + if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column }, Some(file)); } if e.line == 0 { return (e.clone(), None); } - match tag { - 0 => map(&host.script_map.borrow(), true), + // An error in code from a source whose map is not at hand, such as code that `eval` compiled, + // is given without a place. + let unplaced = || (RunError { kind: e.kind.clone(), message: e.message.clone(), line: 0, column: 0 }, None); + match realm.error_source() { + 0 => { + let (e, index, file) = map(&host.script_map.borrow()); + (e, (index > 0).then_some(file)) + } n if n != vectorcraft_js::UNKNOWN_SOURCE => match host.eval_maps.borrow().get(n as usize - 1) { - Some(m) => map(m, false), - None => (e.clone(), None), + Some(m) => { + let (e, _, file) = map(m); + (e, Some(file)) + } + None => unplaced(), }, - _ => (e.clone(), None), + // Code an earlier run of the named engine compiled, such as a function it defined, is at + // its place in that run's files: the run's script, a file it included, or a file + // `$.evalFile` gave. A script given as text is named by that run's name. + _ => { + let kept = host.kept_maps.as_ref().map(|k| k.borrow()); + match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + Some(kept) => { + let (e, index, file) = map(&kept.map); + let file = match &kept.script { + Some(name) if index == 0 && file.is_empty() => name.clone(), + _ => file, + }; + (e, Some(file)) + } + None => unplaced(), + } + } } } @@ -1214,6 +1508,100 @@ impl Session { self.script_key.is_some() } + /// The named engine of the running script. + fn running_engine(&self) -> Option<String> { + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.engine.clone())).flatten() + } + + /// The named engines (`#targetengine`) this session keeps, in the order they were made: each + /// one's name, its heap after its last run in bytes, and whether a run has it now. + pub fn script_engines(&self) -> Vec<(String, usize, bool)> { + with_engines(&self.script_engines, |engines| engines.iter().map(|e| (e.name.clone(), e.heap, e.realm.is_none())).collect()) + } + + /// Drops the named engine `name` and the globals its runs left; a later run that names it gets a + /// new one. + pub fn drop_script_engine(&mut self, name: &str) -> Result<()> { + if name == MAIN_ENGINE { + return Err(EngineError::Other(DROP_MAIN.to_string())); + } + if self.running_engine().as_deref() == Some(name) { + return Err(EngineError::Busy); + } + let gone = with_engines(&self.script_engines, |engines| { + let at = engines.iter().position(|e| e.name == name)?; + Some(engines.remove(at)) + }); + match gone { + Some(engine) => { + drop(engine); + Ok(()) + } + None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))), + } + } + + /// The realm of the named engine `name` for a run, with the link its host functions use and the + /// source maps it kept: the realm its last run left, or `None` for an engine made now. → the + /// kind and text of the failure when the engine cannot be had. + fn take_engine(&mut self, name: &str) -> std::result::Result<TakenEngine, (include::FailKind, String)> { + if cfg!(target_arch = "wasm32") { + return Err((include::FailKind::Error, NO_ENGINES_ON_WEB.to_string())); + } + with_engines(&self.script_engines, |engines| { + if let Some(e) = engines.iter_mut().find(|e| e.name == name) { + let realm = e.realm.take().ok_or((include::FailKind::Error, ENGINE_BUSY.to_string()))?; + return Ok((Some(realm), e.link.clone(), e.maps.clone())); + } + if engines.len() >= MAX_ENGINES { + return Err(( + include::FailKind::Limit, + format!("a session keeps at most {MAX_ENGINES} script engines; drop one with script.engine.drop"), + )); + } + let link: Link = Rc::new(RefCell::new(None)); + let maps = Rc::new(RefCell::new(KeptMaps::default())); + engines.push(Engine { name: name.to_string(), realm: None, link: link.clone(), heap: 0, maps: maps.clone() }); + Ok((None, link, maps)) + }) + } + + /// The end of a run in engine `engine` (`None` for a realm that is not kept): the link no longer + /// holds the run, and the engine keeps `realm`, with the source maps of the code the run + /// compiled, or is dropped without one. + fn return_engine(&self, engine: Option<&str>, link: &Link, realm: Option<Realm>) { + let host = link.borrow_mut().take(); + if let (Some(h), Some(_)) = (&host, &realm) { + h.keep_maps(); + } + drop(host); + let Some(name) = engine else { return }; + let mut realm = realm; + let heap = realm.as_mut().map(Realm::collect_garbage); + let gone = with_engines(&self.script_engines, |engines| { + let at = engines.iter().position(|e| e.name == name)?; + match (realm.take(), engines.get_mut(at)) { + (Some(r), Some(e)) => { + e.realm = Some(r); + e.heap = heap.unwrap_or(0); + None + } + _ => Some(engines.remove(at)), + } + }); + drop(gone); + drop(realm); + } + + /// The end of `job`: its engine gets its realm back, with a run that was stopped where it was + /// ended, unless the run ended with an internal error, which drops the engine. + fn end_job(&self, job: Job, internal: bool) { + let Job { mut realm, link, engine, host, .. } = job; + drop(host); + realm.end(); + self.return_engine(engine.as_deref(), &link, (!internal).then_some(realm)); + } + /// The flag that stops the script running in this session from any thread, at its next /// instruction. pub fn script_interrupt(&self) -> Interrupt { @@ -1326,6 +1714,13 @@ impl Session { let line = console::ConsoleLine { run: key.run, name: key.name.clone(), entry: console::Entry::End(ending) }; self.script_console.push(line, false); drop(key); + // The realm of the job's named engine went with the job, so the engine is dropped. + let lost: Vec<Engine> = with_engines(&self.script_engines, |engines| { + let (lost, kept) = std::mem::take(engines).into_iter().partition(|e| e.realm.is_none()); + *engines = kept; + lost + }); + drop(lost); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1363,10 +1758,40 @@ impl Session { Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(), _ => request.name, }; - let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() }; + // The engine named by `#targetengine`, other than `main`: its realm, kept from its last run, + // or none for an engine this run makes. + let named = match &expanded { + Ok(include::Expanded { engine: Some((engine, line, column)), .. }) if engine != MAIN_ENGINE => Some((engine.clone(), *line, *column)), + _ => None, + }; + let (expanded, kept) = match named { + None => (expanded, None), + Some((engine, line, column)) => match self.take_engine(&engine) { + Ok(kept) => (expanded, Some((engine, kept))), + Err((kind, message)) => { + let file = Arc::from(files.file_name()); + (Err(include::Failure { kind, message, index: 0, file, line, column }), None) + } + }, + }; + let heap_bytes = if kept.is_some() { engine_heap() } else { HEAP_BYTES }; + let limits = Limits { fuel: request.fuel, heap_bytes, ..Limits::default() }; + let (engine, realm, link, kept_maps) = match kept { + None => (None, None, Rc::new(RefCell::new(None)), None), + Some((engine, (realm, link, maps))) => (Some(engine), realm, link, Some(maps)), + }; + // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them + // from its first run, and they act for the run that calls them. + let fresh = realm.is_none(); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; let strict = options.strict; - let mut realm = Realm::with_options(options, limits); + let mut realm = match realm { + Some(mut realm) => { + realm.set_limits(limits); + realm + } + None => Realm::with_options(options, limits), + }; realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); self.script_runs += 1; @@ -1394,36 +1819,63 @@ impl Session { commands: RefCell::default(), run_nanos: Cell::new(0), dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers), + disk: RefCell::new(files::Disk::new(files.scope())), files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), eval_failures: RefCell::default(), + script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE), + report_name: Arc::from(name.as_str()), + kept_maps, started: clock(), wake_at: Cell::new(None), can_wait: realm.wait_flag(), eval_strict: Cell::new(None), + dollar: dollar::RunState::new(&request.locale), + args: RefCell::new((Data::Undefined, 0)), }); - let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) - .map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?; + *link.borrow_mut() = Some(host.clone()); + let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { + Ok(args) => args, + Err(place) => { + self.return_engine(engine.as_deref(), &link, (!fresh).then_some(realm)); + return Err(EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") }); + } + }; + let size = data_size(&args); + *host.args.borrow_mut() = (args, size); let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start }; self.script_console.push(line, false); - let info = dollar::RunInfo { locale: request.locale, strict }; + let engine_name = match &expanded { + Ok(include::Expanded { engine: Some((name, ..)), .. }) => Some(name.clone()), + _ => None, + }; + let info = dollar::RunInfo { strict, engine: engine_name }; let localization = realm.localization(); + dollar::start_run(&localization, &request.locale); let started = match expanded { Err(f) => Err(preprocessor_error(f)), Ok(expanded) => { *host.script_map.borrow_mut() = expanded.map; realm.set_strict_writes(expanded.strict == Some(true)); - realm - .add_script_extensions() - .and_then(|()| realm.define_host_object("vc", vc_object(&host, args))) - .and_then(|()| realm.define_host_object("$", dollar_object(&host, info, &localization))) - .and_then(|()| dialogs::install(&mut realm, &host)) - .and_then(|()| realm.start(&expanded.source)) - .map_err(|e| located(&host, realm.error_source(), realm.error_mark(), &e)) + (if fresh { realm.add_script_extensions() } else { Ok(()) }) + .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) + .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) + .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) + .and_then(|()| { + let r = realm.start(&expanded.source); + host.script_tag.set(realm.script_tag()); + r + }) + .map_err(|e| located(&host, &realm, &e)) } }; if let Err((e, file)) = started { + // An engine this run made is not kept: only a run that starts makes one. An internal + // error drops a kept one. + let keep = !fresh && e.kind != RunErrorKind::Internal; + self.return_engine(engine.as_deref(), &link, keep.then_some(realm)); let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); @@ -1432,7 +1884,7 @@ impl Session { } let scope = crate::file_access::ScopeHandle::capture(); let (run, line_name) = (host.run, host.name.clone()); - let job = Job { realm, host, world: World::working(self), start_uids: open, name: name.clone(), scope }; + let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope }; let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); self.script_key = Some(JobKey { id, run, name: line_name }); @@ -1450,6 +1902,10 @@ impl Session { if let Some(e) = job.host.dialogs.take_failure() { return Some(self.script_failed(job, &e)); } + // A canceled request ends a sleep or a wait at this pump. + if vectorcraft_doc::cancel::check().is_err() { + self.script_stop.set(); + } if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); self.script_key = Some(key); @@ -1461,9 +1917,6 @@ impl Session { let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; return Some(self.script_failed(job, &e)); } - if vectorcraft_doc::cancel::check().is_err() { - self.script_stop.set(); - } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); match outcome { @@ -1494,10 +1947,10 @@ impl Session { fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> { job.host.dialogs.stopped(); let fuel_left = job.realm.fuel_left(); - let (e, file) = located(&job.host, job.realm.error_source(), job.realm.error_mark(), e); + let (e, file) = located(&job.host, &job.realm, e); let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); - drop(job); + self.end_job(job, e.kind == RunErrorKind::Internal); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1579,6 +2032,7 @@ impl Session { "hostCalls": host.calls.get(), }); close_run(self, host, &mut report, console::Ending::Finished); + self.end_job(job, false); self.script_report = Some(report.clone()); Ok(report) } @@ -1617,6 +2071,10 @@ const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the scr const EVAL_NO_PATH: &str = "$.evalFile requires a file path"; const EVAL_TIMEOUT: &str = "$.evalFile: the timeout must be a finite number of milliseconds, 0 or more"; const EVAL_ARGUMENTS: &str = "$.evalFile: takes a file path and a timeout"; +const NO_RUN: &str = "this function's script run has ended"; +const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped"; +const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web"; +const ENGINE_BUSY: &str = "the script engine is in use by another run"; /// The report of a run that failed; `file` is the included file the error is in. fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { @@ -1782,6 +2240,10 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) }; + /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. + pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) }; + /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. + pub(crate) static TEST_KEPT_MAP_BYTES: Cell<Option<usize>> = const { Cell::new(None) }; /// Tests: the `JSINCLUDE` folders in place of the environment's. pub(crate) static TEST_JSINCLUDE: RefCell<Option<Vec<std::path::PathBuf>>> = const { RefCell::new(None) }; /// Tests: the time since a run started, in place of its clock's. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index e34eb711bd..887c740936 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -87,7 +87,6 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, - ignored_plugin_grants: Default::default(), plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, @@ -115,6 +114,7 @@ impl Session { recovery: Default::default(), in_tool_actions: false, previewing: false, + decoded_images: Default::default(), envelope_defaults: None, liquify_stroke: None, plane_widget_press: false, @@ -123,6 +123,7 @@ impl Session { press_type_selection: None, press_point: None, ruler_guide: None, + ruler_origin: None, port_marks: Default::default(), font_search: None, link_search: None, @@ -134,6 +135,7 @@ impl Session { global_edit_options: Default::default(), keyboard_text: false, script_key: None, + script_engines: crate::script::EnginesKey::new(), script_stop: vectorcraft_js::Interrupt::new(), script_report: None, script_console: Default::default(), @@ -300,8 +302,8 @@ impl Session { cmd::compositefonts::filter_loaded(&mut doc); // Inline graphics in text take their size from their symbols' art (not saved). doc.resolve_inline_art(); - // Guides from files saved before guides had layers go on a layer. - doc.adopt_guides(); + // Ruler guides a reader left in the saved list become nodes on their layers. + doc.guides_into_nodes(); cmd::dimension::conform(&mut doc); self.reset_tool_for_doc_switch(); let mut st = DocState::new(doc, path); @@ -328,7 +330,7 @@ impl Session { doc.limit_depth(); cmd::compositefonts::filter_loaded(&mut doc); doc.resolve_inline_art(); - doc.adopt_guides(); + doc.guides_into_nodes(); cmd::dimension::conform(&mut doc); // In the back, type set in a font named like a composite font is measured when the document // comes to the front and its own composite fonts are registered, not in the front diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 1762c96765..c7d22ab6c7 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -335,6 +335,7 @@ impl Session { pub fn commit_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); + self.decoded_images.empty(); if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } @@ -414,6 +415,7 @@ impl Session { pub fn cancel_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); + self.decoded_images.empty(); self.pending_paint = None; if let Some(paint) = self .active() diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 34c4eed727..23079fe901 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -82,7 +82,13 @@ impl Session { && params.get("ids").is_none_or(Value::is_null) && params.get("id").and_then(Value::as_str).is_some_and(|e| !e.starts_with('$')); if cmd::params::id_stands_for_ids(spec.params) && !effect_named && self.active().is_some() { - cmd::given_objects(self, params, id)?; + // `effect.refreshDeferred` looks its objects up itself: they can also be in the art of + // a symbol, pattern, brush or opacity mask. + if id == "effect.refreshDeferred" { + cmd::given_object_ids(params, id)?; + } else { + cmd::given_objects(self, params, id)?; + } } if SELECTS_GIVEN_IDS.contains(&id) { self.check_given_ids(id, params)?; @@ -99,6 +105,13 @@ impl Session { // the artboards the journal recorded need only a document too, whatever is selected and // whichever tool is chosen. let given = given_ids(spec.params, params); + // The guide commands take ruler guides by index; an object command given one's id is refused. + if let (Some(ids), Some(st)) = (&given, self.active()) + && let Some(guide) = ids.iter().find(|i| st.doc.node(**i).is_some_and(|n| n.is_ruler_guide())) + { + let value = guide.0; + return Err(cmd::bad(id, format!("id {value} is a ruler guide, not an object"))); + } let enabled = if (id == "edit.clear" && params.get("ids").is_some()) || (matches!(id, "edit.copy" | "edit.cut") && params.get("selectedArtboards").is_some()) { diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 01ebc46526..4943353ee0 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -39,6 +39,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use std::time::SystemTime; use vectorcraft_pdf::{PdfPreset, builtin_preset}; +use vectorcraft_plugins::permissions::GrantToken; use vectorcraft_plugins::safe_mode; use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; @@ -88,6 +89,24 @@ static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(()); /// The state of each plug-in folder's storage, shared by every storage made for the folder until /// the plug-in is removed, which closes it and drops it. static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new()); +/// The grants of plug-in stores that the sessions of the process don't count, and when each was +/// last written ([`IgnoredGrants`]). Another process reads `grants.json` as it is. +static IGNORED_PLUGIN_GRANTS: Mutex<IgnoredGrants> = Mutex::new(IgnoredGrants { ignored: BTreeSet::new(), written: BTreeMap::new(), writes: 0 }); +/// How many of the latest grant writes [`IgnoredGrants`] keeps. +const MAX_GRANT_WRITES_KEPT: usize = 256; + +/// Grants of plug-in stores, by the store's folder ([`plugin_store_key`]) and the plug-in id. +struct IgnoredGrants { + /// The grants that should be gone but could not be removed: no session in the process counts + /// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id + /// ([`Session::store_grant`]). + ignored: BTreeSet<(PathBuf, String)>, + /// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the + /// count of writes it made ([`IgnoredGrants::writes`]). + written: BTreeMap<(PathBuf, String), u64>, + /// How many grant writes the sessions of the process have made ([`Session::grant_writes`]). + writes: u64, +} /// The file name (without extension) a stored item called `name` gets: its name made safe for any /// file system, then a hash of the name, so that names that differ only in characters a file name @@ -99,6 +118,37 @@ pub(crate) fn file_stem(name: &str) -> String { format!("{}-{hash:016x}", safe.trim()) } +/// The folder `dir` spelled one way for every path to it, so that sessions attached to it by +/// different paths share [`IGNORED_PLUGIN_GRANTS`]: the canonical path when the folder exists, else +/// the canonical path of its nearest folder that exists followed by the rest of the path, with `.` +/// and `..` taken out by name. The path as given when it has no absolute form (the current folder +/// can't be read). +pub(crate) fn plugin_store_key(dir: &Path) -> PathBuf { + if let Ok(path) = std::fs::canonicalize(dir) { + return path; + } + let Ok(absolute) = std::path::absolute(dir) else { return dir.to_path_buf() }; + let mut parts: Vec<std::path::Component> = Vec::new(); + for part in absolute.components() { + match part { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + if matches!(parts.last(), Some(std::path::Component::Normal(_))) { + parts.pop(); + } + } + _ => parts.push(part), + } + } + for kept in (1..=parts.len()).rev() { + let base: PathBuf = parts[..kept].iter().collect(); + if let Ok(found) = std::fs::canonicalize(&base) { + return parts[kept..].iter().fold(found, |path, part| path.join(part)); + } + } + parts.iter().collect() +} + /// The regular files of `dir` with the extension `ext` (any case), by file name, at most /// [`MAX_STORE_FILES`]; none when the folder can't be read. fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> { @@ -190,12 +240,32 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> { thread_local! { /// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume. pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when + /// another program holds it open. + pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then + /// reports a failure, as when the last flush of a copy fails. + pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: moving a plug-in's settings and cache back from `<folder>.removed` ([`move_back`]) + /// fails on this thread, as when another program holds a file in the folder. + pub(crate) static MOVE_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: writing the `.delete` file beside a folder about to be deleted ([`delete_aside`]) + /// fails on this thread, as on a full volume. + pub(crate) static MARKER_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; } /// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted. fn take(dir: &Path, file: &str) -> bool { let path = dir.join(file); - match std::fs::remove_file(&path) { + #[cfg(test)] + let removed = if file == GRANTS_FILE && GRANTS_DELETE_FAILS.get() { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } else { + std::fs::remove_file(&path) + }; + #[cfg(not(test))] + let removed = std::fs::remove_file(&path); + match removed { Err(e) if e.kind() != std::io::ErrorKind::NotFound => { log::warn!("can't remove {}: {e}", path.display()); false @@ -334,9 +404,6 @@ impl Session { let disabled = read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); safe_mode::set_disabled(disabled); - if self.plugin_dir.as_ref() != Some(&dir) { - self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear(); - } self.plugin_dir = Some(dir); self.load_stored_plugins(); } @@ -347,7 +414,8 @@ impl Session { /// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and /// stays in the folder with its grant. A grant for an id whose stored module lists no /// permissions is forgotten; one that can't be removed from the grants file doesn't count for - /// the rest of the session ([`Session::plugin_approver`]). + /// any session in the process attached to the folder until the file can be written for the id + /// ([`Session::ignore_stored_grant`]). pub fn load_stored_plugins(&mut self) { let Some(dir) = self.plugin_dir.clone() else { return }; if safe_mode::active() { @@ -383,9 +451,11 @@ impl Session { match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) { Some(g) => { asks_nothing.remove(&m.id); - vectorcraft_plugins::registry::grant(g.clone()); + vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id)); - vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())); + if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + } } None => { log::warn!("skipping the stored plug-in {}: the user hasn't granted this module the permissions it lists", path.display()) @@ -395,7 +465,9 @@ impl Session { Ok(plugin) => { asks_nothing.insert(plugin.id().to_string()); vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id())); - vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())); + if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + } } Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), } @@ -407,8 +479,11 @@ impl Session { Ok(file) => file.names(id), Err(e) => e.unread, }; - if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) { - self.ignore_stored_grant(id); + if named { + let writes = self.grant_writes(); + if !self.store_grant(id, None) && self.holds_plugin_grant(id) { + self.ignore_stored_grant(id, writes); + } } } } @@ -469,12 +544,37 @@ impl Session { } } - /// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session - /// doesn't count ([`Session::ignore_stored_grant`]). + /// [`Session::plugin_approver`] for a folder load: a module the store's grants approve gets + /// that grant recorded for the process too, since the registry installs only a module that a + /// recorded grant covers ([`vectorcraft_plugins::registry::install`]). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn plugin_folder_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> { + let grants = self.plugin_dir.as_deref().map(|dir| self.counted_grants(dir)); + move |plugin| { + let m = plugin.manifest(); + match &grants { + Some(grants) if m.asks_permissions() => match grants.get(&m.id).filter(|g| grant_covers(g, plugin)) { + Some(g) => { + vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); + true + } + None => false, + }, + _ => vectorcraft_plugins::registry::approved(plugin), + } + } + } + + /// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those the process + /// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked + /// out on each call, so a path whose link now leads elsewhere is matched with where it leads. fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> { - let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()); + let key = plugin_store_key(dir); let mut grants = stored_grants(dir); - grants.retain(|id, _| !ignored.contains(id)); + let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); + for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) { + grants.remove(id); + } grants } @@ -498,16 +598,21 @@ impl Session { /// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a /// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the - /// store now holds `previous`. + /// write reported success; a write that reports a failure may still have put `previous` back. pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool { #[cfg(test)] if PUT_BACK_FAILS.get() { return false; } - match previous { + let back = match previous { Some(bytes) => self.store_plugin(id, bytes), None => self.unstore_plugin(id), + }; + #[cfg(test)] + if PUT_BACK_FAILS_AFTER_WRITE.get() { + return false; } + back } /// The file the plug-in `id` is stored in, spelled as [`Session::load_stored_plugins`] names it @@ -522,20 +627,53 @@ impl Session { /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now /// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts - /// again ([`Session::ignore_stored_grant`]). + /// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]). pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool { let done = self.write_grant(id, grant); - if done { - self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) { + let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); + let entry = (key, id.to_string()); + shared.ignored.remove(&entry); + shared.writes = shared.writes.saturating_add(1); + let writes = shared.writes; + shared.written.insert(entry, writes); + if shared.written.len() > MAX_GRANT_WRITES_KEPT + && let Some(oldest) = shared.written.iter().min_by_key(|(_, at)| **at).map(|(entry, _)| entry.clone()) + { + shared.written.remove(&oldest); + } } done } - /// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next - /// succeeds for it or another store is attached: for a grant that should be gone and could not - /// be removed, which would otherwise approve the bytes it covers. - pub(crate) fn ignore_stored_grant(&self, id: &str) { - self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string()); + /// How many grant writes the sessions of the process have made ([`Session::store_grant`]). + /// Taken before a write that may fail, for [`Session::ignore_stored_grant`]. + pub(crate) fn grant_writes(&self) -> u64 { + IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes + } + + /// How many grant writes the process keeps ([`IgnoredGrants::written`]). + #[cfg(test)] + pub(crate) fn grant_writes_kept() -> usize { + IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).written.len() + } + + /// Stop counting the attached store's grant for the plug-in `id`, in every session in the + /// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in + /// one of them: for a grant that should be gone and could not be removed, which would otherwise + /// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed + /// write: when a session has written the store's grants for `id` since, the file holds what that + /// write asked for, and the grant keeps counting. A write no longer among the latest + /// [`MAX_GRANT_WRITES_KEPT`] is not seen, and the grant stops counting. Another process on the + /// folder reads `grants.json` as it is. + pub(crate) fn ignore_stored_grant(&self, id: &str, writes: u64) { + if let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) { + let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); + let entry = (key, id.to_string()); + if shared.written.get(&entry).is_none_or(|at| *at <= writes) { + shared.ignored.insert(entry); + } + } } fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool { @@ -590,26 +728,34 @@ impl Session { } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without - /// one, nowhere (its storage calls then fail as unavailable). + /// one, nowhere (its storage calls then fail as unavailable). Settings and cache that a removal + /// kept are moved back first ([`plugin_storage`]). pub(crate) fn attach_plugin_storage(&self, id: &str) { vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id)); } - /// Does the attached plug-in store have a folder of settings and cache for plug-in `id`? A - /// folder behind a `storage` folder that is a link is not counted: the plug-in's storage calls - /// can't reach it and removing the plug-in leaves it. + /// Does the attached plug-in store have a folder of settings and cache for plug-in `id`, or one + /// that a removal kept ([`aside_paths`], [`is_kept`])? A folder behind a `storage` folder + /// that is a link is not counted: the plug-in's storage calls can't reach it and removing the + /// plug-in leaves it. pub(crate) fn has_plugin_storage(&self, id: &str) -> bool { - self.plugin_dir - .as_deref() - .is_some_and(|dir| !is_link(&dir.join(PLUGIN_DATA_DIR)) && std::fs::symlink_metadata(plugin_data_dir(dir, id)).is_ok()) + self.plugin_dir.as_deref().is_some_and(|dir| { + let path = plugin_data_dir(dir, id); + !is_link(&dir.join(PLUGIN_DATA_DIR)) && (std::fs::symlink_metadata(&path).is_ok() || aside_paths(&path).iter().any(|a| is_kept(a))) + }) } /// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it. - /// The folder is first renamed out of the way (`<folder>.removed`), and that fails, leaving it - /// as it was, when the rename does; what the deletion then leaves stays under that name, with a - /// log record. A later call for the id tries to delete it again. `forget` runs once the folder is - /// out of the way, before anything is deleted: when it returns `false`, the folder is renamed - /// back and this fails. + /// Settings and cache that an earlier removal kept ([`is_kept`]) are first moved back when the + /// folder is missing ([`restore_removed`]); what earlier deletions left is deleted. The folder is + /// then renamed out of the way ([`aside_paths`]: `<folder>.removed`, or `<folder>.removing` while + /// `<folder>.removed` holds kept settings), and that fails, leaving it as it was, when the rename + /// does. `forget` runs once the folder is out of the way, before anything is deleted: when it + /// returns `false`, the folder is renamed back and this fails, and the kept settings stay. When + /// that rename fails too, the error also names both paths and the reason, and the next attach or + /// removal for the id moves the folder back. Once `forget` returns `true`, the folder and the + /// kept settings are deleted ([`delete_aside`]); what that deletion leaves stays, with a log + /// record, and a later call for the id tries to delete it again. pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> { let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string()); vectorcraft_plugins::registry::set_storage(id, None); @@ -636,28 +782,45 @@ impl Session { close(); return Ok(()); } - let mut aside = path.clone().into_os_string(); - aside.push(".removed"); - let aside = PathBuf::from(aside); - let _ = std::fs::remove_dir_all(&aside); - match std::fs::rename(&path, &aside) { + let asides = aside_paths(&path); + if std::fs::symlink_metadata(&path).is_err() + && let Err(e) = restore_removed(&path) + { + log::warn!("can't move the settings and cache of {} back: {e}", path.display()); + } + for aside in asides.iter().filter(|a| !is_kept(a)) { + delete_aside(aside); + } + let target = if std::fs::symlink_metadata(&path).is_err() { + asides.iter().rev().find(|a| is_kept(a)).unwrap_or(&asides[0]) + } else if !is_kept(&asides[0]) { + &asides[0] + } else if std::fs::symlink_metadata(&asides[1]).is_err() { + &asides[1] + } else { + return Err(StorageError::Io(format!("{}: {} and {} are in the way", path.display(), asides[0].display(), asides[1].display()))); + }; + match std::fs::rename(&path, target) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(StorageError::Io(format!("{}: {e}", path.display()))), Ok(()) => {} } if !forget() { - if std::fs::symlink_metadata(&aside).is_ok() - && let Err(e) = std::fs::rename(&aside, &path) + if std::fs::symlink_metadata(target).is_ok() + && let Err(e) = move_back(target, &path) { - log::warn!("can't move {} back: {e}", aside.display()); + log::warn!("can't move {} back: {e}", target.display()); + return Err(StorageError::Io(format!( + "{GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {} to {}: {e}", + target.display(), + path.display() + ))); } return Err(not_forgotten()); } close(); - if std::fs::symlink_metadata(&aside).is_ok() - && let Err(e) = std::fs::remove_dir_all(&aside) - { - log::warn!("can't delete {}: {e}", aside.display()); + for aside in &asides { + delete_aside(aside); } Ok(()) } @@ -688,10 +851,107 @@ pub(crate) fn plugin_data_dir(dir: &Path, id: &str) -> PathBuf { dir.join(PLUGIN_DATA_DIR).join(format!("id-{}", case_safe(id))) } -/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. +/// `path` with `suffix` added to its last part. +fn suffixed(path: &Path, suffix: &str) -> PathBuf { + let mut named = path.as_os_str().to_os_string(); + named.push(suffix); + PathBuf::from(named) +} + +/// Where [`Session::remove_plugin_storage`] moves the plug-in folder `path` out of the way: +/// `<path>.removed`, and `<path>.removing` while `<path>.removed` holds settings and cache an +/// earlier removal kept ([`is_kept`]). The second one, when it is there, is the newer. +fn aside_paths(path: &Path) -> [PathBuf; 2] { + [suffixed(path, ".removed"), suffixed(path, ".removing")] +} + +/// `<aside>.delete`: an empty file written next to the folder `aside` before it is deleted, so +/// that what a failed deletion leaves there is not taken for settings a removal kept. +fn delete_marker(aside: &Path) -> PathBuf { + suffixed(aside, ".delete") +} + +/// Does `aside` hold settings and cache that a removal kept: a folder, or a link in place of one, +/// without a [`delete_marker`] beside it? +fn is_kept(aside: &Path) -> bool { + std::fs::symlink_metadata(aside).is_ok_and(|m| !m.is_file()) && std::fs::symlink_metadata(delete_marker(aside)).is_err() +} + +/// Write the empty file `marker` ([`delete_marker`]). +fn write_delete_marker(marker: &Path) -> std::io::Result<()> { + #[cfg(test)] + if MARKER_WRITE_FAILS.get() { + return Err(std::io::Error::other("the volume is full")); + } + std::fs::write(marker, b"") +} + +/// Delete the folder `aside` (a file there is left), writing its [`delete_marker`] first and +/// removing it once the folder is gone; what the deletion can't remove stays, with a log record. +/// When the marker can't be written, nothing is deleted, so that the folder stays whole. +fn delete_aside(aside: &Path) { + let marker = delete_marker(aside); + match std::fs::symlink_metadata(aside) { + Err(_) => { + let _ = std::fs::remove_file(&marker); + return; + } + Ok(m) if m.is_file() => return, + Ok(_) => {} + } + if let Err(e) = write_delete_marker(&marker) { + log::warn!("can't save {}: {e}; {} is left as it is", marker.display(), aside.display()); + return; + } + match std::fs::remove_dir_all(aside) { + Err(e) => log::warn!("can't delete {}: {e}", aside.display()), + Ok(()) => { + if let Err(e) = std::fs::remove_file(&marker) { + log::warn!("can't remove {}: {e}", marker.display()); + } + } + } +} + +/// Rename the plug-in folder at `aside` back to `path`. +fn move_back(aside: &Path, path: &Path) -> std::io::Result<()> { + #[cfg(test)] + if MOVE_BACK_FAILS.get() { + return Err(std::io::Error::other("the folder is in use")); + } + std::fs::rename(aside, path) +} + +/// Move the newest settings and cache that a removal kept ([`aside_paths`], [`is_kept`]) back to +/// the plug-in folder `path` when there is none. When `path` is there, it is used and the kept +/// folders are left as they are, with a log record, until the plug-in's removal deletes them. +/// Called under [`PLUGIN_DATA_LOCK`]. +fn restore_removed(path: &Path) -> std::io::Result<()> { + let asides = aside_paths(path); + let mut kept = asides.iter().rev().filter(|a| is_kept(a)); + if std::fs::symlink_metadata(path).is_ok() { + for aside in kept { + log::warn!("{} is used: the settings and cache in {} are left as they are", path.display(), aside.display()); + } + return Ok(()); + } + kept.next().map_or(Ok(()), |aside| move_back(aside, path)) +} + +/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. Settings and cache +/// that a removal kept are moved back first ([`restore_removed`]); when that fails, the failure is +/// logged and there is no storage (its calls fail as unavailable), so that nothing the plug-in +/// writes takes their place. A later attach or load tries again. fn plugin_storage(dir: Option<&Path>, id: &str) -> Option<Arc<dyn Storage>> { let dir = dir?; let data = plugin_data_dir(dir, id); + if !is_link(&dir.join(PLUGIN_DATA_DIR)) { + let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if let Err(e) = restore_removed(&data) { + log::warn!("can't move the settings and cache of {} back: {e}", data.display()); + return None; + } + } let state = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).entry(data.clone()).or_default().clone(); Some(Arc::new(PluginStorage { root: dir.to_path_buf(), dir: data, state })) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9c6de6a89e..3363bb4a0c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20,6 +20,7 @@ mod brushlib; mod brushsym; mod build; mod cancel; +mod caret_kerning; mod charstroke; pub(super) mod clip; mod clipboard; @@ -47,6 +48,7 @@ mod docsetup; mod document_move; mod draw2; mod dynamic_symbols; +mod dynamic_text; mod editcolors; mod effectedit; mod emptytype; @@ -88,6 +90,7 @@ mod layerclip; mod layers; mod legacy_ai; mod library; +mod library_roots; mod link_paths; mod linked_stops; mod linkfiles; @@ -131,6 +134,7 @@ mod placed_document; mod plugins; mod prefs; mod prefs_file; +mod prefs_roots; mod previewbounds; mod print; mod printadvanced; @@ -153,10 +157,13 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_engines; mod script_folder; mod script_include; +mod script_io; mod script_run; mod scripts; +mod select_effects; mod select_ids_first; mod shaper; mod shapetools; @@ -192,12 +199,14 @@ mod toolsettings; mod transformfx; mod transparencygrid; mod trap; +mod turn_direction; mod typearea; mod typeglyphbounds; mod typescale; mod typeundo; mod units; mod variables; +mod warp_images; mod webexport; mod widthpoints; mod widthprofiles; @@ -215,6 +224,18 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { NodeId(r["id"].as_u64().unwrap()) } +/// The active document's selected ruler guides, by their `guide.list` indexes. +pub(crate) fn selected_guides(s: &Session) -> Vec<usize> { + let st = s.doc().unwrap(); + crate::cmd::guide_indexes(&st.doc, &st.selection.guides) +} + +/// The active document's key guide, by its `guide.list` index. +pub(crate) fn key_guide(s: &Session) -> Option<usize> { + let st = s.doc().unwrap(); + st.selection.key_guide.and_then(|k| crate::cmd::guide_indexes(&st.doc, &[k]).first().copied()) +} + #[test] fn create_and_undo_redo() { let mut s = session(); @@ -3145,7 +3166,7 @@ fn every_command_survives_empty_params() { // The view toggles among them flip the process-wide proof view. let _proof_view = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); for sel in [false, true] { - for c in command_specs() { + for c in command_specs().iter().filter(|c| crate::runs_with_empty_params(c.id)) { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); rect(&mut s, 20.0, 0.0, 10.0, 10.0); @@ -4230,8 +4251,8 @@ fn given_targets_are_used_as_given_and_range_style_takes_the_selected_type() { /// #785: commands whose `ids` or `id` the shared check doesn't read (it reads `id` where it stands /// for `ids` of one) refuse one that isn't an object id. They don't act on the selection, the -/// current layer or a new object instead, and the document, the selection and the undo history -/// stay as they are. +/// current layer or a new object instead, and the document, the selection, the undo history, +/// isolation mode and the shown opacity mask stay as they are. #[test] fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() { let mut s = session(); @@ -4279,17 +4300,19 @@ fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() { if let Some(p) = p.as_object_mut() { p.insert(key.into(), bad.clone()); } - let (doc, selection, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len()); + let st = s.doc().unwrap(); + let (doc, selection, undo, modes) = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), (st.isolation, st.mask_view)); let r = s.execute(cmd, &p); let named = |e: &str| e.contains("object id") || e.contains("step reference") || e.contains(&format!("`{key}` must be")); let refused = r.as_ref().err().map(|e| e.to_string()).is_some_and(|e| named(&e)); - let same = s.doc().unwrap().doc == doc && s.doc().unwrap().selection == selection && s.doc().unwrap().history.undo.len() == undo; + let st = s.doc().unwrap(); + let same = st.doc == doc && st.selection == selection && st.history.undo.len() == undo && (st.isolation, st.mask_view) == modes; if !(refused && same) { wrong.push(format!("{cmd} {p}: {r:?}, document unchanged: {same}")); } if !same { let st = s.doc_mut().unwrap(); - (st.doc, st.selection) = (doc, selection); + (st.doc, st.selection, (st.isolation, st.mask_view)) = (doc, selection, modes); st.history.undo.truncate(undo); } } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 8d12c83719..53cbb42ca9 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, FillLayer, Node}; +use vectorcraft_doc::{AppearanceItem, FillLayer, LineJoin, Node}; use crate::*; @@ -185,6 +185,48 @@ fn group_rows_are_the_groups_own_stack() { assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00"); } +/// #6739: `stroke.set` without an item on a group with a stroke row of its own edits that row; +/// its members, which have no stroke (as paths a PDF import brings in), are left alone instead of +/// each getting a black 1 pt stroke. Options alone never make a stroke visible: a row created for +/// a join has no paint, while a weight still gives the usual black stroke. +#[test] +fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + for id in [a, b] { + run(&mut s, "appearance.removeItem", json!({"ids": [id.0], "index": 1})); + assert!(node(&s, id).appearance.stroke().is_none(), "the member has no stroke row"); + } + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "appearance.setItem", json!({"ids": [g.0], "index": 0, "color": "#ffffff", "weight": 2})); + let r = run(&mut s, "stroke.set", json!({"ids": [g.0], "join": "round"})); + assert_eq!(r["objects"], 1, "{r}"); + let gs = node(&s, g).appearance.stroke().unwrap().clone(); + assert_eq!((gs.join, gs.width, gs.paint.color().map(|c| c.to_hex())), (LineJoin::Round, 2.0, Some("#ffffff".to_string()))); + for id in [a, b] { + assert!(node(&s, id).appearance.stroke().is_none(), "a member keeps no stroke"); + } + // A group without a stroke of its own still reaches its members; for a join alone the row + // made on each has no paint, so nothing becomes visible. + let (c, d) = (rect(&mut s, 400.0), rect(&mut s, 550.0)); + for id in [c, d] { + run(&mut s, "appearance.removeItem", json!({"ids": [id.0], "index": 1})); + } + let h = NodeId(run(&mut s, "object.group", json!({"ids": [c.0, d.0]}))["id"].as_u64().unwrap()); + run(&mut s, "stroke.set", json!({"ids": [h.0], "join": "bevel"})); + for id in [c, d] { + let st = node(&s, id).appearance.stroke().cloned().expect("a stroke row for the join"); + assert_eq!((st.paint, st.join), (Paint::None, LineJoin::Bevel), "no paint for a join alone"); + } + // A weight is a visible stroke: an object without one gets the black stroke, as before. + let e = rect(&mut s, 700.0); + run(&mut s, "appearance.removeItem", json!({"ids": [e.0], "index": 1})); + run(&mut s, "stroke.set", json!({"ids": [e.0], "weight": 3})); + let st = node(&s, e).appearance.stroke().cloned().unwrap(); + assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0)); +} + #[test] fn text_items_take_item_paint() { let mut s = session(); diff --git a/crates/engine/src/tests/areafit.rs b/crates/engine/src/tests/areafit.rs index b6d6883430..7d8f759cf5 100644 --- a/crates/engine/src/tests/areafit.rs +++ b/crates/engine/src/tests/areafit.rs @@ -485,7 +485,7 @@ fn making_and_restyling_type_reports_its_overflow() { } /// The formats whose exports draw type. -const DRAWING_FORMATS: [&str; 8] = ["pdf", "eps", "svg", "png", "jpg", "tiff", "emf", "wmf"]; +const DRAWING_FORMATS: [&str; 9] = ["pdf", "eps", "svg", "png", "jpg", "tiff", "emf", "wmf", "hpgl"]; /// The warnings of `document.export {format, …options}` about type that doesn't fit its frame. fn export_overflow(s: &mut Session, format: &str, options: Value) -> Vec<String> { diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 059357ddb3..4b391c5714 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -418,3 +418,179 @@ fn native_blend_easing_values_clamp_and_non_finite_become_default() { assert_eq!((spec.ease.ramp, spec.color_shift), (ramp, shift), "{bad}"); } } + +fn create_spine(s: &mut Session, p: Value) -> Value { + s.execute("object.blend.createSpine", &p).unwrap()["mode"].clone() +} + +/// Two squares 100 pt apart blended with `p`; the blend. +fn make(s: &mut Session, y: f64, p: Value) -> NodeId { + let (a, b) = (rect(s, 0.0, y, 10.0), rect(s, 100.0, y, 10.0)); + let mut p = p; + p["ids"] = json!([a.0, b.0]); + p["steps"] = json!(3); + id_of(&s.execute("object.blend.make", &p).unwrap()) +} + +#[test] +fn create_spine_sets_whether_new_blends_get_a_spine() { + let mut s = session(); + assert_eq!(create_spine(&mut s, json!({})), "auto", "Auto until one is chosen"); + let spined = make(&mut s, 0.0, json!({})); + assert!(!spec(&s, spined).1.no_spine); + let depth = s.doc().unwrap().history.undo.len(); + assert_eq!(create_spine(&mut s, json!({"mode": "never"})), "never"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth, "a tool setting, not an undo step"); + assert_eq!(create_spine(&mut s, json!({})), "never"); + // The Blend Options set with nothing selected keep it, and it keeps them. + s.execute("select.none", &json!({})).unwrap(); + s.execute("object.blend.options", &json!({"steps": 7})).unwrap(); + assert_eq!(create_spine(&mut s, json!({})), "never"); + assert_eq!(s.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7)); + // A new blend has no spine; the blend made before keeps its own. + let bare = make(&mut s, 50.0, json!({})); + assert!(spec(&s, bare).1.no_spine); + assert!(!spec(&s, spined).1.no_spine, "blends already made keep their spine"); + sel(&mut s, &[bare]); + let info = s.execute("object.blend.info", &json!({})).unwrap(); + assert_eq!(info["hasSpine"], json!(false)); + assert!(info.get("spine").is_none(), "{info}"); + sel(&mut s, &[spined]); + assert_eq!(s.execute("object.blend.info", &json!({})).unwrap()["hasSpine"], json!(true)); + // `createSpine` on Make chooses for that blend only. + let forced = make(&mut s, 100.0, json!({"createSpine": "always"})); + assert!(!spec(&s, forced).1.no_spine); + assert_eq!(create_spine(&mut s, json!({})), "never"); + assert_eq!(create_spine(&mut s, json!({"mode": "always"})), "always"); + let always = make(&mut s, 150.0, json!({})); + assert!(!spec(&s, always).1.no_spine); + assert!(spec(&s, bare).1.no_spine, "blends already made keep having no spine"); + let none = make(&mut s, 200.0, json!({"createSpine": "never"})); + assert!(spec(&s, none).1.no_spine); + // The setting survives a round trip through the preferences file; Auto is not written. + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Always); + assert_eq!(s.prefs.to_json()["blendOptions"]["createSpine"], json!("always")); + create_spine(&mut s, json!({"mode": "auto"})); + assert!(s.prefs.to_json()["blendOptions"].get("createSpine").is_none()); + let mut odd = s.prefs.to_json(); + odd["blendOptions"]["createSpine"] = json!("sometimes"); + let unknown: Prefs = serde_json::from_value(odd).unwrap(); + assert_eq!(unknown.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Auto, "an unknown value reads as Auto"); +} + +#[test] +fn create_spine_refuses_bad_values_and_changes_nothing() { + let mut s = session(); + create_spine(&mut s, json!({"mode": "never"})); + let prefs = s.prefs.blend_options; + for bad in [json!({"mode": "sometimes"}), json!({"mode": 1}), json!({"mode": true}), json!({"mode": ["never"]}), json!({"mode": "Never"})] { + let e = s.execute("object.blend.createSpine", &bad).unwrap_err().to_string(); + assert!(e.contains("`mode` must be one of auto, always, never"), "{bad}: {e}"); + assert_eq!(s.prefs.blend_options, prefs, "{bad}"); + } + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0)); + let depth = s.doc().unwrap().history.undo.len(); + for bad in [json!({"createSpine": "x"}), json!({"createSpine": 0}), json!({"createSpine": "never", "easingType": "easeIn"}), json!({"ramp": 30})] + { + let mut p = bad.clone(); + p["ids"] = json!([a.0, b.0]); + assert!(s.execute("object.blend.make", &p).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth, "{bad}: nothing made"); + } + assert!(s.execute("object.blend.createSpine", &json!({"spine": "never"})).is_err(), "an unknown key"); +} + +#[test] +fn a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release() { + let mut s = session(); + let g = make(&mut s, 0.0, json!({"createSpine": "never"})); + sel(&mut s, &[g]); + let before = node(&s, g); + let depth = s.doc().unwrap().history.undo.len(); + // Reverse Spine, easing and the spine point commands refuse it and change nothing. + let refused = [ + ("object.blend.reverseSpine", json!({})), + ("object.blend.options", json!({"easingType": "easeOut"})), + ("object.blend.options", json!({"ramp": 40})), + ("object.blend.spine.addAnchor", json!({"x": 50, "y": 5})), + ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 50})), + ]; + for (cmd, p) in refused { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("the blend has no spine"), "{cmd}: {e}"); + assert_eq!((node(&s, g), s.doc().unwrap().history.undo.len()), (before.clone(), depth), "{cmd}"); + } + // Spacing, Orientation and Shift still apply; Align to Path makes no spine. + s.execute("object.blend.options", &json!({"steps": 2, "orientation": "path", "colorShift": 20})).unwrap(); + let sp = spec(&s, g).1; + assert_eq!((sp.spacing, sp.orientation, sp.color_shift, sp.no_spine), (BlendSpacing::Steps(2), BlendOrientation::AlignToPath, 20.0, true)); + assert!(s.execute("object.blend.info", &json!({})).unwrap().get("spine").is_none()); + // Taking in another key keeps it without a spine, whatever Create Spine says. + let c = rect(&mut s, 200.0, 0.0, 10.0); + sel(&mut s, &[g, c]); + create_spine(&mut s, json!({"mode": "always"})); + let g = id_of(&s.execute("object.blend.make", &json!({})).unwrap()); + assert_eq!(spec(&s, g).0.len(), 3); + assert!(spec(&s, g).1.no_spine && spec(&s, g).1.spine.is_none()); + // Release gives back the keys and no spine path. + sel(&mut s, &[g]); + let r = s.execute("object.blend.release", &json!({})).unwrap(); + assert_eq!((r["ids"].as_array().map(Vec::len), &r["spines"]), (Some(3), &json!([]))); + s.execute("edit.undo", &json!({})).unwrap(); + // Replace Spine gives it one: then it reverses and eases like any other. + let line = id_of(&s.execute("path.create", &json!({"d": "M0 100 L200 150"})).unwrap()); + sel(&mut s, &[g, line]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let sp = spec(&s, g).1; + assert!(!sp.no_spine && sp.spine.is_some()); + let info = s.execute("object.blend.info", &json!({})).unwrap(); + assert_eq!((&info["hasSpine"], &info["spine"]["explicit"]), (&json!(true), &json!(true))); + s.execute("object.blend.reverseSpine", &json!({})).unwrap(); + s.execute("object.blend.options", &json!({"easingType": "easeOut", "ramp": 40})).unwrap(); + assert_eq!(spec(&s, g).1.ease.ramp, 0.4); +} + +#[test] +fn a_blend_without_a_spine_draws_its_steps_where_one_with_a_spine_does() { + let mut s = session(); + for orientation in ["page", "path"] { + let spined = make(&mut s, 0.0, json!({"orientation": orientation})); + let bare = make(&mut s, 0.0, json!({"orientation": orientation, "createSpine": "never"})); + let boxes = |g: NodeId| -> Vec<_> { vectorcraft_doc::live::expand_live(&node(&s, g)).iter().map(|n| n.geometric_bounds()).collect() }; + assert_eq!(boxes(bare), boxes(spined), "{orientation}"); + assert!(boxes(bare).len() >= 3, "the three steps at least"); + } + // Easing stored on a blend without a spine (a hand-edited file) leaves its steps evenly spaced. + let bare = make(&mut s, 300.0, json!({"orientation": "path", "createSpine": "never"})); + let even = vectorcraft_doc::live::expand_live(&node(&s, bare)); + let mut eased = node(&s, bare); + if let NodeKind::Blend { spec, .. } = &mut eased.kind { + spec.ease = vectorcraft_doc::live::BlendEase { kind: vectorcraft_doc::live::BlendEaseType::In, ramp: 1.0 }; + } + let boxes = |v: &[Node]| -> Vec<_> { v.iter().map(|n| n.geometric_bounds()).collect() }; + assert_eq!(boxes(&vectorcraft_doc::live::expand_live(&eased)), boxes(&even)); +} + +#[test] +fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() { + let mut s = session(); + let bare = make(&mut s, 0.0, json!({"createSpine": "never"})); + let spined = make(&mut s, 50.0, json!({})); + let d = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap(); + assert_eq!(&back.layers, &d.layers); + let saved = |g: NodeId| match &back.node(g).unwrap().kind { + NodeKind::Blend { spec, .. } => spec.no_spine, + _ => panic!("not a blend"), + }; + assert!(saved(bare) && !saved(spined)); + assert_eq!(serde_json::to_value(spec(&s, bare).1).unwrap()["noSpine"], json!(true)); + assert!(serde_json::to_value(spec(&s, spined).1).unwrap().get("noSpine").is_none(), "a spine is not written"); + let old: BlendSpec = serde_json::from_value(json!({"spacing": {"steps": 4}})).unwrap(); + assert!(!old.no_spine, "a blend saved before Create Spine has a spine"); + for odd in [json!("yes"), json!(1), json!(null)] { + let v: BlendSpec = serde_json::from_value(json!({"noSpine": odd.clone()})).unwrap_or_else(|e| panic!("{odd}: {e}")); + assert!(!v.no_spine, "{odd}"); + } +} diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index e98593bfc8..243ea564f4 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -104,7 +104,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { let list = run(&mut s, "brush.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); let ids: Vec<&str> = libs.iter().map(|l| l["id"].as_str().unwrap()).collect(); - assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "pattern-borders", "scatter-shapes", "game-trails"]); + assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "bristle-brushes", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams"]); assert!(libs.iter().all(|l| l["category"] == "builtIn")); let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"})); assert_eq!( @@ -117,14 +117,26 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[4]["count"].as_u64(), Some(4)); + assert_eq!(libs[5]["count"].as_u64(), Some(4)); + let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); + assert_eq!( + beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(), + ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] + ); + assert_eq!(libs[6]["count"].as_u64(), Some(4)); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); + assert_eq!(strs(&added["added"]), ["Laser Bolt"]); // One kind of brush per library, every brush drawing something. for (id, kind) in [ ("art-ribbons", "art"), ("calligraphic-nibs", "calligraphic"), + ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), ("game-trails", "art"), + ("energy-beams", "art"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -154,6 +166,77 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); } +/// Bristle Brushes: one brush per tip shape, every value inside the range the brush keeps (a value +/// outside would be clamped without notice), names no other library or default brush uses; added +/// in one step, not twice, and saved as a library they reopen unchanged. +#[test] +fn the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges() { + use vectorcraft_brush::{Bristle, BristleShape}; + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "bristle-brushes").unwrap(); + assert_eq!(lib.name, "Bristle Brushes"); + let names: Vec<String> = lib.brushes.iter().map(|b| b.name.clone()).collect(); + assert!((8..=10).contains(&names.len()), "{names:?}"); + let within = |v: f64, (lo, hi): (f64, f64)| (lo..=hi).contains(&v); + let mut shapes = vec![]; + for b in &lib.brushes { + let BrushKind::Bristle(x) = &b.kind else { panic!("{} is not a bristle brush", b.name) }; + assert!(within(x.size, Bristle::SIZE_RANGE) && within(x.length, Bristle::LENGTH_RANGE), "{}", b.name); + for v in [x.density, x.thickness, x.opacity, x.stiffness] { + assert!(within(v, Bristle::PERCENT_RANGE), "{}: {v}", b.name); + } + let mut kept = b.clone(); + kept.sanitize(); + assert_eq!(&kept, b, "sanitizing changes {}", b.name); + assert!(b.name.chars().count() <= Bristle::MAX_NAME_CHARS, "{}", b.name); + if !shapes.contains(&x.shape) { + shapes.push(x.shape); + } + } + let every = [ + BristleShape::RoundPoint, + BristleShape::FlatPoint, + BristleShape::RoundBlunt, + BristleShape::FlatBlunt, + BristleShape::RoundCurve, + BristleShape::FlatCurve, + BristleShape::RoundAngle, + BristleShape::FlatAngle, + BristleShape::RoundFan, + BristleShape::FlatFan, + ]; + assert!(every.iter().all(|x| shapes.contains(x)), "{shapes:?}"); + // Names of its own: no default brush's, no other built-in library's, none twice. + let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect(); + let others: Vec<String> = cmd::brushlib::BUILTIN + .iter() + .filter(|b| b.id != "bristle-brushes") + .flat_map(|b| cmd::brushlib::library(&s, b.id).unwrap().1.brushes.iter().map(|x| x.name.clone()).collect::<Vec<_>>()) + .collect(); + for (i, n) in names.iter().enumerate() { + assert!(!defaults.contains(&n.as_str()) && !others.contains(n) && !names[..i].contains(n), "{n}"); + } + + // Added to a document in one undo step; adding them again adds nothing. + let before = (undo_len(&s), brushes(&s)); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Bristle Brushes"})); + assert_eq!(strs(&r["added"]), names.iter().map(String::as_str).collect::<Vec<_>>()); + assert_eq!(undo_len(&s), before.0 + 1); + assert_eq!(brushes(&s), [before.1.clone(), names.clone()].concat()); + for b in &lib.brushes { + assert_eq!(&brush(&s, &b.name), b); + } + let again = undo_len(&s); + let r = run(&mut s, "brush.addFromLibrary", json!({"library": "bristle-brushes"})); + assert_eq!((strs(&r["added"]).len(), strs(&r["existing"]).len(), undo_len(&s)), (0, names.len(), again)); + // Saved as a library and loaded back: the same brushes, in the same order. + let saved = run(&mut s, "brush.saveLibrary", json!({ "names": names, "name": "Bristles" })); + let b64 = saved["dataBase64"].as_str().unwrap().to_string(); + let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Bristles.vectorcraft"})); + let (_, reopened) = cmd::brushlib::library(&s, r["library"].as_str().unwrap()).unwrap(); + assert_eq!(reopened.brushes, lib.brushes); +} + #[test] fn a_saved_library_reopens_and_its_brushes_join_another_document_in_one_step() { let dir = folder("user"); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index b86cf89ee7..1a1fcd87b5 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -253,6 +253,367 @@ fn selection_art_is_the_art_new_brush_takes() { assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only brush.new is an undo step"); } +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn selected(s: &Session) -> Vec<NodeId> { + s.doc().unwrap().selection.objects.clone() +} + +/// The JSON of object `id`, as `brush.options` params take art. +fn art_json(s: &mut Session, id: NodeId) -> Value { + s.execute("brush.selectionArt", &json!({"ids": [id.0]})).unwrap()["art"].clone() +} + +/// `brush.placeArt` places a copy of an art or scatter brush's art centered where it is dropped +/// (by default on the first artboard's center), selected, in one undo step; brushes without art, +/// unknown brushes and a position that is not a number are refused. +#[test] +fn place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped() { + let mut s = session(); + let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0); + s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap(); + let steps = undo_steps(&s); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Bar", "x": 100, "y": 80})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(selected(&s), vec![id]); + assert_ne!(id, r, "a copy, not the art the brush was made from"); + assert!(close(bounds(&s, id), Rect::new(80.0, 76.0, 120.0, 84.0), 1e-6), "{:?}", bounds(&s, id)); + // Without a position: the first artboard's center (the document is 400 × 300). + let scatter = NodeId(s.execute("brush.placeArt", &json!({"name": "Dots"})).unwrap()["id"].as_u64().unwrap()); + let c = bounds(&s, scatter).center(); + assert!((c.x - 200.0).abs() < 1e-6 && (c.y - 150.0).abs() < 1e-6, "{c:?}"); + let steps = undo_steps(&s); + for (p, msg) in [ + (json!({"name": "3 pt. Round"}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Bristle Round"}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Nope"}), "no brush named `Nope`"), + ] { + let e = s.execute("brush.placeArt", &p).unwrap_err(); + assert!(e.to_string().contains(msg), "{p}: {e}"); + } + assert!(s.execute("brush.placeArt", &json!({"name": "Bar", "x": "100"})).is_err()); + assert_eq!(undo_steps(&s), steps, "a refused call adds no undo step"); +} + +/// Brush art holding an instance of a symbol whose art lies away from the symbol's origin (as +/// imported symbols can) is centered by that art, not by the box an instance has without its +/// document. +#[test] +fn placed_art_with_a_symbol_instance_is_centered_by_the_symbols_art() { + let mut s = session(); + let r = rect(&mut s, 300.0, 10.0, 100.0, 40.0); + let art = node(&s, r); + s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Off".into(), art: std::sync::Arc::new(art) }); + let layer = d.layers[0].id; + let inst = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((50.0, 50.0)); + d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Off".into(), xf })).unwrap(); + let inst = inst.0; + s.execute("brush.new", &json!({"type": "art", "name": "Stamp", "ids": [inst]})).unwrap(); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Stamp", "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap()); + let st = s.doc().unwrap(); + let b = st.doc.bounds_of(&[id], false).unwrap(); + assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 150.0).abs() < 1e-6, "{b:?}"); + assert!((b.width() - 100.0).abs() < 1e-6, "{b:?}"); +} + +/// A pattern brush with side, outer corner and start tiles, the side tile with a repeat frame +/// wider than its art: → its name. +fn framed_pattern_brush(s: &mut Session) -> String { + let side = rect(s, 0.0, 0.0, 20.0, 10.0); + let corner = rect(s, 0.0, 40.0, 10.0, 10.0); + let start = rect(s, 0.0, 80.0, 6.0, 10.0); + let name = s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "ids": [side.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let params = json!({ + "side": art_json(s, side), + "side_frame": Rect::new(-2.0, 0.0, 22.0, 10.0), + "outer_corner": art_json(s, corner), + "start": art_json(s, start), + }); + s.execute("brush.options", &json!({"name": name, "params": params})).unwrap(); + name +} + +/// `brush.placeArt` lays a pattern brush's tiles out left to right, each in a group named for its +/// tile, with an unpainted rectangle at the back of a tile with a repeat frame marking that frame. +#[test] +fn pattern_brushes_place_their_tiles_in_a_row() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap()); + let placed = node(&s, id); + let tiles: Vec<Node> = placed.children().unwrap().iter().map(|c| (**c).clone()).collect(); + let names: Vec<&str> = tiles.iter().map(|t| t.name.as_deref().unwrap_or("")).collect(); + assert_eq!(names, ["Side Tile", "Outer Corner Tile", "Start Tile"]); + let boxes: Vec<Rect> = tiles.iter().map(|t| t.geometric_bounds().unwrap()).collect(); + assert!(boxes.windows(2).all(|w| (w[1].x0 - w[0].x1 - 10.0).abs() < 1e-6), "10 pt apart, left to right: {boxes:?}"); + // The side tile: the frame's rectangle, unpainted, behind the art. + let side = tiles[0].children().unwrap(); + assert_eq!(side.len(), 2); + let marker = &side[0]; + assert!(marker.appearance.items.iter().all(|i| match i { + vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.is_none(), + vectorcraft_doc::AppearanceItem::Stroke(st) => st.paint.is_none(), + })); + let frame = marker.geometric_bounds().unwrap(); + assert!((frame.width() - 24.0).abs() < 1e-6 && (frame.height() - 10.0).abs() < 1e-6, "{frame:?}"); + assert_eq!(tiles[1].children().unwrap().len(), 1, "no frame, no rectangle"); +} + +/// `brush.replaceArt` reads the tiles `brush.placeArt` places back tile by tile, frames included: +/// every tile and the frame keep their sizes, and the frame keeps its place around the art. +#[test] +fn placed_pattern_tiles_go_back_into_the_brush_tile_by_tile() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let before = s.execute("brush.get", &json!({"name": name})).unwrap(); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [id.0]})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let after = s.execute("brush.get", &json!({"name": name})).unwrap(); + let size = |v: &Value| { + let n: Node = serde_json::from_value(v.clone()).unwrap(); + let b = n.geometric_bounds().unwrap(); + (b.width(), b.height()) + }; + for key in ["side", "outer_corner", "start"] { + let (a, b) = (size(&before[key]), size(&after[key])); + assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6, "{key}: {a:?} → {b:?}"); + } + assert!(after.get("end").is_none_or(Value::is_null) && after.get("inner_corner").is_none_or(Value::is_null)); + let frame: Rect = serde_json::from_value(after["side_frame"].clone()).unwrap(); + let art: Node = serde_json::from_value(after["side"].clone()).unwrap(); + let art = art.geometric_bounds().unwrap(); + assert!((frame.width() - 24.0).abs() < 1e-6 && (art.x0 - frame.x0 - 2.0).abs() < 1e-6, "{frame:?} around {art:?}"); + assert!(after["outer_corner_frame"].is_null() || after.get("outer_corner_frame").is_none()); +} + +/// Art that is not the tiles `brush.placeArt` places becomes a pattern brush's side tile, and the +/// other tiles stay; one tile group alone replaces only that tile. +#[test] +fn other_art_replaces_the_side_tile_of_a_pattern_brush() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let before = s.execute("brush.get", &json!({"name": name})).unwrap(); + let r = rect(&mut s, 100.0, 100.0, 30.0, 12.0); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [r.0]})).unwrap(); + let after = s.execute("brush.get", &json!({"name": name})).unwrap(); + let side: Node = serde_json::from_value(after["side"].clone()).unwrap(); + assert!(close(side.geometric_bounds().unwrap(), Rect::new(100.0, 100.0, 130.0, 112.0), 1e-6)); + assert!(after.get("side_frame").is_none_or(Value::is_null), "the old frame goes with the old art"); + assert_eq!((&after["outer_corner"], &after["start"]), (&before["outer_corner"], &before["start"])); + // One placed tile, its group dragged back alone: only the start tile changes. + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()); + let start = node(&s, id).children().unwrap()[2].clone(); + assert_eq!(start.name.as_deref(), Some("Start Tile")); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [start.id.0]})).unwrap(); + let last = s.execute("brush.get", &json!({"name": name})).unwrap(); + assert_eq!((&last["side"], &last["outer_corner"]), (&after["side"], &after["outer_corner"])); + let art: Node = serde_json::from_value(last["start"].clone()).unwrap(); + assert!(close(art.geometric_bounds().unwrap(), start.geometric_bounds().unwrap(), 1e-6), "the start tile is the placed one"); + assert!(art.name.is_none(), "the tile's name stays on the canvas"); +} + +/// `brush.replaceArt` gives a brush new art in one undo step: strokes that use it redraw with it, +/// or with `applyToStrokes: false` keep the brush as it was while a copy with the new art becomes +/// the current brush. A brush no stroke uses changes in place either way. +#[test] +fn replace_art_applies_to_strokes_or_leaves_them_on_the_old_brush() { + let mut s = session(); + let r = rect(&mut s, 10.0, 200.0, 40.0, 8.0); + s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap(); + let path = line(&mut s); + s.execute("brush.apply", &json!({"name": "Bar", "ids": [path.0]})).unwrap(); + let thin = brushed_bounds(&s, path).height(); + // A path painted with a brush made from the taller art: what the stroke should draw. + let tall = rect(&mut s, 10.0, 220.0, 40.0, 20.0); + s.execute("brush.new", &json!({"type": "art", "name": "Tall", "ids": [tall.0]})).unwrap(); + let reference = line(&mut s); + s.execute("brush.apply", &json!({"name": "Tall", "ids": [reference.0]})).unwrap(); + let want = brushed_bounds(&s, reference).height(); + assert!(want > thin * 2.0, "{want} against {thin}"); + // Apply to Strokes: the stroke redraws with the taller art. + let steps = undo_steps(&s); + let r = s.execute("brush.replaceArt", &json!({"name": "Bar", "ids": [tall.0]})).unwrap(); + assert_eq!(r["name"], "Bar"); + assert_eq!(undo_steps(&s), steps + 1); + assert!((brushed_bounds(&s, path).height() - want).abs() < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert!((brushed_bounds(&s, path).height() - thin).abs() < 1e-9, "undo puts the old art back"); + s.execute("edit.redo", &json!({})).unwrap(); + // Leave Strokes: the stroke keeps Bar as it was; Bar copy has the new art, after Bar, current. + let short = rect(&mut s, 10.0, 260.0, 40.0, 4.0); + let bar = s.execute("brush.get", &json!({"name": "Bar"})).unwrap(); + let r = s.execute("brush.replaceArt", &json!({"name": "Bar", "ids": [short.0], "applyToStrokes": false})).unwrap(); + assert_eq!(r["name"], "Bar copy"); + assert_eq!(brush_of(&s, path).as_deref(), Some("Bar")); + assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap(), bar); + assert!((brushed_bounds(&s, path).height() - want).abs() < 1e-6); + let copy: Node = serde_json::from_value(s.execute("brush.get", &json!({"name": "Bar copy"})).unwrap()["art"].clone()).unwrap(); + assert!((copy.geometric_bounds().unwrap().height() - 4.0).abs() < 1e-6); + let list = s.execute("brush.list", &json!({})).unwrap(); + assert_eq!(list["current"], "Bar copy"); + let names: Vec<&str> = list["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect(); + let at = names.iter().position(|n| *n == "Bar").unwrap(); + assert_eq!(names.get(at + 1), Some(&"Bar copy")); + // No stroke uses Bar copy: its art changes in place, with or without applying. + s.execute("brush.replaceArt", &json!({"name": "Bar copy", "ids": [tall.0], "applyToStrokes": false})).unwrap(); + assert!(s.execute("brush.get", &json!({"name": "Bar copy 2"})).is_err()); +} + +/// `brush.replaceArt` refuses a brush without art, an unknown brush, an empty selection, art with no +/// width and an `applyToStrokes` that is not a boolean, and changes nothing then. +#[test] +fn replace_art_refuses_what_it_cannot_take() { + let mut s = session(); + let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0); + let flat = s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap(); + let lib = s.execute("brush.list", &json!({})).unwrap(); + let steps = undo_steps(&s); + for (p, msg) in [ + (json!({"name": "3 pt. Round", "ids": [r.0]}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Bristle Round", "ids": [r.0]}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"), + (json!({"name": "Nope", "ids": [r.0]}), "no brush named `Nope`"), + (json!({"name": "Arrow", "ids": [flat]}), "the selected art has no width"), + (json!({"name": "Chain", "ids": [flat]}), "the selected art has no width"), + (json!({"name": "Arrow", "ids": [r.0], "applyToStrokes": "no"}), "`applyToStrokes` must be true or false"), + ] { + let e = s.execute("brush.replaceArt", &p).unwrap_err(); + assert!(e.to_string().contains(msg), "{p}: {e}"); + } + s.select(|_, sel| sel.clear()).unwrap(); + let e = s.execute("brush.replaceArt", &json!({"name": "Arrow"})).unwrap_err(); + assert!(e.to_string().contains("nothing selected"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.execute("brush.list", &json!({})).unwrap(), lib); +} + +/// An instance of a symbol whose art has no width is art with no width for `brush.new` and +/// `brush.replaceArt`, although an instance's box without its document has width. +#[test] +fn a_symbol_whose_art_has_no_width_makes_no_brush_art() { + let mut s = session(); + let flat = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap()); + let art = node(&s, flat); + s.execute("edit.clear", &json!({"ids": [flat.0]})).unwrap(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Flat".into(), art: std::sync::Arc::new(art) }); + let layer = d.layers[0].id; + let inst = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Flat".into(), xf: vectorcraft_geom::Affine::IDENTITY })) + .unwrap(); + assert!(node(&s, inst).geometric_bounds().is_some_and(|b| b.width() > 1.0), "the box an instance has without its document"); + for (cmd, p) in [("brush.new", json!({"type": "art", "ids": [inst.0]})), ("brush.replaceArt", json!({"name": "Arrow", "ids": [inst.0]}))] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(e.to_string().contains("the selected art has no width"), "{cmd}: {e}"); + } +} + +/// `brush.replaceArt` checks only the art it is given: a tile the pattern brush already has that +/// has no width does not stop another tile from being replaced. +#[test] +fn replace_art_checks_only_the_tiles_it_is_given() { + let mut s = session(); + let flat = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap()); + let end = art_json(&mut s, flat); + s.execute("brush.options", &json!({"name": "Chain", "params": {"end": end}})).unwrap(); + let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0); + s.execute("brush.replaceArt", &json!({"name": "Chain", "ids": [r.0]})).unwrap(); + let side: Node = serde_json::from_value(s.execute("brush.get", &json!({"name": "Chain"})).unwrap()["side"].clone()).unwrap(); + assert!(close(side.geometric_bounds().unwrap(), bounds(&s, r), 1e-6)); +} + +/// Tile `key` (`side`, `start`…) of pattern brush `name`. +fn tile_art(s: &mut Session, name: &str, key: &str) -> Node { + serde_json::from_value(s.execute("brush.get", &json!({"name": name})).unwrap()[key].clone()).unwrap() +} + +/// A pattern brush tile placed with `brush.placeArt` and given back with `brush.replaceArt` is the +/// art it was, not that art inside the tile's group, however many times it goes out and back. +#[test] +fn pattern_tiles_go_out_and_back_without_gaining_a_group() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let size = |n: &Node| { + let b = n.geometric_bounds().unwrap(); + (b.width(), b.height()) + }; + let first = tile_art(&mut s, &name, "side"); + assert!(matches!(first.kind, NodeKind::Path { .. }), "{:?}", first.kind); + for round in 1..=2 { + let id = s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap(); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [id]})).unwrap(); + let side = tile_art(&mut s, &name, "side"); + assert!(matches!(side.kind, NodeKind::Path { .. }), "round {round}: {:?}", side.kind); + let (a, b) = (size(&first), size(&side)); + assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6, "round {round}: {a:?} → {b:?}"); + } +} + +/// A tile group whose art was deleted, leaving only the rectangle that marks its frame, is art with +/// no width: the brush keeps its tile. +#[test] +fn a_tile_group_holding_only_its_frame_is_refused() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let before = s.execute("brush.get", &json!({"name": name})).unwrap(); + let id = NodeId(s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap()); + let side = node(&s, id).children().unwrap()[0].clone(); + assert_eq!(side.name.as_deref(), Some("Side Tile")); + let art = side.children().unwrap()[1].id; + s.execute("edit.clear", &json!({"ids": [art.0]})).unwrap(); + let steps = undo_steps(&s); + let e = s.execute("brush.replaceArt", &json!({"name": name, "ids": [side.id.0]})).unwrap_err(); + assert!(e.to_string().contains("the selected art has no width"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.execute("brush.get", &json!({"name": name})).unwrap(), before); +} + +/// Two groups named for the same tile: the frontmost one is the tile's art. +#[test] +fn the_frontmost_group_named_for_a_tile_is_that_tile() { + let mut s = session(); + let name = framed_pattern_brush(&mut s); + let back = rect(&mut s, 10.0, 10.0, 20.0, 10.0); + let front = rect(&mut s, 10.0, 40.0, 30.0, 10.0); + let (back, front) = (node(&s, back), node(&s, front)); + s.execute("edit.clear", &json!({"ids": [back.id.0, front.id.0]})).unwrap(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let tile = |d: &mut Document, n: Node| { + let mut g = Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]); + g.name = Some("Start Tile".into()); + std::sync::Arc::new(g) + }; + let tiles = vec![tile(d, back), tile(d, front)]; + let both = Node::group(d.alloc_id(), tiles); + let both_id = both.id; + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, both).unwrap(); + s.execute("brush.replaceArt", &json!({"name": name, "ids": [both_id.0]})).unwrap(); + let start = tile_art(&mut s, &name, "start"); + assert!((start.geometric_bounds().unwrap().width() - 30.0).abs() < 1e-6, "{:?}", start.geometric_bounds()); +} + +/// Type is art for `brush.replaceArt` as it is for `brush.new`: taken as it is. +#[test] +fn replace_art_takes_type_as_brush_new_does() { + let mut s = session(); + let t = s.execute("text.create", &json!({"x": 20, "y": 60, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap(); + let want = art_json(&mut s, NodeId(t)); + s.execute("brush.replaceArt", &json!({"name": "Arrow", "ids": [t]})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["art"], want); + let made = s.execute("brush.new", &json!({"type": "art", "ids": [t]})).unwrap()["name"].as_str().unwrap().to_string(); + assert_eq!(s.execute("brush.get", &json!({"name": made})).unwrap()["art"], want); +} + #[test] fn brush_options_rename_duplicate_and_delete_update_strokes() { let mut s = session(); @@ -1951,3 +2312,63 @@ fn symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several() { } assert_eq!(names(&s).len(), 6); } + +/// Symbols panel › Sort by Name: the document's symbols in name order, ignoring case, with names +/// that differ only in case kept in their order, as one undo step that keeps the current symbol +/// and every instance; sorting symbols already in order adds no undo step. +#[test] +fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() { + let mut s = session(); + let names = |s: &mut Session| -> Vec<String> { + let list = s.execute("symbol.list", &json!({})).unwrap(); + list["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap_or_default().to_string()).collect() + }; + let current = |s: &mut Session| s.execute("symbol.list", &json!({})).unwrap()["current"].clone(); + let made = ["leaf", "Badge", "apple", "Leaf", "Zed"]; + for (i, name) in made.into_iter().enumerate() { + rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0); + s.execute("symbol.new", &json!({"name": name})).unwrap(); + } + // No current symbol stored: the first one is current. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol"); + assert_eq!(current(&mut s), "leaf"); + let instances = |s: &Session| { + let mut v = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + v.push((n.id, symbol.clone())); + } + }); + v + }; + let placed = instances(&s); + assert_eq!(placed.len(), 5); + let before = s.doc().unwrap().history.undo.len(); + s.execute("symbol.sortByName", &json!({})).unwrap(); + assert_eq!(names(&mut s), ["apple", "Badge", "leaf", "Leaf", "Zed"]); + assert_eq!(current(&mut s), "leaf", "the current symbol stays current"); + assert_eq!(instances(&s), placed, "every instance keeps its symbol"); + assert_eq!(s.doc().unwrap().history.undo.len(), before + 1, "one undo step"); + // Already in order: nothing changes and no undo step is added. + let revision = s.doc().unwrap().revision; + s.execute("symbol.sortByName", &json!({})).unwrap(); + assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision), (before + 1, revision)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&mut s), made); + assert_eq!(current(&mut s), "leaf"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(names(&mut s), ["apple", "Badge", "leaf", "Leaf", "Zed"]); + // An explicitly current symbol stays current too. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "Zed"})).unwrap(); + s.execute("symbol.sortByName", &json!({})).unwrap(); + assert_eq!(current(&mut s), "Zed"); + // Run as a batch step it sorts as well, and with no symbols it adds no undo step. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("command.batch", &json!({"commands": [{"command": "symbol.sortByName", "params": {}}]})).unwrap(); + assert_eq!(names(&mut s), ["apple", "Badge", "leaf", "Leaf", "Zed"]); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let before = s.doc().unwrap().history.undo.len(); + s.execute("symbol.sortByName", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), before); +} diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 3ed51e3c38..0fc2bcb476 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -2945,6 +2945,120 @@ fn merged_live_paint_groups_keep_the_bottom_groups_gap_options() { assert_eq!(merged(off, json!({"detect": false})), GapOptions { detect: false, size: GapSize::Custom(12.0), color: blue }); } +#[test] +fn live_paint_bucket_drag_fills_multiple_faces() { + let mut s = session(); + let g = live(&mut s); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0)); + let before = s.doc().unwrap().doc.clone(); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + // Skip the middle face between pointer events, as can happen in a fast drag. + s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + let gn = node(&s, g); + for x in [25.0, 75.0, 125.0] { + let f = vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap(); + assert_eq!(f.appearance.fill_paint(), s.paint.fill, "dragged face at {x}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "one Undo restores every face"); + s.pointer(&PointerEvent::new(PointerKind::Move, 125.0, 50.0), v).unwrap(); + assert!(!s.overlays(v).is_empty(), "hover still highlights a face"); + assert_eq!(s.doc().unwrap().doc, before, "hover does not paint"); +} + +#[test] +fn live_paint_bucket_drag_crosses_thin_grid_cells_and_can_cancel() { + for (deferred, cancel) in [(false, false), (false, true), (true, false)] { + let mut s = session(); + let ids = [rect(&mut s, 0.0, 0.0, 150.0, 100.0), line(&mut s, (50.0, 0.0), (50.0, 100.0)), line(&mut s, (50.25, 0.0), (50.25, 100.0))]; + s.execute("select.set", &json!({"ids": ids.map(|i| i.0)})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.prefs.real_time_drawing = !deferred; + s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap(); + if cancel { + assert!(s.tool_busy()); + assert!(s.tool_claims_key(ToolKey::Escape, v)); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + assert!(!s.tool_busy()); + assert!(!s.tool_claims_key(ToolKey::Escape, v)); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + if !cancel { + let g = s.doc().unwrap().selection.objects[0]; + let gn = node(&s, g); + for x in [25.0, 50.125, 125.0] { + let f = vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap(); + assert_eq!(f.appearance.fill_paint(), s.paint.fill, "deferred={deferred}, x={x}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc == before, "deferred={deferred}, cancel={cancel}: original paths and selection art must be restored"); + } +} + +#[test] +fn live_paint_bucket_long_drag_keeps_late_turns_and_release_as_one_undo() { + for cancel in [false, true] { + let mut s = session(); + let ids = [rect(&mut s, 0.0, 0.0, 150.0, 100.0), line(&mut s, (50.0, 0.0), (50.0, 100.0)), line(&mut s, (100.0, 0.0), (100.0, 100.0))]; + s.execute("select.set", &json!({"ids": ids.map(|id| id.0)})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.prefs.real_time_drawing = false; + s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + for i in 1..4096 { + s.pointer(&PointerEvent::new(PointerKind::Drag, 25.0 + f64::from(i) / 10000.0, 50.0), v).unwrap(); + } + // Turn around the middle face after the chunk limit, then enter the right face on Up. + for (x, y) in [(25.0, 150.0), (125.0, 150.0)] { + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + } + if cancel { + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + if !cancel { + let g = s.doc().unwrap().selection.objects[0]; + let gn = node(&s, g); + for x in [25.0, 125.0] { + assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().appearance.fill_paint(), s.paint.fill); + } + assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(75.0, 50.0)).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE)); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc == before, "long drag is one cancellable undo step"); + } +} + +#[test] +fn live_paint_bucket_drag_rejects_invalid_points_atomically() { + let mut s = session(); + let g = live(&mut s); + let before = s.doc().unwrap().doc.clone(); + for points in + [json!([]), json!([[26.0, 50.0]]), json!([[25.0, 50.0], [null, 0]]), json!([[25.0, 50.0], [1e30, 0]]), json!(vec![[25.0, 50.0]; 4097])] + { + assert!(s.execute("livePaint.fill", &json!({"group": g.0, "point": [25.0, 50.0], "points": points})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + } + for continuation in [json!(null), json!([[[26.0, 50.0], [125.0, 50.0]]]), json!([vec![[25.0, 50.0]; 4097]])] { + assert!( + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25.0, 50.0], "points": [[25.0, 50.0]], "continuation": continuation})) + .is_err() + ); + assert_eq!(s.doc().unwrap().doc, before); + } +} + #[test] fn live_paint_bucket_tool_fills_face() { let mut s = session(); diff --git a/crates/engine/src/tests/caret_kerning.rs b/crates/engine/src/tests/caret_kerning.rs new file mode 100644 index 0000000000..dca3519cb1 --- /dev/null +++ b/crates/engine/src/tests/caret_kerning.rs @@ -0,0 +1,183 @@ +//! Kerning at the Type tool's caret at the start of a line (#5111): with no character on the line +//! before the caret, `type.step`, `type.resetTracking` and the Kerning field set the space before +//! the character after it (`kerningBefore`), as one undo step, and the character moves. + +use serde_json::json; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, t: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": t, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("not text") }; + (**t).clone() +} + +fn style_at(s: &Session, id: NodeId, byte: usize) -> CharStyle { + vectorcraft_text::edit::style_at(&obj(s, id).runs, byte + 1) +} + +/// Where glyph `byte` is drawn along its line, in text space. +fn drawn_x(s: &Session, id: NodeId, byte: usize) -> f64 { + let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &obj(s, id)); + l.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4] +} + +/// The Type tool editing `id` (made by [`text`]) with its caret at byte `caret`. +fn caret_in(s: &mut Session, id: NodeId, caret: usize) -> ViewInfo { + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 102.0, 95.0), v).unwrap(); + } + assert_eq!(s.tool_options()["editing"], json!(id.0), "editing the text"); + s.set_tool_option("select", &json!({"start": caret, "end": caret})); + v +} + +fn step_at(s: &mut Session, id: NodeId, caret: usize, by: i32) -> serde_json::Value { + s.execute("type.step", &json!({"id": id.0, "start": caret, "end": caret, "attribute": "kerning", "by": by})).unwrap() +} + +#[test] +fn a_step_at_the_start_of_the_text_moves_the_first_character() { + let mut s = session(); + let id = text(&mut s, "AV"); + let inc = s.prefs.tracking_increment; + let (a, v) = (drawn_x(&s, id, 0), drawn_x(&s, id, 1)); + assert_eq!(step_at(&mut s, id, 0, 1)["ids"], json!([id.0])); + let st = style_at(&s, id, 0); + assert_eq!((st.kerning_before, st.kerning), (inc, None), "the space before A, not after it"); + // A step of `inc` thousandths of the 20 pt em moves both letters along the line. + let moved = inc / 1000.0 * 20.0; + assert!((drawn_x(&s, id, 0) - a - moved).abs() < 1e-6 && (drawn_x(&s, id, 1) - v - moved).abs() < 1e-6); + // A negative step goes back towards the line's start, past it. + step_at(&mut s, id, 0, -3); + assert_eq!(style_at(&s, id, 0).kerning_before, -2.0 * inc); + assert!((drawn_x(&s, id, 0) - a + 2.0 * moved).abs() < 1e-6); + // One undo step each. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, inc); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, 0.0); + assert!((drawn_x(&s, id, 0) - a).abs() < 1e-6); +} + +#[test] +fn inside_a_line_a_step_still_kerns_the_character_before_the_caret() { + let mut s = session(); + let id = text(&mut s, "AV"); + step_at(&mut s, id, 1, 1); + let (a, v) = (style_at(&s, id, 0), style_at(&s, id, 1)); + assert_eq!((a.kerning_before, v.kerning_before, v.kerning), (0.0, 0.0, None)); + assert!(a.kerning.is_some(), "the pair after A"); +} + +#[test] +fn the_start_of_a_paragraph_or_after_a_forced_line_break_kerns_the_character_after_it() { + let mut s = session(); + let inc = s.prefs.tracking_increment; + let id = text(&mut s, "One\nTwo"); + let t = drawn_x(&s, id, 4); + step_at(&mut s, id, 4, 1); + assert_eq!((style_at(&s, id, 3).kerning, style_at(&s, id, 4).kerning_before), (None, inc), "not the line break's kerning"); + assert!(drawn_x(&s, id, 4) > t, "T moves"); + let forced = text(&mut s, "One\u{2028}Two"); + let after = "One\u{2028}".len(); + step_at(&mut s, forced, after, 1); + assert_eq!((style_at(&s, forced, 3).kerning, style_at(&s, forced, after).kerning_before), (None, inc)); +} + +#[test] +fn an_empty_line_has_nothing_to_kern() { + let mut s = session(); + let id = text(&mut s, "One\n\nTwo"); + let before = obj(&s, id).runs; + assert_eq!(step_at(&mut s, id, 4, 1)["ids"], json!([])); + assert_eq!(obj(&s, id).runs, before); + // Nor does the end of text after a line break. + let end = text(&mut s, "One\n"); + assert_eq!(step_at(&mut s, end, 4, 1)["ids"], json!([])); +} + +#[test] +fn reset_at_the_start_of_a_line_clears_the_space_before_and_a_full_reset_clears_it_too() { + let mut s = session(); + let id = text(&mut s, "AV"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": -40, "tracking": 100})).unwrap(); + step_at(&mut s, id, 0, 2); + assert_ne!(style_at(&s, id, 0).kerning_before, 0.0); + // At the caret before A only the space before A goes; A keeps its kerning after it. + caret_in(&mut s, id, 0); + s.execute("type.resetTracking", &json!({})).unwrap(); + let st = style_at(&s, id, 0); + assert_eq!((st.kerning_before, st.kerning, st.tracking), (0.0, Some(-40.0), 100.0)); + step_at(&mut s, id, 0, 2); + s.execute("type.resetTracking", &json!({"ids": [id.0]})).unwrap(); + let st = style_at(&s, id, 0); + assert_eq!((st.kerning_before, st.kerning, st.tracking), (0.0, None, 0.0), "all manual kerning"); +} + +#[test] +fn set_range_style_sets_the_space_before() { + let mut s = session(); + let id = text(&mut s, "AV"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerningBefore": 50})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, 50.0); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerningBefore": 20000})).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, 10000.0, "kerning's limits"); + assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "kerningBefore": "auto"})).is_err()); +} + +/// The Type tool: Alt+← at the caret before the first character kerns it, and Alt+→ back. +#[test] +fn alt_arrows_at_the_caret_before_the_first_character_kern_it() { + let mut s = session(); + let inc = s.prefs.tracking_increment; + let id = text(&mut s, "Hello"); + let v = caret_in(&mut s, id, 0); + let alt = Mods { alt: true, ..Mods::default() }; + s.tool_key(ToolKey::Left, alt, v).unwrap(); + assert_eq!((style_at(&s, id, 0).kerning_before, style_at(&s, id, 0).kerning), (-inc, None)); + s.tool_key(ToolKey::Right, alt, v).unwrap(); + s.tool_key(ToolKey::Right, alt, v).unwrap(); + assert_eq!(style_at(&s, id, 0).kerning_before, inc); +} + +/// The Eyedropper copies how type looks, not where a line starts: a sample from a first character +/// with a space before it leaves the target's first character where it was. +#[test] +fn the_eyedropper_keeps_the_targets_space_before() { + let mut s = session(); + let src = text(&mut s, "Source"); + s.execute("text.setRangeStyle", &json!({"id": src.0, "start": 0, "end": 1, "kerningBefore": 300, "tracking": 50})).unwrap(); + let dst = text(&mut s, "Target"); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let st = style_at(&s, dst, 0); + assert_eq!((st.tracking, st.kerning_before), (50.0, 0.0), "the tracking goes, the space before doesn't"); +} + +/// A character style captured from a line's first character leaves its space before out, and a +/// style can't be given one: it would space the first character of every paragraph set in it. +#[test] +fn a_character_style_leaves_the_space_before_out() { + let mut s = session(); + let id = text(&mut s, "Source"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerningBefore": 300, "tracking": 50})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "id": id.0})).unwrap(); + let attrs = s.doc().unwrap().doc.char_styles[0].attrs.clone(); + assert_eq!(attrs.get("tracking"), Some(&json!(50.0))); + assert!(!attrs.contains_key("kerningBefore"), "{attrs:?}"); + let err = s.execute("charStyle.new", &json!({"name": "Spaced", "attrs": {"kerningBefore": 100}})).unwrap_err(); + assert!(err.to_string().contains("kerningBefore"), "{err}"); +} diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 24d6d387db..b5ebf080ea 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -710,12 +710,133 @@ fn in_place_pastes_go_onto_the_artboard_named() { assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 15.0), "{cmd}"); let ids = ids_of(&s.execute(cmd, &json!({})).unwrap()); assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[0].x0 + 10.0, boards[0].y0 + 15.0), "{cmd} without one"); - // An artboard that isn't there: where they were. - let ids = ids_of(&s.execute(cmd, &json!({"artboard": 9})).unwrap()); - assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[0].x0 + 10.0, boards[0].y0 + 15.0), "{cmd} on no artboard"); + // An artboard that isn't there, or a value that isn't an index: an error, and nothing pasted. + let before = doc(&s).clone(); + for bad in [json!(9), json!(-1), json!(1.5), json!("1")] { + assert!(s.execute(cmd, &json!({"artboard": bad})).is_err(), "{cmd} with artboard {bad}"); + } + assert_eq!(doc(&s), &before, "{cmd}"); } } +/// Paste in Place, in Front and in Back onto several artboards (the Artboard tool's selection, which +/// the app passes as `artboards`): a copy on each, where the objects were on the artboard they were +/// copied from, the copies in artboard order and in their own paint order, all selected, in one undo +/// step. +#[test] +fn in_place_pastes_put_a_copy_on_each_artboard_named() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 4})).unwrap(); + let boards: Vec<Rect> = doc(&s).artboards.iter().map(|a| a.rect).collect(); + let a = rect(&mut s, boards[1].x0 + 10.0, boards[1].y0 + 15.0, 20.0, 20.0); + let b = rect(&mut s, boards[1].x0 + 50.0, boards[1].y0 + 5.0, 10.0, 10.0); + copy(&mut s, &[a, b]); + for cmd in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + let undo = s.doc().unwrap().history.undo.len(); + let before = doc(&s).clone(); + let ids = ids_of(&s.execute(cmd, &json!({"artboards": [3, 0]})).unwrap()); + assert_eq!(ids.len(), 4, "{cmd}: two objects on each of two artboards"); + for (pair, board) in ids.chunks(2).zip([boards[0], boards[3]]) { + assert_eq!(doc(&s).bounds_of(&pair[..1], false).unwrap().origin(), Point::new(board.x0 + 10.0, board.y0 + 15.0), "{cmd}"); + assert_eq!(doc(&s).bounds_of(&pair[1..], false).unwrap().origin(), Point::new(board.x0 + 50.0, board.y0 + 5.0), "{cmd}"); + } + let layer: Vec<NodeId> = doc(&s).layers[0].children().into_iter().flatten().map(|n| n.id).collect(); + let at: Vec<usize> = ids.iter().map(|id| layer.iter().position(|n| n == id).unwrap()).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{cmd}: in paint order, artboard by artboard: {at:?}"); + assert_eq!(s.doc().unwrap().selection.in_paint_order(doc(&s)), ids, "{cmd}: the copies are selected"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{cmd}: one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), &before, "{cmd}: undo takes every copy away"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(doc(&s).layers[0].children().into_iter().flatten().count(), layer.len(), "{cmd}: redo"); + // `artboard` wins over `artboards`. + let ids = ids_of(&s.execute(cmd, &json!({"artboard": 2, "artboards": [0, 3]})).unwrap()); + assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 5.0), "{cmd}"); + // A list that is empty, names an artboard the document lacks or names one twice, or isn't a + // list: an error, and nothing pasted. + let before = doc(&s).clone(); + for bad in [json!([]), json!([0, 4]), json!([1, 1]), json!([0, -1]), json!(2), json!("0,1")] { + assert!(s.execute(cmd, &json!({"artboards": bad})).is_err(), "{cmd} with artboards {bad}"); + } + assert!(s.execute(cmd, &json!({"artboard": 1, "artboards": [7]})).is_err(), "{cmd}: a bad list with `artboard`"); + assert_eq!(doc(&s), &before, "{cmd}"); + } +} + +/// With the Artboard tool chosen and several artboards selected, Paste in Place, in Front and in +/// Back put a copy on each without naming them; the journal notes them, so a replay pastes on the +/// same artboards, and a recorded action leaves them out. With one selected, or another tool, the +/// objects go where they were. +#[test] +fn in_place_pastes_follow_the_artboard_tool_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + let boards: Vec<Rect> = doc(&s).artboards.iter().map(|a| a.rect).collect(); + let r = rect(&mut s, boards[0].x0 + 10.0, boards[0].y0 + 15.0, 20.0, 20.0); + copy(&mut s, &[r]); + let origins = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| doc(s).bounds_of(&[*id], false).unwrap().origin()).collect::<Vec<_>>(); + let on = |b: &[usize]| b.iter().map(|i| Point::new(boards[*i].x0 + 10.0, boards[*i].y0 + 15.0)).collect::<Vec<_>>(); + s.select_tool("artboard", ViewInfo::default()).unwrap(); + for cmd in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + s.set_tool_option("selected", &json!([2, 1])); + let start = s.journal.len(); + let ids = ids_of(&s.execute(cmd, &json!({})).unwrap()); + assert_eq!(origins(&s, &ids), on(&[1, 2]), "{cmd}"); + assert_eq!(s.journal.since(start).last().map(|(_, p)| p["artboards"].clone()), Some(json!([1, 2])), "{cmd}: journaled"); + assert!(s.journal_for_action(start).iter().all(|(_, p)| p.get("artboards").is_none()), "{cmd}: not in an action"); + // A stale index in the tool's selection is passed over. + s.set_tool_option("selected", &json!([0, 9])); + let ids = ids_of(&s.execute(cmd, &json!({})).unwrap()); + assert_eq!(origins(&s, &ids), on(&[0]), "{cmd}: one left"); + s.set_tool_option("selected", &json!([1])); + let ids = ids_of(&s.execute(cmd, &json!({})).unwrap()); + assert_eq!(origins(&s, &ids), on(&[0]), "{cmd}: one selected, where it was"); + } + s.set_tool_option("selected", &json!([1, 2])); + s.select_tool("selection", ViewInfo::default()).unwrap(); + let ids = ids_of(&s.execute("edit.pasteInPlace", &json!({})).unwrap()); + assert_eq!(origins(&s, &ids), on(&[0]), "another tool: where it was"); +} + +/// Art copied from no artboard onto several: it keeps its place on the first and its offset to the +/// first on the others. Guides alone go on each artboard named. +#[test] +fn in_place_pastes_onto_several_artboards_of_art_off_them_and_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + let boards: Vec<Rect> = doc(&s).artboards.iter().map(|a| a.rect).collect(); + let r = rect(&mut s, boards[0].x0 - 100.0, boards[0].y0 + 15.0, 20.0, 20.0); + copy(&mut s, &[r]); + assert_eq!(s.clipboard.source_artboard, None); + let ids = ids_of(&s.execute("edit.pasteInPlace", &json!({"artboards": [1, 2]})).unwrap()); + let at: Vec<Point> = ids.iter().map(|id| doc(&s).bounds_of(&[*id], false).unwrap().origin()).collect(); + let first = Point::new(boards[0].x0 - 100.0, boards[0].y0 + 15.0); + assert_eq!(at, [first, first + (boards[2].origin() - boards[1].origin())]); + // Guides alone, copied from artboard 1: one on each artboard named, 30 pt into it. + s.execute("guide.add", &json!({"vertical": true, "pos": boards[0].x0 + 30.0})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let r = s.execute("edit.pasteInFront", &json!({"artboards": [1, 2]})).unwrap(); + assert_eq!(r["guides"], 2); + let mut guides: Vec<f64> = doc(&s).ruler_guides().iter().map(|g| g.pos).collect(); + guides.sort_by(f64::total_cmp); + assert_eq!(guides, [boards[0].x0 + 30.0, boards[1].x0 + 30.0, boards[2].x0 + 30.0]); +} + +/// Artboards on the clipboard come back once, where they were, whichever artboards are named. +#[test] +fn in_place_pastes_of_copied_artboards_ignore_the_artboards_named() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("artboard.copy", &json!({"index": 0, "art": true})).unwrap(); + let r = s.execute("edit.pasteInPlace", &json!({"artboards": [1, 2]})).unwrap(); + assert_eq!(r["artboards"], json!([3])); + assert_eq!(ids_of(&r).len(), 1); + assert_eq!(doc(&s).artboards[3].rect, doc(&s).artboards[0].rect); +} + /// Art copied from beside the artboards goes back where it was, whichever artboard is active (#1924). #[test] fn in_place_pastes_of_art_off_the_artboards_stay_where_it_was() { diff --git a/crates/engine/src/tests/colorguide.rs b/crates/engine/src/tests/colorguide.rs index 1033edf674..6213b202cd 100644 --- a/crates/engine/src/tests/colorguide.rs +++ b/crates/engine/src/tests/colorguide.rs @@ -60,6 +60,18 @@ fn harmony_refuses_steps_or_amount_that_is_not_a_number() { assert_eq!(r["grid"][0].as_array().unwrap().len(), 9, "a null is read as a key left out"); } +/// The Color Guide refuses a `rule` or `variation` that is not a string; a `variation` such as 5 +/// would otherwise be dropped and the default variation used. +#[test] +fn harmony_refuses_rule_or_variation_that_is_not_a_string() { + let mut s = Session::new(); + for p in [json!({"color": "#ff0000", "rule": 5}), json!({"color": "#ff0000", "rule": "triad", "variation": 5})] { + let e = s.execute("color.harmony", &p).unwrap_err().to_string(); + assert!(e.contains("must be a string"), "{p}: {e}"); + } + s.execute("color.harmony", &json!({"color": "#ff0000", "rule": "triad", "variation": null})).unwrap(); +} + #[test] fn new_swatch_saves_several_colours_in_one_step() { let mut s = session(); diff --git a/crates/engine/src/tests/constrain_tools.rs b/crates/engine/src/tests/constrain_tools.rs index 6a8317cfeb..41acc54172 100644 --- a/crates/engine/src/tests/constrain_tools.rs +++ b/crates/engine/src/tests/constrain_tools.rs @@ -78,7 +78,7 @@ fn constrain_angle_turns_the_arrow_keys() { let g = s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap()["index"].as_u64().unwrap(); s.execute("guide.select", &json!({"indexes": [g]})).unwrap(); s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); - let pos = s.doc().unwrap().doc.guides[g as usize].pos; + let pos = s.doc().unwrap().doc.ruler_guides()[g as usize].pos; assert!(close(pos, 60.0), "a vertical guide moves 10 right: {pos}"); } @@ -115,6 +115,9 @@ fn constrain_angle_draws_boxes_along_the_turned_axes() { let mut s = new_doc(); set_pref(&mut s, "constrainAngle", json!(90)); for tool in ["rectangle", "ellipse"] { + // The shape drawn before stays selected, and a press on its box's corner handle would + // scale it instead of drawing. + s.execute("select.none", &json!({})).unwrap(); s.select_tool(tool, ViewInfo::default()).unwrap(); // 60 right and 20 down on the page: along axes turned 90°, 20 wide and 60 high. gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]); @@ -167,7 +170,7 @@ fn constrain_angle_keeps_guides_selected_with_art_on_the_page_axes() { let h = s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap()["index"].as_u64().unwrap() as usize; s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); s.execute("guide.select", &json!({"indexes": [v, h], "toggle": true})).unwrap(); - let pos = |s: &Session| s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect::<Vec<_>>(); + let pos = |s: &Session| s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::<Vec<_>>(); let at = centre(&s, id); s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); assert_eq!(centre(&s, id) - at, Vec2::new(0.0, -10.0), "the art moves along the turned axis"); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index fcf9b63636..ea10df64b5 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3146,7 +3146,7 @@ fn shift_reshapes_the_closing_segment_of_a_rotated_square_and_undoes() { fn pen_drag_from_the_first_anchor_closes_the_path() { // #501: closing a path by dragging out of its first anchor flickered between a close and a new // path, and released at the wrong moment left the shape open. The press decides: the drag - // shapes the closing curve, symmetric, and the release closes the path wherever it ends. + // shapes the closing curve, and the release closes the path wherever it ends. let none = Mods::default(); let v = view(); let mut s = session(); @@ -3167,13 +3167,119 @@ fn pen_drag_from_the_first_anchor_closes_the_path() { let sp = &path(&s, id).subpaths[0]; assert!(sp.closed && sp.anchors.len() == 3, "{sp:?}"); let a = sp.anchors[0]; - assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(160.0, 252.0)), "symmetric"); + assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(100.0, 300.0)), "only the closing segment curves"); assert_eq!(paths(&s).len(), 1); // The next click starts a new path. gesture(&mut s, &[(500.0, 500.0)], none); assert_eq!(paths(&s).len(), 2); } +/// #6634: closing a path by dragging on its first anchor does not give that anchor symmetric +/// handles. Its incoming handle mirrors the pointer; its outgoing handle stays where it is on a +/// corner, so the first segment keeps its shape, and on a smooth anchor turns to stay in line at +/// its own length. Alt keeps the outgoing handle where it was when Alt went down, Shift keeps the +/// drag to 45° steps, and a click leaves the anchor a corner with the closing segment straight +/// into it. Each close is one undo step. +#[test] +fn pen_closing_drag_does_not_make_the_first_anchor_symmetric() { + use vectorcraft_geom::AnchorKind; + let (none, alt, shift) = (Mods::default(), Mods { alt: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() }); + let v = view(); + // Draws a path from (100, 300), dragged out to `start` when given (a smooth anchor), through + // (200, 200) and (300, 300), and returns it with its first anchor as drawn. + let draw = |s: &mut Session, start: Option<(f64, f64)>| { + s.select_tool("pen", v).unwrap(); + let first = match start { + Some(out) => vec![(100.0, 300.0), out], + None => vec![(100.0, 300.0)], + }; + gesture(s, &first, none); + gesture(s, &[(200.0, 200.0)], none); + gesture(s, &[(300.0, 300.0)], none); + let id = s.doc().unwrap().selection.objects[0]; + let anchor = path(s, id).subpaths[0].anchors[0]; + (id, anchor) + }; + let first = |s: &Session, id: NodeId| { + let sp = &path(s, id).subpaths[0]; + assert!(sp.closed, "{sp:?}"); + sp.anchors[0] + }; + + // A corner: the first segment stays straight however the drag turns. + let mut s = session(); + let (id, before) = draw(&mut s, None); + assert_eq!(gesture(&mut s, &[(100.0, 300.0), (80.0, 250.0), (60.0, 200.0)], none), 1, "one undo step"); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(140.0, 400.0), before.h_out, AnchorKind::Corner), "{a:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!path(&s, id).subpaths[0].closed, "the undo opens the path again"); + + // A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 50. + let mut s = session(); + let (id, before) = draw(&mut s, Some((150.0, 300.0))); + assert_eq!((before.h_out, before.kind), (Point::new(150.0, 300.0), AnchorKind::Smooth)); + gesture(&mut s, &[(100.0, 300.0), (100.0, 250.0), (100.0, 200.0)], none); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(100.0, 400.0), AnchorKind::Smooth), "{a:?}"); + assert!(near(a.h_out, Point::new(100.0, 250.0)), "in line, at its own length: {a:?}"); + + // Alt held from the press: a corner, its outgoing handle where it was. + let mut s = session(); + let (id, before) = draw(&mut s, Some((150.0, 300.0))); + gesture(&mut s, &[(100.0, 300.0), (100.0, 250.0), (100.0, 200.0)], alt); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(100.0, 400.0), before.h_out, AnchorKind::Corner), "{a:?}"); + + // Alt pressed mid-drag: the outgoing handle stays where the drag had turned it. + let mut s = session(); + let (id, _) = draw(&mut s, Some((150.0, 300.0))); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 200.0).with_mods(alt), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 200.0).with_mods(alt), v).unwrap(); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(70.0, 400.0), AnchorKind::Corner), "{a:?}"); + assert!(near(a.h_out, Point::new(100.0, 250.0)), "{a:?}"); + + // Shift: the drag keeps to 45° steps (straight up here), at the pointer's distance from the + // anchor, mirrored into the incoming handle. + let mut s = session(); + let (id, before) = draw(&mut s, None); + gesture(&mut s, &[(100.0, 300.0), (95.0, 250.0), (90.0, 200.0)], shift); + let a = first(&s, id); + assert!(near(a.h_in, Point::new(100.0, 300.0 + 10f64.hypot(100.0))) && a.h_out == before.h_out, "{a:?}"); + + // A click: the closing segment comes straight in, and a smooth anchor keeps its outgoing + // handle and becomes a corner. + let mut s = session(); + let (id, before) = draw(&mut s, Some((150.0, 300.0))); + assert_eq!(gesture(&mut s, &[(100.0, 300.0)], none), 1); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(100.0, 300.0), before.h_out, AnchorKind::Corner), "{a:?}"); +} + +/// Close Path's `in` moves the first anchor's incoming handle as Move Direction Handle does, and +/// `out` places its outgoing handle, making it a corner; `out` that is not [x, y] is refused. +#[test] +fn close_path_places_the_first_anchors_handles() { + use vectorcraft_geom::AnchorKind; + let mut s = session(); + let id = curve(&mut s); + let a = path(&s, id).subpaths[0].anchors[0]; + assert!(a.has_out() && a.kind == AnchorKind::Corner, "{a:?}"); + for h in [json!("1, 2"), json!([1]), json!([1, "2"])] { + refuses_with(&mut s, "path.close", &json!({"id": id.0, "out": h}), "`out` must be [x, y]"); + } + s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0]})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), a.h_out, AnchorKind::Corner), "a corner keeps its outgoing handle"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0], "out": [120.0, 60.0]})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), Point::new(120.0, 60.0), AnchorKind::Corner)); +} + #[test] fn pen_with_alt_converts_the_anchors_of_the_path_being_drawn() { // #504: while drawing, Alt-click on a smooth anchor of the path makes it a corner and Alt-drag diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index f4ae97bb14..c5ef8a1949 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -432,6 +432,30 @@ fn redefining_the_symbol_keeps_the_changes_whose_objects_remain() { assert_eq!(overrides(&s, inst), 0); } +#[test] +fn redefining_the_symbol_drops_paints_its_new_objects_do_not_draw() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let p = json!({"id": inst.0, "path": [1], "fill": "#ff0000", "stroke": "#ff0000", "opacity": 50}); + s.execute("symbol.instance.setAppearance", &p).unwrap(); + // The second object is now an image, which draws no fill or stroke of its own. + let a = square(&mut s, 10.0); + place_image(&mut s); + let image = top(&s); + s.execute("symbol.update", &json!({"name": "Pair", "ids": [a.0, image.0]})).unwrap(); + let o = node(&s, inst).extras().symbol_overrides.clone(); + assert_eq!(o.len(), 1, "the opacity change stays: {o:?}"); + assert_eq!((&o[0].fill, &o[0].stroke, o[0].opacity), (&None, &None, Some(0.5))); + // A change of paint alone goes with its paint: the first object is now a blend. + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [0], "stroke": "#ff0000"})).unwrap(); + let (b, c) = (square(&mut s, 10.0), square(&mut s, 60.0)); + let blend = id(&s.execute("object.blend.make", &json!({"ids": [b.0, c.0], "steps": 1})).unwrap()); + let d = square(&mut s, 120.0); + s.execute("symbol.update", &json!({"name": "Pair", "ids": [blend.0, d.0]})).unwrap(); + let o = node(&s, inst).extras().symbol_overrides.clone(); + assert_eq!(o.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [vec![1]], "{o:?}"); +} + #[test] fn replace_symbol_drops_the_changes_made_for_the_old_symbol() { let mut s = session(); @@ -1309,7 +1333,7 @@ fn a_lent_selection_tool_moves_the_instance_of_a_picked_object() { #[test] fn read_only_commands_read_the_instance_of_a_picked_object() { let mut failures = Vec::new(); - for spec in crate::cmd::command_specs().iter().filter(|c| !c.journal) { + for spec in crate::cmd::command_specs().iter().filter(|c| !c.journal && crate::runs_with_empty_params(c.id)) { let mut s = session(); let inst = pair(&mut s, "dynamic"); s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); diff --git a/crates/engine/src/tests/dynamic_text.rs b/crates/engine/src/tests/dynamic_text.rs new file mode 100644 index 0000000000..20cad1dc01 --- /dev/null +++ b/crates/engine/src/tests/dynamic_text.rs @@ -0,0 +1,460 @@ +//! Type › Dynamic Text (`type.dynamicText`): type on a path scaled by one factor to fill the span +//! between its brackets, fitted again after each edit, and kept at its drawn sizes when it is +//! turned off or threaded. +//! <https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html> + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeKind, TextObject}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +/// 12 pt type on the 400 pt line from (100, 300) to (500, 300), from its start, selected. +fn on_line(s: &mut Session, text: &str) -> NodeId { + let pid = s.execute("path.create", &json!({ "d": "M100 300 L500 300" })).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": text, "size": 12, "at": [100, 300]})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +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 fit(s: &Session, id: NodeId) -> f64 { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).fit_scale +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn err(r: Result<Value>) -> String { + r.unwrap_err().to_string() +} + +#[test] +fn dynamic_text_turns_on_and_off_and_toggles() { + let mut s = session(); + let id = on_line(&mut s, "Grow"); + let before = undo_len(&s); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!((r["on"].clone(), r["ids"].clone()), (json!(true), json!([id.0]))); + let f = r["fitScale"].as_f64().unwrap(); + assert!(f > 2.0, "short text on a long path grows: {f}"); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Dynamic Text"); + assert!(text(&s, id).dynamic_text); + // The bounds the engine keeps are the fitted layout's. + let t = text(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert_eq!(t.cached_bounds, Some(lay.bounds)); + // Already on: nothing changes and no undo step is recorded. + let r = s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(r["on"], json!(true)); + assert_eq!(undo_len(&s), before + 1); + // Toggled off: the text keeps the sizes it was drawn at, in one undo step. + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!((r["on"].clone(), r["fitScale"].clone()), (json!(false), json!(1.0))); + assert_eq!(undo_len(&s), before + 2); + let off = text(&s, id); + assert!(!off.dynamic_text); + assert!((off.runs[0].style.size - 12.0 * f).abs() < 1e-9, "{} vs {}", off.runs[0].style.size, 12.0 * f); + // Undo brings Dynamic Text back with the stored size. + s.execute("edit.undo", &json!({})).unwrap(); + let back = text(&s, id); + assert!(back.dynamic_text && back.runs[0].style.size == 12.0); + let r = s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + assert_eq!(r["on"], json!(false)); + let r = s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + assert_eq!(r["on"], json!(false)); +} + +#[test] +fn dynamic_text_refuses_bad_params_and_other_type() { + let mut s = session(); + let id = on_line(&mut s, "Grow"); + let before = undo_len(&s); + assert!(err(s.execute("type.dynamicText", &json!({"on": "yes"}))).contains("on")); + assert!(err(s.execute("type.dynamicText", &json!({"on": 1}))).contains("on")); + assert_eq!(undo_len(&s), before); + assert!(!text(&s, id).dynamic_text); + // Point type alone: refused (area type takes Block, `typecmd::block_tests`). + let point = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [point]})).unwrap(); + assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path or area type")); + let empty = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [empty]})).unwrap(); + assert!(s.execute("type.dynamicText", &json!({})).is_err()); + // With point type selected too, only the type on a path changes. + let before = undo_len(&s); + s.execute("select.set", &json!({"ids": [point, id.0]})).unwrap(); + let r = s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert!(!text(&s, NodeId(point)).dynamic_text); + assert_eq!(undo_len(&s), before + 1); +} + +#[test] +fn dynamic_text_fits_again_after_each_edit() { + let mut s = session(); + let id = on_line(&mut s, "Grow"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let start = fit(&s, id); + // Longer text draws smaller. + s.execute("text.setText", &json!({"ids": [id.0], "text": "Grow and grow again"})).unwrap(); + let longer = fit(&s, id); + assert!(longer < start * 0.5, "{longer} vs {start}"); + // An end bracket nearer the start draws it smaller still. + s.execute("type.pathOptions", &json!({"ids": [id.0], "end": 0.5})).unwrap(); + let half = fit(&s, id); + assert!(half < longer * 0.6, "{half} vs {longer}"); + s.execute("type.pathOptions", &json!({"ids": [id.0], "end": null})).unwrap(); + // A longer path draws it larger. + s.execute("text.reshapePath", &json!({"id": id.0, "anchors": [[0, 1]], "dx": 200, "dy": 0})).unwrap(); + let reshaped = fit(&s, id); + assert!(reshaped > longer * 1.3, "{reshaped} vs {longer}"); + // Each fit keeps the cached bounds in step with the layout. + let t = text(&s, id); + assert_eq!(t.cached_bounds, Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds)); + // Scaling the object: the fit is in document points, so the drawn size stays. + let drawn = |s: &Session| { + let t = text(s, id); + t.runs[0].style.size * t.style_scale().unwrap().points * fit(s, id) + }; + let size = drawn(&s); + s.execute("object.scale", &json!({"ids": [id.0], "sx": 50, "sy": 50})).unwrap(); + let smaller = drawn(&s); + assert!(smaller < size * 0.6, "the path is half as long: {smaller} vs {size}"); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, id)).overflow); +} + +#[test] +fn threading_turns_dynamic_text_off_at_its_drawn_sizes() { + let mut s = session(); + let id = on_line(&mut s, "Threaded story"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let f = fit(&s, id); + let frame = s.execute("shape.rectangle", &json!({"x": 100, "y": 400, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id.0, frame]})).unwrap(); + let before = undo_len(&s); + let r = s.execute("text.thread.create", &json!({})).unwrap(); + assert_eq!(r["dynamicTextOff"], json!([id.0])); + assert_eq!(undo_len(&s), before + 1, "one undo step"); + let t = text(&s, id); + assert!(!t.dynamic_text); + assert!((t.runs[0].style.size - 12.0 * f).abs() < 1e-9, "{} vs {}", t.runs[0].style.size, 12.0 * f); + // Undo restores Dynamic Text and the stored size together. + s.execute("edit.undo", &json!({})).unwrap(); + let t = text(&s, id); + assert!(t.dynamic_text && t.runs[0].style.size == 12.0); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!text(&s, id).dynamic_text); + // Type on a path in a thread is refused by id, alone or with other type on a path. + let e = err(s.execute("type.dynamicText", &json!({"on": true, "ids": [id.0]}))); + assert!(e.contains("in a thread") && e.contains(&id.0.to_string()), "{e}"); + let free = on_line(&mut s, "Free"); + let e = err(s.execute("type.dynamicText", &json!({"on": true, "ids": [free.0, id.0]}))); + assert!(e.contains("in a thread") && e.contains(&id.0.to_string()), "{e}"); + assert!(!text(&s, id).dynamic_text && !text(&s, free).dynamic_text); + // A thread made without any Dynamic Text says nothing about it. + let a = on_line(&mut s, "Plain"); + let b = s.execute("shape.rectangle", &json!({"x": 400, "y": 400, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); + let r = s.execute("text.thread.create", &json!({})).unwrap(); + assert!(r.get("dynamicTextOff").is_none(), "{r}"); +} + +#[test] +fn text_thread_add_turns_dynamic_text_off() { + let mut s = session(); + let id = on_line(&mut s, "Threaded story"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let f = fit(&s, id); + let r = s.execute("text.thread.add", &json!({"from": id.0, "rect": [100, 400, 200, 100]})).unwrap(); + assert_eq!(r["dynamicTextOff"], json!([id.0])); + let t = text(&s, id); + assert!(!t.dynamic_text && (t.runs[0].style.size - 12.0 * f).abs() < 1e-9); + let added = text(&s, NodeId(r["id"].as_u64().unwrap())); + assert!(!added.dynamic_text); +} + +#[test] +fn dynamic_text_is_saved_only_when_on_and_reads_back() { + let mut s = session(); + let id = on_line(&mut s, "Saved"); + let data = + |s: &mut Session| s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let off = data(&mut s); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let f = fit(&s, id); + let on = data(&mut s); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "on.vectorcraft", "dataBase64": on})).unwrap(); + let t = first_text(&o); + assert!(text(&o, t).dynamic_text); + assert_eq!(text(&o, t).runs[0].style.size, 12.0); + assert_eq!(fit(&o, t), f); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "off.vectorcraft", "dataBase64": off})).unwrap(); + let t = first_text(&o); + assert!(!text(&o, t).dynamic_text); + // The document summary reports the setting and the factor. + let d = s.execute("document.inspect", &json!({})).unwrap().to_string(); + assert!(d.contains("\"dynamicText\":true"), "{d}"); +} + +#[test] +fn svg_export_writes_the_drawn_size() { + let mut s = session(); + let id = on_line(&mut s, "Grow"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let size = 12.0 * fit(&s, id); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(svg.contains("<textPath"), "{svg}"); + let sizes: Vec<f64> = svg + .match_indices("font-size") + .filter_map(|(at, m)| { + let rest = svg[at + m.len()..].trim_start_matches(['=', ':', '"', ' ']); + let end = rest.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(rest.len()); + rest[..end].parse().ok() + }) + .collect(); + assert!(sizes.iter().any(|v| (v - size).abs() < 1e-3), "{size} in {sizes:?}"); + assert!(!sizes.iter().any(|v| (v - 12.0).abs() < 1e-3), "the stored size is not written: {sizes:?}"); +} + +#[test] +fn release_type_on_a_path_keeps_the_drawn_size() { + let mut s = session(); + let id = on_line(&mut s, "Release"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let size = 12.0 * fit(&s, id); + assert!(size > 24.0, "the text grows on the long line: {size}"); + let r = s.execute("addon.type.releasePath", &json!({"ids": [id.0], "mode": "text"})).unwrap(); + let released = NodeId(r["texts"][0].as_u64().unwrap()); + let t = text(&s, released); + assert!(!t.dynamic_text, "point type does not keep Dynamic Text"); + assert!((t.runs[0].style.size - size).abs() < 1e-9, "{} vs the drawn {size}", t.runs[0].style.size); + assert_eq!(fit(&s, released), 1.0); + // Type on a path without Dynamic Text keeps its stored size. + let plain = on_line(&mut s, "Plain"); + let r = s.execute("addon.type.releasePath", &json!({"ids": [plain.0], "mode": "text"})).unwrap(); + let t = text(&s, NodeId(r["texts"][0].as_u64().unwrap())); + assert!(!t.dynamic_text && t.runs[0].style.size == 12.0); +} + +/// 12 pt point type at (100, 100), selected, with its layout bounds. +fn point(s: &mut Session, content: &str) -> (NodeId, vectorcraft_geom::Rect) { + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": content, "size": 12})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let b = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).bounds; + (id, b) +} + +/// Type on a path's path, start bracket and end bracket. +fn on_path(t: &TextObject) -> (vectorcraft_geom::PathData, f64, Option<f64>) { + match &t.kind { + vectorcraft_doc::TextKind::OnPath { path, start, end } => (path.clone(), *start, *end), + k => panic!("not type on a path: {k:?}"), + } +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +#[test] +fn presets_put_point_type_on_a_fitted_circle_arch_or_bow() { + let mut s = session(); + let (id, b) = point(&mut s, "Round and round"); + let w = b.width().max(b.height()); + let before = undo_len(&s); + let r = s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Dynamic Text"); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!(t.path_align, vectorcraft_doc::PathAlign::Descender, "above by default"); + let (path, start, end) = on_path(&t); + assert!(path.is_closed()); + assert_eq!((start, end), (0.75, None)); + let pb = path.bounds().unwrap(); + assert!(close(pb.width(), w) && close(pb.height(), w), "{pb:?} vs {w}"); + assert!(close(pb.center().x, b.center().x) && close(pb.center().y, b.center().y), "{pb:?} vs {b:?}"); + // The start bracket, 3/4 of the way round, is the circle's bottom. + let bottom = path.subpaths[0].anchors[3].p; + assert!(close(bottom.y, pb.y1) && close(bottom.x, pb.center().x), "{bottom:?}"); + // Round a circle as wide as the text, the text grows to fill it and does not overflow. + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.fit_scale > 2.0 && !lay.overflow, "{} {}", lay.fit_scale, lay.overflow); + assert_eq!(r["fitScale"], json!(lay.fit_scale)); + assert_eq!(t.cached_bounds, Some(lay.bounds)); + // Undo gives the point type back. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(text(&s, id).kind, vectorcraft_doc::TextKind::Point) && !text(&s, id).dynamic_text); + + for (preset, up) in [("arch", true), ("bow", false)] { + s.execute("type.dynamicTextPreset", &json!({"preset": preset, "ids": [id.0]})).unwrap(); + let t = text(&s, id); + let (path, start, end) = on_path(&t); + assert!(!path.is_closed() && t.dynamic_text); + assert_eq!((start, end), (0.0, None)); + let a = &path.subpaths[0].anchors; + let (first, middle, last) = (a[0].p, a[1].p, a[a.len() - 1].p); + // Left to right, the chord as wide as the text, the arc rising (or falling) half its radius. + assert!(first.x < last.x && close(last.x - first.x, w) && close(first.y, last.y), "{preset}: {first:?} {last:?}"); + let pb = path.bounds().unwrap(); + assert!(close(pb.height(), w / 3f64.sqrt() / 2.0), "{preset}: {pb:?}"); + assert!(close(pb.center().y, b.center().y), "{preset}: {pb:?} vs {b:?}"); + assert_eq!(middle.y < first.y, up, "{preset}: {middle:?} {first:?}"); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.fit_scale > 1.0 && !lay.overflow, "{preset}: {}", lay.fit_scale); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn preset_position_and_flip_set_align_to_path_and_direction() { + let mut s = session(); + let (id, _) = point(&mut s, "Over the hill"); + for (position, align) in [ + ("above", vectorcraft_doc::PathAlign::Descender), + ("center", vectorcraft_doc::PathAlign::Center), + ("below", vectorcraft_doc::PathAlign::Ascender), + ] { + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "position": position})).unwrap(); + assert_eq!(text(&s, id).path_align, align, "{position}"); + } + // Flipped, the arch runs right to left and the text stands on its other side. + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "flip": true})).unwrap(); + let t = text(&s, id); + let (path, start, end) = on_path(&t); + let a = &path.subpaths[0].anchors; + assert!(a[0].p.x > a[a.len() - 1].p.x, "{path:?}"); + assert_eq!((start, end), (0.0, None)); + assert_eq!(t.path_align, vectorcraft_doc::PathAlign::Descender); + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); + // A flipped circle runs the other way round from its bottom. + s.execute("type.dynamicTextPreset", &json!({"preset": "circle", "flip": true})).unwrap(); + let (path, start, end) = on_path(&text(&s, id)); + assert_eq!((start, end), (0.25, None)); + let at = path.subpaths[0].anchors[1].p; + assert!(close(at.y, path.bounds().unwrap().y1), "reversed, the bottom is a quarter of the way: {at:?}"); + // The effect and Spacing of Type on a Path Options stay. + s.execute("type.pathOptions", &json!({"effect": "skew", "spacing": 5})).unwrap(); + s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap(); + let t = text(&s, id); + assert_eq!((t.path_effect.id(), t.path_spacing), ("skew", 5.0)); +} + +#[test] +fn presets_fit_type_on_a_path_to_its_path_and_record_nothing_when_nothing_changes() { + let mut s = session(); + let id = on_line(&mut s, "Along the line"); + s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap(); + let (path, ..) = on_path(&text(&s, id)); + let a = &path.subpaths[0].anchors; + // The bow is as wide as the 400 pt line, centered where it was. + assert!(close(a[0].p.x, 100.0) && close(a[a.len() - 1].p.x, 500.0), "{a:?}"); + assert!(close(path.bounds().unwrap().center().y, 300.0)); + // The same preset again: nothing changes and no undo step is recorded. + let before = undo_len(&s); + let r = s.execute("type.dynamicTextPreset", &json!({"preset": "bow"})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(undo_len(&s), before); + // Another position is a change. + s.execute("type.dynamicTextPreset", &json!({"preset": "bow", "position": "below"})).unwrap(); + assert_eq!(undo_len(&s), before + 1); + // The fit follows later edits to the text. + let f = fit(&s, id); + s.execute("text.setText", &json!({"ids": [id.0], "text": "Along the line and on past it"})).unwrap(); + assert!(fit(&s, id) < f * 0.8, "{} vs {f}", fit(&s, id)); + // On a rotated object the arch still bulges up the page, and on a squashed one the circle is + // round on the page. + let (turned, _) = point(&mut s, "Turned"); + s.execute("object.rotate", &json!({"ids": [turned.0], "angle": 45})).unwrap(); + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [turned.0]})).unwrap(); + let t = text(&s, turned); + let page = on_path(&t).0.transformed(t.xf); + let a = &page.subpaths[0].anchors; + assert!(close(a[0].p.y, a[2].p.y) && a[1].p.y < a[0].p.y && a[0].p.x < a[2].p.x, "{a:?}"); + // The same preset again leaves the rotated arch as it is. + let before = undo_len(&s); + s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [turned.0]})).unwrap(); + assert_eq!(undo_len(&s), before); + let (squashed, _) = point(&mut s, "Squashed"); + s.execute("object.scale", &json!({"ids": [squashed.0], "sx": 200, "sy": 50})).unwrap(); + s.execute("type.dynamicTextPreset", &json!({"preset": "circle", "ids": [squashed.0]})).unwrap(); + let t = text(&s, squashed); + let pb = on_path(&t).0.transformed(t.xf).bounds().unwrap(); + assert!(close(pb.width(), pb.height()), "{pb:?}"); + // Empty 12 pt point type gets a circle four ems (48 pt) across. + let (empty, _) = point(&mut s, ""); + s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap(); + let (path, ..) = on_path(&text(&s, empty)); + let pb = path.bounds().unwrap(); + assert!(close(pb.width(), 48.0) && close(pb.height(), 48.0), "{pb:?}"); +} + +#[test] +fn presets_refuse_bad_params_area_type_and_threads() { + let mut s = session(); + let (id, _) = point(&mut s, "Point"); + let before = undo_len(&s); + for p in [ + json!({}), + json!({"preset": "square"}), + json!({"preset": 1}), + json!({"preset": "arch", "position": "top"}), + json!({"preset": "arch", "position": true}), + json!({"preset": "arch", "flip": "yes"}), + ] { + let e = err(s.execute("type.dynamicTextPreset", &p)); + let key = ["position", "flip"].into_iter().find(|k| p.get(k).is_some()).unwrap_or("preset"); + assert!(e.contains(key), "{p}: {e}"); + } + assert_eq!(undo_len(&s), before); + assert!(matches!(text(&s, id).kind, vectorcraft_doc::TextKind::Point)); + // Area type alone is refused; beside point type it is left as it is. + let area = + s.execute("text.create", &json!({"x": 10, "y": 300, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [area]})).unwrap(); + assert!(err(s.execute("type.dynamicTextPreset", &json!({"preset": "circle"}))).contains("select point type or type on a path")); + s.execute("select.set", &json!({"ids": [area, id.0]})).unwrap(); + let r = s.execute("type.dynamicTextPreset", &json!({"preset": "circle"})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert!(matches!(text(&s, NodeId(area)).kind, vectorcraft_doc::TextKind::Area { .. }) && !text(&s, NodeId(area)).dynamic_text); + // Type on a path in a thread is refused by id. + let threaded = on_line(&mut s, "Threaded story"); + let frame = s.execute("shape.rectangle", &json!({"x": 100, "y": 400, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let before = undo_len(&s); + let e = err(s.execute("type.dynamicTextPreset", &json!({"preset": "arch", "ids": [threaded.0, id.0]}))); + assert!(e.contains("in a thread") && e.contains(&threaded.0.to_string()), "{e}"); + assert_eq!(undo_len(&s), before); +} + +/// The id of the first text object in `s`'s document. +fn first_text(s: &Session) -> NodeId { + let mut found = None; + s.doc().unwrap().doc.walk(|n| { + if found.is_none() && matches!(n.kind, NodeKind::Text(_)) { + found = Some(n.id); + } + }); + found.unwrap() +} diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index 49307845fd..8f41ed3a73 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -124,6 +124,35 @@ fn adjust_balance_refuses_a_channel_that_is_not_a_number() { assert_eq!(fill_of(&s, a).to_hex(), "#b38080"); } +/// The Edit Colors commands refuse a scope switch, `convert` or `mode` of the wrong type, which they +/// would otherwise replace with the default: `{"fill": "false"}` recolored the fills. +#[test] +fn edit_colors_refuse_a_param_of_the_wrong_type() { + let mut s = session(); + let a = rect(&mut s, json!("#ff0000")); + let undo = s.doc().unwrap().history.undo.len(); + let cases = [ + ("edit.colors.invert", json!({"fill": "false"}), "`fill` must be true or false"), + ("edit.colors.toCMYK", json!({"stroke": 0}), "`stroke` must be true or false"), + ("edit.colors.toGrayscale", json!({"fill": "false"}), "`fill` must be true or false"), + ("edit.colors.toRGB", json!({"includeImages": "no"}), "`includeImages` must be true or false"), + ("edit.colors.saturate", json!({"intensity": 50, "includePatterns": 1}), "`includePatterns` must be true or false"), + ("edit.colors.adjustBalance", json!({"r": 20, "fill": "false"}), "`fill` must be true or false"), + ("edit.colors.adjustBalance", json!({"tint": 20, "convert": "true"}), "`convert` must be true or false"), + ("edit.colors.adjustBalance", json!({"tint": 20, "fill": "false"}), "`fill` must be true or false"), + ("edit.colors.adjustBalance", json!({"mode": 1, "r": 20}), "`mode` must be a string"), + ]; + for (id, p, want) in cases { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{id} {p}: {e}"); + } + assert_eq!(fill_of(&s, a).to_hex(), "#ff0000"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + // A null is read as a switch left out. + s.execute("edit.colors.invert", &json!({"fill": null, "stroke": null})).unwrap(); + assert_eq!(fill_of(&s, a).to_hex(), "#00ffff"); +} + // ---------- meshes, images and patterns ---------- fn mesh_colors(s: &Session, id: NodeId) -> Vec<Color> { diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index 2d10c3f5d9..34e01bf31e 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -147,3 +147,37 @@ fn show_all_hidden_attributes() { s.execute("edit.undo", &json!({})).unwrap(); assert!(node(&s, id).appearance.has_hidden()); } + +/// A Warp applied now takes its style's Bézier net (`version` 1) unless a map is given, an edit +/// keeps the map the effect has (one saved before the version existed keeps the earlier map), and +/// a map this build doesn't draw is refused. +#[test] +fn warps_keep_the_map_their_version_names() { + let (mut s, id) = session_with_rect(); + let version = |s: &Session| node(s, id).appearance.effects[0].params.get("version").cloned(); + run(&mut s, "effect.apply", json!({"effect": "warp.flag", "params": {"bend": 40}})); + assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET))); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 20}, "warpStyle": "arc"})); + assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET))); + // As a file saved before the version existed gives it. + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(Value::Object(p)) = doc.node_mut(id).and_then(|n| n.appearance.effects.first_mut()).map(|e| &mut e.params) { + p.remove("version"); + } + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 10, "horizontal": 20}})); + assert_eq!(version(&s), None); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"version": 1}})); + assert_eq!(version(&s), Some(json!(1))); + run(&mut s, "effect.apply", json!({"effect": "warp.arc", "params": {"version": 0}})); + assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0)); + // A whole number given as a float is that version. + run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 1.0}})); + assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(1)); + run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 0.0}})); + assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0)); + for bad in [json!(2), json!(-1), json!(0.5), json!("1")] { + assert!(s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"version": bad}})).is_err(), "{bad}"); + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"version": bad}})).is_err(), "{bad}"); + } + assert_eq!(node(&s, id).appearance.effects.len(), 2); +} diff --git a/crates/engine/src/tests/envelope.rs b/crates/engine/src/tests/envelope.rs index e4d030d387..4ffd7a361a 100644 --- a/crates/engine/src/tests/envelope.rs +++ b/crates/engine/src/tests/envelope.rs @@ -123,6 +123,51 @@ fn reset_with_warp_and_mesh_switch_the_kind_and_keep_the_content() { assert!(s.execute("object.envelope.resetWithMesh", &json!({})).is_err()); } +/// A new warp envelope bends with its style's Bézier net (`version` [`live::WARP_NET`]) and keeps +/// it through Reset with Warp. One saved before the version existed keeps the earlier map when its +/// warp or its options change. +#[test] +fn new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map() { + // The surface point a quarter of the way along the top edge. + let quarter = |s: &Session, e| live::EnvelopeMap::of(&node(s, e)).unwrap().surface_mesh(4, 4, vectorcraft_color::Color::BLACK).points[1].p; + let at = |x, y| vectorcraft_geom::Point::new(x, y); + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40})); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e)); + assert_eq!(s.execute("object.envelope.info", &json!({})).unwrap()["version"], json!(live::WARP_NET)); + // Flag moves the top edge 6 × bend × height × u(1 - u)(1 - 2u) down at u: 22.5 at u = 1/4. + assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e)); + s.execute("object.envelope.resetWithWarp", &json!({"bend": -40})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e)); + assert!(quarter(&s, e).distance(at(150.0, 77.5)) < 1e-9, "{:?}", quarter(&s, e)); + // As a file saved before the version existed gives it. + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Envelope { kind, .. }) = doc.node_mut(e).map(|n| &mut n.kind) + && let EnvelopeKind::Warp { version, .. } = &mut **kind + { + *version = 0; + } + s.execute("object.envelope.options", &json!({"fidelity": 75})).unwrap(); + s.execute("object.envelope.resetWithWarp", &json!({"bend": 40})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e)); + // The earlier map's flag: half the bend times sin(π x), x = -1/2 here, in half heights. + assert!(quarter(&s, e).distance(at(150.0, 90.0)) < 1e-9, "{:?}", quarter(&s, e)); + // `version` moves a warp to a map, and a new warp can take the earlier one. + s.execute("object.envelope.options", &json!({"version": 1.0})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e)); + assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e)); + s.execute("object.envelope.resetWithWarp", &json!({"version": 0})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e)); + let (_, old) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40, "version": 0})); + assert!(matches!(kind(&s, old), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, old)); + for bad in [json!(2), json!(-1), json!(0.5), json!("1"), json!(null)] { + for cmd in ["object.envelope.makeWithWarp", "object.envelope.resetWithWarp", "object.envelope.options"] { + let r = s.execute(cmd, &json!({"version": bad})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("`version` must be 0 or 1")), "{cmd} {bad}: {r:?}"); + } + } +} + #[test] fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() { let mut s = session(); @@ -141,9 +186,9 @@ fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() { let content = node(&s, a); assert_eq!((content.opacity, content.blend, content.extras().mask.is_some()), (0.4, BlendMode::Multiply, true), "the content keeps the look"); let NodeKind::Mesh(m) = node(&s, ids[1]).kind else { panic!("the warp's shape comes back as a mesh") }; - // The mesh follows the arc: its outline reaches below the content's bottom edge at the sides. + // The mesh follows the arc: its top corners swing out past the content's sides and up. let b = m.outline().bounds().unwrap(); - assert!(b.y1 > 201.0, "{b:?}"); + assert!(b.x0 < 99.0 && b.x1 > 301.0 && b.y0 < 99.0, "{b:?}"); assert_eq!(s.doc().unwrap().selection.objects, ids); } diff --git a/crates/engine/src/tests/envelope_distort.rs b/crates/engine/src/tests/envelope_distort.rs index b42b1da027..435d918552 100644 --- a/crates/engine/src/tests/envelope_distort.rs +++ b/crates/engine/src/tests/envelope_distort.rs @@ -154,6 +154,35 @@ fn images_bend_as_a_raster_mesh_warp() { assert_eq!(svg.matches("<image").count(), 1, "the pieces share the image's pixels"); } +#[test] +fn a_colorized_image_keeps_its_color_in_an_envelope() { + let mut s = session(); + let img = image::GrayImage::from_pixel(4, 4, image::Luma([0])); + let mut png = vec![]; + image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let im = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); + let id = d.alloc_id(); + let xf = Affine::translate((100.0, 100.0)) * Affine::scale(10.0); + let im = + vectorcraft_doc::ImageObject { key: "gray".into(), width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [im.0]})).unwrap(); + sel(&mut s, &[im]); + arch(&mut s, 80.0, json!({})); + let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true); + // The black pixels draw in the fill color, in the bent shape. + let mid = img.pixel(120, 97); + assert!(mid[0] > 200 && mid[1] < 60 && mid[2] < 60, "the middle rose, red: {mid:?}"); + let inside = img.pixel(120, 120); + assert!(inside[0] > 200 && inside[1] < 60 && inside[2] < 60, "red inside: {inside:?}"); +} + /// A selected embedded 2×2 image, 80×80 pt at (100, 100): a red column left of a blue one. fn two_color_image(s: &mut Session) -> NodeId { let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }); @@ -286,17 +315,18 @@ fn symbols_bend_with_the_envelope() { let e = arch(&mut s, 60.0, json!({})); let pts = anchors(&evaluated(&s, e)); assert!(pts.iter().any(|p| p.y < 90.0), "the symbol's art rose in the middle"); - // Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art). + // Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art). The + // arch lifts the middle of the 100..200 box by about 51, so (200, 120) is inside it. let mut r = vectorcraft_render::Renderer::new(); let region = Rect::new(0.0, 0.0, 400.0, 300.0); - assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] < 60); + assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] < 60); s.edit("edit symbol", |d, _| { let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(-10.0, -10.0, -8.0, -8.0)), Default::default()); d.symbols[0].art = Arc::new(art); Ok(()) }) .unwrap(); - assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] > 200); + assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] > 200); } fn strokes(nodes: &[Node]) -> usize { @@ -405,3 +435,210 @@ fn new_envelopes_distort_appearance_and_old_ones_keep_their_look() { let e = arch(&mut s, 50.0, json!({})); assert!(matches!(node(&s, e).kind, NodeKind::Envelope { options, .. } if options == EnvelopeOptions::NEW)); } + +/// What strokes the object in [`squeezed`]. +#[derive(Clone, Copy)] +enum Stroked { + /// Nothing. + No, + /// The characters of type, or a path's own stroke. + Own, + /// A stroke on type's own appearance (Appearance panel), the characters unstroked. + Appearance, +} + +/// The weight of the strokes in [`squeezed`]. +const SQUEEZED_WEIGHT: f64 = 8.0; + +/// `make`'s object, stroked by `stroked` with a red stroke [`SQUEEZED_WEIGHT`] wide, in a one-patch +/// mesh envelope with Distort Appearance on whose right column is moved in to squeeze the object to +/// half its width (a horizontal squeeze, the same everywhere): the session, the envelope and the +/// height of the envelope's middle. +fn squeezed(make: fn(&mut Session) -> NodeId, stroked: Stroked) -> (Session, NodeId, f64) { + use vectorcraft_doc::live::EnvelopeKind; + let mut s = session(); + let a = make(&mut s); + sel(&mut s, &[a]); + match stroked { + Stroked::No => {} + Stroked::Own => { + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [a.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + } + Stroked::Appearance => { + s.edit("appearance stroke", |d, _| { + let n = d.node_mut(a).unwrap(); + let mut appearance = (*n.appearance).clone(); + appearance + .items + .push(AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), SQUEEZED_WEIGHT))); + n.appearance = appearance.into(); + Ok(()) + }) + .unwrap(); + } + } + let e = id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap()); + let NodeKind::Envelope { options, .. } = &node(&s, e).kind else { panic!("an envelope") }; + assert!(options.distort_appearance, "new envelopes distort appearance"); + let mut middle = 0.0; + s.edit("squeeze", |d, _| { + let NodeKind::Envelope { kind, .. } = &mut d.node_mut(e).unwrap().kind else { panic!("an envelope") }; + let EnvelopeKind::Mesh { points, handles, .. } = &mut **kind else { panic!("a mesh") }; + let (left, right) = (points[0].x, points[1].x); + points[1].x = left + (right - left) / 2.0; + points[3].x = points[1].x; + handles.clear(); + middle = (points[0].y + points[2].y) / 2.0; + Ok(()) + }) + .unwrap(); + (s, e, middle) +} + +/// Where the ink of the page of `s` starts and ends across height `y`, as the canvas draws it. +fn ink_across(s: &Session, y: f64) -> (f64, f64) { + let scale = 8.0; + let region = Rect::new(0.0, y - 0.5, 800.0, y + 0.5); + let r = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, region, scale, true); + let row = (r.height / 2) as usize; + let inked: Vec<usize> = (0..r.width as usize).filter(|i| r.pixels[(row * r.width as usize + i) * 4..][..3].iter().any(|c| *c < 128)).collect(); + let (first, last) = (inked.first().unwrap(), inked.last().unwrap()); + (*first as f64 / scale, (last + 1) as f64 / scale) +} + +/// How wide the ink is across the middle of `make`'s object in [`squeezed`]. +fn squeezed_ink(make: fn(&mut Session) -> NodeId, stroked: Stroked) -> f64 { + let (s, _, middle) = squeezed(make, stroked); + let (first, last) = ink_across(&s, middle); + last - first +} + +/// A capital I set 300 points tall at (100, 400), filled black. +fn tall_i(s: &mut Session) -> NodeId { + id_of(&s.execute("text.create", &json!({"x": 100, "y": 400, "text": "I", "size": 300})).unwrap()) +} + +/// With Distort Appearance on, the characters' stroke of type in an envelope paints along the bent +/// glyph outlines at its own weight, as `.ai` files draw it (#6644): squeezed to half its width, the +/// stem of an I still has half the weight of stroke on each side, not a quarter. +#[test] +fn type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope() { + let (plain, stroked) = (squeezed_ink(tall_i, Stroked::No), squeezed_ink(tall_i, Stroked::Own)); + let past = stroked - plain; + assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})"); +} + +/// A stroke on type's own appearance paints at its own weight too (#6644). +#[test] +fn a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope() { + let (plain, stroked) = (squeezed_ink(tall_i, Stroked::No), squeezed_ink(tall_i, Stroked::Appearance)); + let past = stroked - plain; + assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})"); +} + +/// A path's stroke still bends with the art: squeezed to half its width, it reaches half as far past +/// the path's left and right sides. +#[test] +fn a_paths_stroke_still_bends_in_a_squeezed_envelope() { + let (plain, stroked) = (squeezed_ink(rect, Stroked::No), squeezed_ink(rect, Stroked::Own)); + let past = stroked - plain; + assert!( + (past - SQUEEZED_WEIGHT / 2.0).abs() < 0.5, + "the stroke reaches {past} pt past the squeezed rectangle, both sides together ({plain} → {stroked})" + ); +} + +/// The type's stroke paints past the envelope's grid, where the glyphs reach its edge: the +/// envelope's visual bounds hold it (#6644). +#[test] +fn the_visual_bounds_of_an_envelope_hold_its_types_strokes() { + let (s, e, middle) = squeezed(tall_i, Stroked::Own); + let n = node(&s, e); + let (visual, grid) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap()); + let (first, last) = ink_across(&s, middle); + assert!(first < grid.x0 - 1.0, "the stroke paints past the grid: {first} vs {grid:?}"); + // The ink is measured to whole pixels (an eighth of a point); miter spikes don't count, as in + // type's own visual bounds. + let pixel = 0.125; + assert!(visual.x0 <= first + pixel && visual.x1 >= last - pixel, "{visual:?} holds the ink from {first} to {last}"); + assert!(first - visual.x0 < 1.0 && visual.x1 - last < 1.0, "{visual:?} reaches no further than the ink from {first} to {last}"); +} + +/// A repeat of stroked type reaches past its copies by as far as the characters' strokes paint +/// past their glyphs: half the weight of a centred stroke, as type's own visual bounds (#6644). +#[test] +fn the_visual_bounds_of_a_repeat_of_stroked_type_grow_by_half_the_stroke() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "I", "size": 100})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + let r = id_of(&s.execute("object.repeat.grid", &json!({"ids": [t.0], "rows": 2, "cols": 2})).unwrap()); + let n = node(&s, r); + let (visual, geometric) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap()); + let grown = [geometric.x0 - visual.x0, geometric.y0 - visual.y0, visual.x1 - geometric.x1, visual.y1 - geometric.y1]; + assert!(grown.iter().all(|g| (g - SQUEEZED_WEIGHT / 2.0).abs() < 1e-6), "{grown:?}"); +} + +/// An I stroked by `stroked` in a one-patch mesh envelope that leaves it as it is: the envelope. +fn enveloped_i(s: &mut Session, stroked: bool) -> NodeId { + let t = tall_i(s); + if stroked { + s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + } + sel(s, &[t]); + id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap()) +} + +/// Type's stroke in an envelope inside an envelope also paints at its own weight: the outer +/// envelope squeezes the inner one's type to half its width, and the stem still has half the weight +/// of stroke on each side (#6644). +#[test] +fn type_strokes_paint_at_their_own_weight_in_an_envelope_inside_an_envelope() { + let (plain, stroked) = (squeezed_ink(|s| enveloped_i(s, false), Stroked::No), squeezed_ink(|s| enveloped_i(s, true), Stroked::No)); + let past = stroked - plain; + assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})"); +} + +/// An opacity mask on type bends as other art does (#6644): with Distort Appearance its stroke +/// becomes its bent outline, as on a path, while the type's own stroke stays a stroke. +#[test] +fn an_opacity_mask_on_type_bends_as_other_art() { + let mut s = session(); + let t = tall_i(&mut s); + s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + let m = id_of(&s.execute("shape.rectangle", &json!({"x": 90, "y": 150, "width": 120, "height": 300})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [m.0], "color": "#ffffff"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [m.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + sel(&mut s, &[t, m]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + assert!(node(&s, t).extras().mask.is_some(), "the type has the mask"); + sel(&mut s, &[t]); + let e = arch(&mut s, 60.0, json!({"distortAppearance": true})); + let (mut masks, mut kept) = (vec![], 0); + for n in &evaluated(&s, e) { + n.walk(&mut |c| { + kept += c.appearance.painted_strokes().count(); + masks.extend(c.extras().mask.as_ref().map(|m| m.art.clone())); + }); + } + assert_eq!(masks.len(), 1, "the mask goes with the type"); + let mut in_mask = 0; + masks[0].walk(&mut |c| in_mask += c.appearance.painted_strokes().count()); + assert_eq!(in_mask, 0, "the mask's stroke became its bent outline"); + assert_eq!(kept, 1, "the type's stroke stays a stroke"); +} + +/// Expand turns an envelope of stroked type into its bent glyph outlines with the stroke on them, +/// at its own weight, as it draws (#6644). +#[test] +fn expanding_an_envelope_of_stroked_type_keeps_the_stroke_at_its_weight() { + let (mut s, e, _) = squeezed(tall_i, Stroked::Own); + sel(&mut s, &[e]); + s.execute("object.envelope.expand", &json!({})).unwrap(); + let mut weights = vec![]; + node(&s, e).walk(&mut |c| weights.extend(c.appearance.painted_strokes().map(|st| st.width))); + assert_eq!(weights, [SQUEEZED_WEIGHT]); +} diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index f8363fe93f..b3a9012e06 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -215,6 +215,291 @@ fn type_picks_up_font_and_size() { assert_eq!((st.size, justify, st.fill.color().unwrap().to_hex()), (12.0, preserved_alignment, "#00ff00".into())); } +/// Sample document-space typography between text objects with different local transforms. +#[test] +fn scaled_type_pick_matches_effective_character_dimensions() { + for source_area in [false, true] { + for target_area in [false, true] { + let mut s = session(); + let create = |s: &mut Session, area: bool, x: f64| { + let mut p = json!({"x": x, "y": 100, "text": "Sample", "size": 12}); + if area { + p["area"] = json!({"width": 160, "height": 80}); + } + id_of(s.execute("text.create", &p).unwrap()) + }; + let src = create(&mut s, source_area, 100.0); + s.execute("object.transform", &json!({"matrix": [3, 0, 0, 2, 0, 0]})).unwrap(); + let dst = create(&mut s, target_area, 300.0); + s.execute("object.transform", &json!({"matrix": [0.5, 0, 0, 1.5, 0, 0]})).unwrap(); + let before = node(&s, dst); + let source = node(&s, src); + let history = undo_len(&s); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let after = node(&s, dst); + let NodeKind::Text(t) = &after.kind else { panic!("not text") }; + let NodeKind::Text(old) = &before.kind else { panic!("not text") }; + let effective = t.effective_char_style(&t.first_style()).unwrap(); + assert!((effective.size - 24.0).abs() < 1e-8, "sampled font size: {}", effective.size); + assert!((effective.h_scale - 150.0).abs() < 1e-8, "sampled horizontal scale: {}", effective.h_scale); + assert_eq!(t.xf, old.xf, "sampling keeps the target's transform"); + assert_eq!(node(&s, src), source); + assert_eq!(undo_len(&s), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, dst), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(node(&s, dst), after); + } + } +} + +/// A text object snapshot, including the local attributes and retained affine transform. +fn sampled_type(s: &Session, id: NodeId) -> vectorcraft_doc::TextObject { + let NodeKind::Text(t) = node(s, id).kind else { panic!("not text") }; + *t +} + +/// Compare the dimensional character attributes that text controls display in document units. +fn assert_sampled_dimensions(actual: &vectorcraft_doc::CharStyle, expected: &vectorcraft_doc::CharStyle) { + assert_eq!(actual.leading.is_some(), expected.leading.is_some()); + for (a, e) in [ + (actual.size, expected.size), + (actual.h_scale, expected.h_scale), + (actual.v_scale, expected.v_scale), + (actual.leading.unwrap_or(0.0), expected.leading.unwrap_or(0.0)), + (actual.baseline_shift, expected.baseline_shift), + (actual.tcy_up_down, expected.tcy_up_down), + (actual.tcy_left_right, expected.tcy_left_right), + ] { + assert!((a - e).abs() < 1e-8, "sampled dimension: {a} != {e}"); + } +} + +/// Rotation, shear, reflection and grouping stay on the objects while typography is copied. +#[test] +fn scaled_type_pick_preserves_affines_and_document_dimensions() { + for grouped in [false, true] { + let mut s = session(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap()); + s.execute("text.setStyle", &json!({"leading": 18})).unwrap(); + s.execute("text.setFormat", &json!({"hScale": 80, "vScale": 125, "baselineShift": 3, "tcyUpDown": 2, "tcyLeftRight": -1})).unwrap(); + if grouped { + s.execute("object.group", &json!({})).unwrap(); + } + s.execute("object.transform", &json!({"matrix": [0, -3, -2, 1, 0, 0]})).unwrap(); + let src_text = sampled_type(&s, src); + let expected = src_text.effective_char_style(&src_text.first_style()).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Target", "size": 20})).unwrap()); + if grouped { + s.execute("object.group", &json!({})).unwrap(); + } + s.execute("object.transform", &json!({"matrix": [-1, 0.5, 1, 2, 0, 0]})).unwrap(); + let before = sampled_type(&s, dst); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let after = sampled_type(&s, dst); + assert_sampled_dimensions(&after.effective_char_style(&after.first_style()).unwrap(), &expected); + assert_eq!(after.xf, before.xf); + assert_eq!(sampled_type(&s, src), src_text); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(t) = &reopened.node(dst).unwrap().kind else { panic!("not text") }; + assert_sampled_dimensions(&t.effective_char_style(&t.first_style()).unwrap(), &expected); + } +} + +/// A transformed target compensates only the highlighted characters, retaining the others. +#[test] +fn scaled_type_pick_changes_only_the_highlighted_range() { + let mut s = session(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap()); + s.execute("object.transform", &json!({"matrix": [3, 0, 0, 2, 0, 0]})).unwrap(); + let source = sampled_type(&s, src); + let expected = source.effective_char_style(&source.first_style()).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Sample", "size": 10})).unwrap()); + s.execute("object.transform", &json!({"matrix": [0.5, 0, 0, 3, 0, 0]})).unwrap(); + let before = sampled_type(&s, dst); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 1, "end": 4})); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + let history = undo_len(&s); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let after = sampled_type(&s, dst); + assert_eq!(after.runs.len(), 3); + assert_eq!((&*after.runs[0].text, &*after.runs[1].text, &*after.runs[2].text), ("S", "amp", "le")); + assert_eq!(after.runs[0].style, before.first_style()); + assert_eq!(after.runs[2].style, before.first_style()); + assert_sampled_dimensions(&after.effective_char_style(&after.runs[1].style).unwrap(), &expected); + assert_eq!(after.xf, before.xf); + assert_eq!(undo_len(&s), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(sampled_type(&s, dst), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(sampled_type(&s, dst), after); +} + +/// Reject unusable source or target transforms before any part of a multi-object pick changes. +#[test] +fn scaled_type_pick_rejects_unrepresentable_dimensions_atomically() { + for (bad_source, factor) in [(true, 0.0), (false, 0.0), (false, 1e-306), (true, f64::from_bits(1))] { + let mut s = session(); + let size = if bad_source && factor > 0.0 { 0.1 } else { 24.0 }; + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": size, "color": "#00ff00"})).unwrap()); + if bad_source { + s.execute("object.transform", &json!({"matrix": [factor, 0, 0, factor, 0, 0]})).unwrap(); + } + let good = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Good", "size": 10})).unwrap()); + let other = id_of(s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Other", "size": 12})).unwrap()); + if !bad_source { + s.execute("object.transform", &json!({"matrix": [factor, 0, 0, factor, 0, 0]})).unwrap(); + } + s.execute("select.set", &json!({"ids": [good.0, other.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + let error = s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap_err(); + assert!(error.to_string().contains("transform"), "{error}"); + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.paint, paint); + assert_eq!(s.eyedropper_sample, sample); + assert_eq!(undo_len(&s), history); + // A paint-only pick does not need a usable text transform. + s.execute("appearance.copyFrom", &json!({"source": src.0, "apply": {"character": false, "paragraph": false}})).unwrap(); + } +} + +/// A failed dimensional pick retains highlighted characters and the previously remembered sample. +#[test] +fn scaled_type_pick_rejection_preserves_the_highlighted_range_and_sample() { + let mut s = session(); + let saved = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Saved", "size": 18})).unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": saved.0})).unwrap(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Source", "size": 24, "color": "#00ff00"})).unwrap()); + s.execute("object.transform", &json!({"matrix": [0, 0, 0, 0, 0, 0]})).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Sample", "size": 10})).unwrap()); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 1, "end": 4})); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let range = s.tool_options(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + assert!(s.execute("appearance.copyFrom", &json!({"source": src.0})).is_err()); + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.tool_options(), range); + assert_eq!(s.paint, paint); + assert_eq!(s.eyedropper_sample, sample); + assert_eq!(undo_len(&s), history); + // Alt-click can still apply the last successful sample after the rejected pick. + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap(); + assert_eq!(sampled_type(&s, dst).first_style().size, 18.0); +} + +/// A pick that would extend text beyond the canvas keeps the previous sample and defaults. +#[test] +fn scaled_type_pick_canvas_rejection_preserves_sample_and_defaults() { + for mode in ["selection", "ids", "reverse", "range"] { + let mut s = session(); + let saved = id_of(s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Saved", "size": 18, "color": "#0000ff"})).unwrap()); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 96, "color": "#ff0000"})).unwrap()); + let dst = id_of(s.execute("text.create", &json!({"x": MAX_COORD - 100.0, "y": 200, "text": "WWWW", "size": 10})).unwrap()); + s.execute("appearance.copyFrom", &json!({"source": saved.0, "ids": []})).unwrap(); + let pick = match mode { + "ids" | "reverse" => { + s.execute("select.none", &json!({})).unwrap(); + if mode == "ids" { json!({"source": src.0, "ids": [dst.0]}) } else { json!({"source": dst.0, "ids": [src.0], "reverse": true}) } + } + "range" => { + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"id": dst.0, "start": 0, "end": 3})); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + json!({"source": src.0}) + } + _ => json!({"source": src.0}), + }; + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let range = s.tool_options(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + + let error = s.execute("appearance.copyFrom", &pick).unwrap_err(); + assert!(error.to_string().contains("coordinates out of range"), "{mode}: {error}"); + assert_eq!(s.doc().unwrap().doc, doc, "{mode}"); + assert_eq!(s.doc().unwrap().selection, selection, "{mode}"); + assert_eq!(s.tool_options(), range, "{mode}"); + assert_eq!(s.paint, paint, "{mode}"); + assert_eq!(s.eyedropper_sample, sample, "{mode}"); + assert_eq!(undo_len(&s), history, "{mode}"); + } +} + +/// Changing justification can move explicitly targeted point text outside the canvas even +/// when character copying is disabled. +#[test] +fn paragraph_only_pick_rejects_out_of_bounds_explicit_target() { + let mut s = session(); + let saved = id_of(s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Saved", "color": "#0000ff"})).unwrap()); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "color": "#ff0000"})).unwrap()); + s.execute("text.setStyle", &json!({"justify": "left"})).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 100, "y": 200, "text": "WWWW", "size": 16})).unwrap()); + s.execute("text.setStyle", &json!({"justify": "right"})).unwrap(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, MAX_COORD - 101.0, 0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": saved.0, "ids": []})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + let sample = s.eyedropper_sample.clone(); + let history = undo_len(&s); + + let pick = json!({"source": src.0, "ids": [dst.0], "apply": {"character": false}}); + let error = s.execute("appearance.copyFrom", &pick).unwrap_err(); + assert!(error.to_string().contains("coordinates out of range"), "{error}"); + assert_eq!(s.doc().unwrap().doc, doc); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.paint, paint); + assert_eq!(s.eyedropper_sample, sample); + assert_eq!(undo_len(&s), history); +} + +/// Disabled character copying and append preserve typography; reverse and cached picks convert it. +#[test] +fn scaled_type_pick_respects_options_and_reverse_sampling() { + let mut s = session(); + let src = id_of(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Source", "size": 12})).unwrap()); + s.execute("object.scale", &json!({"sx": 300, "sy": 200})).unwrap(); + let source = sampled_type(&s, src); + let expected = source.effective_char_style(&source.first_style()).unwrap(); + let dst = id_of(s.execute("text.create", &json!({"x": 300, "y": 100, "text": "Target", "size": 20})).unwrap()); + s.execute("object.scale", &json!({"sx": 50, "sy": 150})).unwrap(); + let before = sampled_type(&s, dst); + for options in [json!({"pickUp": {"character": false}}), json!({"apply": {"character": false}}), json!({"append": true})] { + let mut p = json!({"source": src.0, "ids": [dst.0]}); + p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + s.execute("appearance.copyFrom", &p).unwrap(); + assert_sampled_dimensions(&sampled_type(&s, dst).first_style(), &before.first_style()); + } + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap(); + let after = sampled_type(&s, dst); + assert_sampled_dimensions(&after.effective_char_style(&after.first_style()).unwrap(), &expected); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).unwrap(); + let cached = sampled_type(&s, dst); + assert_sampled_dimensions(&cached.effective_char_style(&cached.first_style()).unwrap(), &expected); +} + #[test] fn alt_click_applies_the_selection_to_the_clicked_object() { let mut s = session(); diff --git a/crates/engine/src/tests/file.rs b/crates/engine/src/tests/file.rs index 6467fe0912..b3b041e2e2 100644 --- a/crates/engine/src/tests/file.rs +++ b/crates/engine/src/tests/file.rs @@ -61,6 +61,35 @@ fn serialize_and_reopen() { assert!(png.len() > 100); } +#[test] +fn export_params_of_the_wrong_type_are_refused_and_null_keeps_the_default() { + let mut s = session(); + s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hello"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 80, "height": 40})).unwrap(); + for (cmd, p, msg) in [ + ("document.serialize", json!({"format": 5}), "`format` must be a string"), + ("document.serialize", json!({"format": "svg", "selectedOnly": "true"}), "`selectedOnly` must be true or false"), + ("document.serialize", json!({"format": "txt", "selectionOnly": 1}), "`selectionOnly` must be true or false"), + ("document.serialize", json!({"format": "txt", "selectionOnly": true, "selectedOnly": "false"}), "`selectedOnly` must be true or false"), + ("document.export", json!({"format": "svg", "path": 5}), "`path` must be a string"), + ("document.exportSelection", json!({"format": "png", "path": 5}), "`path` must be a string"), + ("document.exportSelection", json!({"format": 5}), "`format` must be a string"), + ("document.exportForOffice", json!({"ppi": "300"}), "`ppi` must be a number"), + ("document.exportForOffice", json!({"transparent": "true"}), "`transparent` must be true or false"), + ("document.exportForOffice", json!({"path": 5}), "`path` must be a string"), + ] { + let e = match s.execute(cmd, &p) { + Ok(r) => panic!("{cmd} {p} gave {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains(msg), "{cmd} {p}: {e}"); + } + let r = s.execute("document.serialize", &json!({"format": null, "selectedOnly": null})).unwrap(); + assert_eq!(r, s.execute("document.serialize", &json!({})).unwrap()); + let r = s.execute("document.exportForOffice", &json!({"ppi": null, "transparent": null, "path": null})).unwrap(); + assert_eq!(r, s.execute("document.exportForOffice", &json!({})).unwrap()); +} + #[test] fn save_and_open_path() { let mut s = session(); diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index c37cbfe90d..4d86a84b3c 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -161,7 +161,8 @@ fn an_exported_pdf_opens_with_its_file_info() { assert_eq!(back["description"], "A poster\nfor the fair"); assert_eq!(back["keywords"], json!(["fair", "Poster", "print"])); assert!(back["created"].as_str().is_some_and(|c| c.ends_with('Z')), "the file's creation date: {}", back["created"]); - assert_eq!(back["title"], "poster.pdf", "the title stays the file name"); + assert_eq!(back["title"], "Poster", "File Info shows the title the PDF carries"); + assert_eq!(s.doc().unwrap().title(), "poster.pdf", "the document stays named after the file"); assert_eq!(back["copyrightStatus"], "copyrighted"); assert_eq!(back["copyrightNotice"], "(c) 2026 Ada"); assert_eq!(back["copyrightUrl"], "https://example.com/rights"); @@ -277,6 +278,192 @@ fn a_pdf_compatible_ai_opens_with_the_file_info_of_its_xmp_packet() { assert_eq!(m.copyright_url, ""); } +/// A one-page PDF whose trailer names an information dictionary with the entries `info`, and whose +/// catalog has a metadata stream holding an XMP `dc:title` of `xmp_title`. +fn pdf_titled(info: Option<&str>, xmp_title: Option<&str>) -> Vec<u8> { + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog}; + let first = first_extra(1); + let mut objects = vec![]; + let mut catalog = String::new(); + if let Some(t) = xmp_title { + let xmp = format!( + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\ + <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\ + <dc:title><rdf:Alt><rdf:li xml:lang=\"de\">Zugangswege</rdf:li><rdf:li xml:lang=\"x-default\">{t}</rdf:li></rdf:Alt></dc:title>\ + </rdf:Description></rdf:RDF></x:xmpmeta>" + ); + objects.push(format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n{xmp}\nendstream", xmp.len())); + catalog = format!("/Metadata {first} 0 R "); + } + let info_at = first + objects.len(); + if let Some(i) = info { + objects.push(format!("<< {i} >>")); + } + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let bytes = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &refs, &catalog, None); + if info.is_none() { + return bytes; + } + // The trailer follows the cross-reference table, so a longer trailer moves no object. + String::from_utf8(bytes).unwrap().replacen("/Root 1 0 R", &format!("/Root 1 0 R /Info {info_at} 0 R"), 1).into_bytes() +} + +/// A document called `name` with content `bytes` opened (as `document.open` with no path: the tab +/// shows the document's name), `s` holding it. +fn open_named(s: &mut Session, name: &str, bytes: &[u8]) -> Value { + s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap() +} + +/// The document's name (its tab) and its File Info title. +fn titles(s: &mut Session) -> [String; 2] { + let info = s.execute("file.info", &json!({})).unwrap(); + [s.doc().unwrap().title(), info["title"].as_str().unwrap().to_string()] +} + +/// What opening `bytes` as a file called `name` gives: the document's name and its File Info title. +fn opened(name: &str, bytes: &[u8]) -> [String; 2] { + let mut s = Session::new(); + let r = open_named(&mut s, name, bytes); + let t = titles(&mut s); + assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some(t[0].as_str()), Some(t[1].as_str())), "the open reply"); + assert_eq!(s.doc().unwrap().doc.title, t[0], "the tab is the document's title"); + t +} + +fn svg_titled(inner: &str) -> String { + format!( + "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\">{inner}<rect width=\"5\" height=\"5\"><title>Tooltip" + ) +} + +#[test] +fn import_puts_the_files_own_title_in_file_info_only() { + // SVG: the root's ``, its white space made single spaces (not a shape's tooltip), is the + // File Info title; the document keeps the file's name, with its extension. + assert_eq!(opened("box.svg", svg_titled("<title>\n Access\n paths ").as_bytes()), ["box.svg", "Access paths"]); + assert_eq!( + opened("/work/box.svg", svg_titled("Zugangswege Rechenzentrum – Prüfdiagramm").as_bytes()), + ["box.svg", "Zugangswege Rechenzentrum – Prüfdiagramm"] + ); + // PDF: the XMP `dc:title` (its `x-default` item) beats the Info `Title`; the Info `Title` stands alone. + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), Some("XMP title"))), ["plan.pdf", "XMP title"]); + assert_eq!(opened("plan.pdf", &pdf_titled(None, Some("XMP title"))), ["plan.pdf", "XMP title"]); + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.pdf", "Info title"]); + assert_eq!(opened("plan.ai", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.ai", "Info title"]); + // Compressed SVG too. + let svgz = |inner: &str| vectorcraft_svg::compress(&svg_titled(inner)); + assert_eq!(opened("box.svgz", &svgz("Access paths")), ["box.svgz", "Access paths"]); + // A file that gives none (or a blank one) gives File Info the document's name. + assert_eq!(opened("box.svg", svg_titled("").as_bytes()), ["box.svg", "box.svg"]); + assert_eq!(opened("box.svg", svg_titled(" ").as_bytes()), ["box.svg", "box.svg"]); + assert_eq!(opened("plan.pdf", &pdf_titled(None, None)), ["plan.pdf", "plan.pdf"]); + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Author (Ada)"), None)), ["plan.pdf", "plan.pdf"]); + // The Untitled-N name New gives is no title (a document that never had one writes it). + assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Untitled-2)"), None)), ["plan.pdf", "plan.pdf"]); + // A template opens as a new untitled document, whatever title its file gave. + let [name, info] = opened("plan.ait", &pdf_titled(Some("/Title (Info title)"), None)); + assert!(name.starts_with("Untitled-") && info == name, "{name} / {info}"); +} + +#[test] +fn imported_svg_titles_are_filtered_and_bounded() { + for (raw, expected) in [ + ("Untitled-2".to_string(), None), + ("\u{7f}".to_string(), None), + ("Re\u{7f}lease Plan".to_string(), Some("Release Plan".to_string())), + ("λ".repeat(65_537), Some("λ".repeat(65_536))), + ] { + let svg = svg_titled(&format!("{raw}")); + for format in ["svg", "svgz"] { + let name = format!("box.{format}"); + let bytes = if format == "svgz" { vectorcraft_svg::compress(&svg) } else { svg.as_bytes().to_vec() }; + assert_eq!(opened(&name, &bytes), [name.clone(), expected.clone().unwrap_or(name)], "{format}"); + } + } +} + +#[test] +fn a_file_with_a_title_opened_from_a_path_is_named_after_the_file() { + let dir = std::env::temp_dir().join(format!("vc-infotitle-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("box.svg"); + std::fs::write(&path, svg_titled("Access paths")).unwrap(); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"path": path.to_str().unwrap()})).unwrap(); + assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths"))); + let r = s.execute("document.inspect", &json!({"depth": 0})).unwrap(); + assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths"))); + // The default names of what the document exports are made from the file's name, not its title. + assert_eq!(s.doc().unwrap().doc.title, "box.svg"); + assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "png"), "box.png"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn file_info_edits_a_files_own_title_and_the_document_follows() { + let mut s = Session::new(); + open_named(&mut s, "box.svg", svg_titled("Access paths").as_bytes()); + // The dialog sends back the title it was given: nothing changes (no undo step). + let before = s.doc().unwrap().revision; + let shown = s.execute("file.info", &json!({})).unwrap(); + s.execute("file.info", &shown).unwrap(); + assert_eq!(s.doc().unwrap().revision, before, "the title it gave is no edit"); + assert_eq!(titles(&mut s), ["box.svg", "Access paths"]); + // Another title is the document's own, as ever, and the file's is gone. + let r = s.execute("file.info", &json!({"title": "Plan B"})).unwrap(); + assert_eq!(r["title"], "Plan B"); + assert_eq!(titles(&mut s), ["Plan B", "Plan B"]); + assert_eq!(s.doc().unwrap().doc.metadata.title, None); + // Undo brings the file's title back, and the name. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(titles(&mut s), ["box.svg", "Access paths"]); +} + +#[test] +fn restored_file_info_title_keeps_authored_spaces() { + let mut s = session(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).metadata.title = Some("Release Plan".into()); + for format in ["vectorcraft", "svg", "pdf"] { + let bytes = b64(&s.execute("document.export", &json!({"format": format, "preserveEditing": true})).unwrap()); + let mut reopened = Session::new(); + let reply = open_named(&mut reopened, &format!("again.{format}"), &bytes); + assert_eq!(reply["restored"], format != "vectorcraft", "{format}"); + assert_eq!(reopened.doc().unwrap().doc.metadata.title.as_deref(), Some("Release Plan"), "{format}"); + assert_eq!(titles(&mut reopened)[1], "Release Plan", "{format}"); + } +} + +#[test] +fn the_files_own_title_is_kept_by_saves_and_written_by_exports() { + let mut s = Session::new(); + open_named(&mut s, "box.svg", svg_titled("Access paths").as_bytes()); + // The native file: its own title is the document's name, the File Info title survives. + let native = b64(&s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()); + let mut t = Session::new(); + open_named(&mut t, "other.vectorcraft", &native); + assert_eq!(titles(&mut t), ["box.svg", "Access paths"]); + // An SVG with the editing data it carries, reopened under another name. + let svg = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true, "metadata": true})).unwrap()["text"] + .as_str() + .unwrap() + .to_string(); + assert!(svg.contains("Access paths") && svg.contains("Access paths"), "{svg}"); + let mut u = Session::new(); + let r = open_named(&mut u, "again.svg", svg.as_bytes()); + assert_eq!(r["restored"], true); + assert_eq!(titles(&mut u), ["again.svg", "Access paths"]); + // PDF: the Info `Title` and the XMP `dc:title`, shown by the viewer. + for pdf in pdf_texts(&mut s) { + assert!(pdf.contains("/Title(Access paths)") && xmp_title(&pdf).contains("Access paths"), "{}", xmp_title(&pdf)); + assert!(pdf.contains("/ViewerPreferences<>"), "{pdf}"); + } + // PNG text. + let png = b64(&s.execute("document.export", &json!({"format": "png"})).unwrap()); + assert!(crate::cmd::fileio::pngtext::text(&png).iter().any(|(k, v)| k == "Title" && v == "Access paths")); + // The default file names are made from the document's name. + assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "pdf"), "box.pdf"); +} + #[test] fn png_exports_carry_text_chunks() { let mut s = session(); diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 84e4724fe6..042f741e0e 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -450,6 +450,54 @@ fn objects_without_transparency_stay_unless_outlined() { } } +/// A row of opaque rectangles 1.5 pt apart (closer than twice the antialiasing margin), with a +/// see-through one touching each end: only the two next to a see-through one are flattened, and +/// the document looks the same. +#[test] +fn opaque_art_that_touches_only_opaque_art_stays() { + let _settings = settings_lock(); + let mut s = session(); + let under = rect(&mut s, 0.0, 50.0, 10.0, 10.0, "#2060c0"); + run(&mut s, "transparency.set", json!({"ids": [under], "opacity": 50})); + let row: Vec = (1..15).map(|i| rect(&mut s, 11.5 * f64::from(i), 50.0, 10.0, 10.0, "#e04010")).collect(); + let over = rect(&mut s, 11.5 * 15.0, 50.0, 10.0, 10.0, "#20a040"); + run(&mut s, "transparency.set", json!({"ids": [over], "opacity": 50, "blend": "Multiply"})); + let before = picture(&s); + run(&mut s, "select.all", json!({})); + let (ids, vector, rasterized) = flatten(&mut s, json!({})); + assert_eq!((vector, rasterized), (4, 0), "two groups of two regions each"); + let (ends, kept) = (row[0], row.last().copied().unwrap()); + assert!(!exists(&s, under) && !exists(&s, over) && !exists(&s, ends) && !exists(&s, kept)); + assert!(row[1..row.len() - 1].iter().all(|id| exists(&s, *id) && ids.contains(id)), "the rest of the row stays"); + assert_eq!(ids.len(), row.len() - 2 + 2); + let diff = changed(&before, &picture(&s)); + assert!(diff == 0.0, "{:.2}% of the pixels changed", diff * 100.0); +} + +/// Opaque art between a see-through object's group and the top of that group, painting over a +/// member, joins the group (along a chain too), so it still paints over it; opaque art under the +/// group stays. +#[test] +fn opaque_art_the_group_would_move_under_joins_it() { + let _settings = settings_lock(); + let mut s = session(); + let d = rect(&mut s, 40.0, 80.0, 25.0, 40.0, "#f0d000"); + let a = rect(&mut s, 60.0, 50.0, 45.0, 40.0, "#e01010"); + let b = rect(&mut s, 20.0, 20.0, 45.0, 35.0, "#10a010"); + let c = rect(&mut s, 0.0, 0.0, 25.0, 25.0, "#1010e0"); + let t = rect(&mut s, 100.0, 50.0, 40.0, 40.0, "#000000"); + run(&mut s, "transparency.set", json!({"ids": [t], "opacity": 50})); + let before = picture(&s); + let (ids, ..) = flatten(&mut s, json!({"ids": [d, a, b, c, t]})); + assert!(exists(&s, d) && ids.contains(&d), "the art under the group stays"); + assert!([a, b, c, t].iter().all(|id| !exists(&s, *id)), "the others are flattened together"); + // Where B paints over A, and C over B, they still do. + for p in [Point::new(62.5, 52.5), Point::new(22.5, 22.5), Point::new(62.5, 85.5), Point::new(102.5, 70.5)] { + assert_eq!(pixel(&picture(&s), p), pixel(&before, p), "at {p:?}"); + } + assert!(changed(&before, &picture(&s)) == 0.0); +} + #[test] fn outlined_type_keeps_its_underline() { let _settings = settings_lock(); diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index f31df35eb1..8bef8733b5 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -194,6 +194,43 @@ fn a_search_finds_a_missing_fonts_file_by_its_names() { assert!(matches!(r["state"].as_str(), Some("stopped" | "done")), "{r}"); } +/// A caller confined by read roots sees, in the replies to a search another caller started, only +/// the files found inside its read roots, and the folder searched and a failed search's path only +/// when they are inside them. +#[test] +fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { + let root = folder("read-roots"); + let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3"); + let (home, wide) = (root.join("home"), root.join("lrf-wide")); + for dir in [&home, &wide] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("Findme.otf"), &font).unwrap(); + } + let mut s = session_for(&root); + let roots = |read: &[&Path]| crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap(); + let (narrow, broad) = (roots(&[&home]), roots(&[&root])); + let ask = |s: &mut Session, r: &Arc, p: Value| { + crate::file_access::confine(Some(r), || s.execute("text.findFontFiles", &p).unwrap()) + }; + // A font no file has keeps the search going through every folder. + let fonts = json!([{"family": "Findme Sans 3"}, {"family": "No Such Sans"}]); + ask(&mut s, &broad, json!({"folder": root, "fonts": fonts})); + finished(&mut s); + let all = ask(&mut s, &broad, json!({})); + assert_eq!((&all["fonts"][0]["files"], &all["folder"]), (&json!([home.join("Findme.otf"), wide.join("Findme.otf")]), &json!(root)), "{all}"); + for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] { + assert!(!r.to_string().contains("lrf-wide") && r.get("folder").is_none(), "{r}"); + assert_eq!((&r["fonts"][0]["files"], &r["fonts"][0]["family"]), (&json!([home.join("Findme.otf")]), &json!("Findme Sans 3")), "{r}"); + assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}"); + } + // A search that failed: the reason shows without the path to a caller outside its folder. + ask(&mut s, &broad, json!({"folder": wide.join("gone"), "fonts": fonts})); + assert!(finished(&mut s)["error"].as_str().is_some_and(|e| e.contains("lrf-wide"))); + let r = ask(&mut s, &narrow, json!({})); + assert_eq!((r["state"].as_str(), r["error"].as_str(), r.get("folder")), (Some("failed"), Some("the folder can't be read"), None), "{r}"); + let _ = std::fs::remove_dir_all(&root); +} + #[test] fn junk_search_params_never_fail_internally() { let root = folder("junk"); diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index e6f9383fe3..73e0172da5 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -32,7 +32,7 @@ fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint { #[test] fn new_gradient_defaults_follow_the_cmyk_document_mode() { - for kind in ["linear", "radial", "freeform"] { + for kind in ["linear", "radial", "conic", "diamond", "freeform"] { let mut s = Session::new(); s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); @@ -123,7 +123,7 @@ fn bad_gradients_are_rejected_without_editing() { json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"color": "#000000"}]}), json!({"stops": [{"offset": "a", "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]}), json!({"stops": "red"}), - json!({"kind": "conic"}), + json!({"kind": "spiral"}), json!({"start": [0, 0]}), json!({"aspect": "wide"}), ] { @@ -565,3 +565,319 @@ fn method_is_a_gradient_option_that_saves_and_loads() { let back = fill_gradient(&s, id); assert!(back.gradient.dither && back.gradient.method == GradientMethod::Perceptual); } + +/// A conic gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params +/// agents and swatches read, and the native format. +#[test] +fn a_conic_gradient_is_set_edited_transformed_and_saved() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "conic"}})).unwrap(); + let g = fill_gradient(&s, id); + assert_eq!(g.gradient.kind, GradientKind::Conic); + // Unplaced, it sweeps from the right about the box's center. + let geom = g.resolve(node(&s, id).geometric_bounds().unwrap()); + assert_eq!(geom.start, Point::new(200.0, 150.0)); + assert!((geom.param_at(GradientKind::Conic, Point::new(200.0, 190.0)) - 0.25).abs() < 1e-9); + // `angle` and `conical` name it too. + for name in ["angle", "conical", "CONICAL"] { + s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": name})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Conic, "{name}"); + } + let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string(); + assert!(e.contains("(linear, radial, conic, diamond, freeform)"), "{e}"); + // Placed, an angle turns the vector about the center. + s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap(); + s.execute("paint.editGradient", &json!({"angle": 90})).unwrap(); + let g = fill_geom(&s, id); + assert!(g.start.distance(Point::new(200.0, 150.0)) < 1e-9 && g.end.distance(Point::new(200.0, 90.0)) < 1e-9, "{g:?}"); + // A reflection mirrors the sweep (a negative aspect): each point keeps its color. + let p = Point::new(230.0, 170.0); + let before = g.param_at(GradientKind::Conic, p); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + let m = fill_geom(&s, id); + assert!(m.is_mirrored(), "{m:?}"); + assert!((m.param_at(GradientKind::Conic, Point::new(170.0, 170.0)) - before).abs() < 1e-9); + // An aspect edit sets what it is given: the Gradient panel sends a mirrored conic's sign. + s.execute("paint.editGradient", &json!({"aspect": -80})).unwrap(); + assert_eq!(fill_geom(&s, id).aspect, -0.8); + s.execute("paint.setGradientGeom", &json!({"aspect": 40})).unwrap(); + assert_eq!(fill_geom(&s, id).aspect, 0.4); + // A rotation carries it along. + let g = fill_geom(&s, id); + let before = g.param_at(GradientKind::Conic, p); + s.execute("object.rotate", &json!({"angle": 30, "origin": [200, 150]})).unwrap(); + let r = vectorcraft_geom::Affine::rotate_about(-30f64.to_radians(), Point::new(200.0, 150.0)); + let after = fill_geom(&s, id).param_at(GradientKind::Conic, r * p); + assert!((after - before).abs() < 1e-9, "{before} vs {after}"); + // The params give it back, and the native format keeps it. + s.execute("paint.editGradient", &json!({"aspect": -60})).unwrap(); + let want = fill_gradient(&s, id); + let params = vectorcraft_tools::params::gradient_params(&want); + assert_eq!((params["kind"].as_str(), params["aspect"].as_f64()), (Some("conic"), Some(-60.0))); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setFill", &json!({ "gradient": params })).unwrap(); + let got = fill_gradient(&s, id); + assert_eq!((&got.gradient, got.geom), (&want.gradient, want.geom)); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Paint::Gradient(g) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") }; + assert_eq!((g.gradient.kind, g.geom), (GradientKind::Conic, want.geom)); +} + +/// A free distort that is not affine moves a conic as it moves a radial gradient: by the warp +/// near its center, not near the middle of its vector. +#[test] +fn a_warp_moves_a_conic_by_its_center() { + let warped = |kind: &str| { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [20, 30], "end": [90, 30], "aspect": 60}})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [140, 130], [-20, 100]]})).unwrap(); + fill_geom(&s, id) + }; + let (conic, radial, linear) = (warped("conic"), warped("radial"), warped("linear")); + assert!(conic.start.distance(radial.start) < 1e-9, "{conic:?} vs {radial:?}"); + assert!(conic.start.distance(linear.start) > 0.1, "a linear gradient moves by its middle: {linear:?}"); +} + +/// A negative aspect mirrors a conic's sweep where the gradient is given one, and a mirrored +/// conic swatch lands mirrored on other art. Other kinds refuse a negative aspect, and a conic +/// refuses a focal point. +#[test] +fn a_negative_aspect_mirrors_only_a_conic() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "aspect": -50}})).unwrap(); + assert_eq!(fill_gradient(&s, id).geom.map(|g| g.aspect), Some(-0.5)); + s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [0, 0], "end": [10, 0], "aspect": -200}})).unwrap(); + assert_eq!(fill_gradient(&s, id).geom.map(|g| g.aspect), Some(-2.0)); + let mut q = gradient_param(&fill_gradient(&s, id)); + q["name"] = json!("Mirrored"); + s.execute("swatch.new", &q).unwrap(); + let b = rect(&mut s, 500.0, 300.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"swatch": "Mirrored"})).unwrap(); + assert_eq!(fill_gradient(&s, b).geom.map(|g| g.aspect), Some(-2.0)); + // Radial (and linear) gradients have no mirror: a negative aspect is an error, whichever + // command gives it, and the gradient stays as it was. + let before = fill_gradient(&s, b); + for kind in ["radial", "linear"] { + let e = s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "aspect": -50}})).unwrap_err().to_string(); + assert!(e.contains("aspect"), "{kind}: {e}"); + let e = s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [0, 0], "end": [10, 0], "aspect": -50}})).unwrap_err(); + assert!(e.to_string().contains("aspect"), "{kind}: {e}"); + } + assert_eq!(fill_gradient(&s, b), before); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial", "aspect": 50}})).unwrap(); + let radial = fill_gradient(&s, b); + assert!(s.execute("paint.editGradient", &json!({"aspect": -50})).is_err()); + assert!(s.execute("paint.setGradientGeom", &json!({"aspect": -50})).is_err()); + assert!(s.execute("paint.editGradient", &json!({"kind": "linear", "aspect": -50})).is_err()); + assert_eq!(fill_gradient(&s, b), radial); + // Turned conic in the same edit, a negative aspect mirrors it. + s.execute("paint.editGradient", &json!({"kind": "conic", "aspect": -50})).unwrap(); + assert_eq!(fill_gradient(&s, b).geom.map(|g| g.aspect), Some(-0.5)); + // A conic has no focal point: one given is an error, and null is allowed. + let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [500, 300], "end": [550, 300], "focal": [510, 300]}})); + assert!(e.unwrap_err().to_string().contains("focal")); + s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [500, 300], "end": [550, 300], "focal": null}})).unwrap(); + assert_eq!(fill_gradient(&s, b).geom.unwrap().focal, None); + assert!(s.execute("paint.setGradientGeom", &json!({"focal": [510, 300]})).unwrap_err().to_string().contains("focal")); + // A selected conic takes a negative aspect while the default paint is linear: the default + // takes its size. + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": "conic"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.editGradient", &json!({"aspect": -70})).unwrap(); + assert_eq!(fill_gradient(&s, b).geom.map(|g| g.aspect), Some(-0.7)); + // A linear gradient keeps no focal point, as paint.setGradientGeom leaves it. + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [500, 300], "end": [550, 300], "focal": [510, 300]}})).unwrap(); + assert_eq!(fill_gradient(&s, b).geom.unwrap().focal, None); +} + +/// Saved as `.ai`, as PDF with its editing data and as SVG with its editing data, then opened, a +/// mirrored, squashed conic comes back as it was; a PDF without editing data gives it back from +/// its sweep shading. +#[test] +fn a_conic_survives_saving_as_ai_pdf_and_svg() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [180, 140], "end": [240, 110], "aspect": -60}})).unwrap(); + let want = fill_gradient(&s, id); + let reopened = |s: &mut Session, format: &str, p: Value| { + let mut p = p; + p["format"] = json!(format); + let r = s.execute("file.saveCopy", &p).unwrap(); + let mut back = session(); + back.execute("document.open", &json!({"name": format!("t.{format}"), "dataBase64": r["dataBase64"]})).unwrap(); + let mut found = None; + back.doc().unwrap().doc.walk(|n| { + if let (None, Paint::Gradient(g)) = (&found, n.appearance.fill_paint()) { + found = Some(*g.clone()); + } + }); + found.unwrap_or_else(|| panic!("{format}: the gradient is lost")) + }; + for (format, p) in [("ai", json!({})), ("pdf", json!({"preserveEditing": true})), ("svg", json!({"preserveEditing": true}))] { + let got = reopened(&mut s, format, p); + assert_eq!((got.gradient.kind, got.geom), (GradientKind::Conic, want.geom), "{format}"); + } + let got = reopened(&mut s, "pdf", json!({"preserveEditing": false})); + assert_eq!(got.gradient.kind, GradientKind::Conic); + let (g, w) = (got.geom.unwrap(), want.geom.unwrap()); + assert!(g.is_mirrored() && g.start.distance(w.start) < 0.05, "{g:?}"); + for p in [Point::new(120.0, 120.0), Point::new(280.0, 180.0), Point::new(200.0, 105.0)] { + assert!((g.param_at(GradientKind::Conic, p) - w.param_at(GradientKind::Conic, p)).abs() < 2e-3, "{p:?}: {g:?}"); + } +} + +/// Turning a gradient conic is one undo step, and undoing it gives the gradient back as it was. +#[test] +fn making_a_gradient_conic_is_one_undo_step() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}})).unwrap(); + let (before, steps) = (fill_gradient(&s, id), s.doc().unwrap().history.undo.len()); + s.execute("paint.editGradient", &json!({"kind": "conic", "angle": 45})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_gradient(&s, id), before); +} + +/// A diamond gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params +/// agents and swatches read, and the native format. +#[test] +fn a_diamond_gradient_is_set_edited_transformed_and_saved() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond"}})).unwrap(); + let g = fill_gradient(&s, id); + assert_eq!(g.gradient.kind, GradientKind::Diamond); + // Unplaced, it runs from the box's center out to a square whose edges pass through the box's + // corners. + let geom = g.resolve(node(&s, id).geometric_bounds().unwrap()); + assert_eq!((geom.start, geom.end), (Point::new(200.0, 150.0), Point::new(350.0, 150.0))); + for (p, t) in [ + (Point::new(300.0, 200.0), 1.0), + (Point::new(100.0, 100.0), 1.0), + (Point::new(250.0, 150.0), 1.0 / 3.0), + (Point::new(200.0, 175.0), 1.0 / 6.0), + ] { + assert!((geom.param_at(GradientKind::Diamond, p) - t).abs() < 1e-9, "{p:?}"); + } + s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap(); + s.execute("paint.editGradient", &json!({"kind": "DIAMOND"})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Diamond); + let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string(); + assert!(e.contains("(linear, radial, conic, diamond, freeform)"), "{e}"); + // Placed, an angle turns the vector about the center. + s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap(); + s.execute("paint.editGradient", &json!({"angle": 90})).unwrap(); + let g = fill_geom(&s, id); + assert!(g.start.distance(Point::new(200.0, 150.0)) < 1e-9 && g.end.distance(Point::new(200.0, 90.0)) < 1e-9, "{g:?}"); + // A reflection keeps each point's color. + let p = Point::new(230.0, 170.0); + let before = g.param_at(GradientKind::Diamond, p); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + let m = fill_geom(&s, id); + assert!(m.aspect > 0.0, "{m:?}"); + assert!((m.param_at(GradientKind::Diamond, Point::new(170.0, 170.0)) - before).abs() < 1e-9); + // A rotation carries it along. + let before = m.param_at(GradientKind::Diamond, p); + s.execute("object.rotate", &json!({"angle": 30, "origin": [200, 150]})).unwrap(); + let r = vectorcraft_geom::Affine::rotate_about(-30f64.to_radians(), Point::new(200.0, 150.0)); + let after = fill_geom(&s, id).param_at(GradientKind::Diamond, r * p); + assert!((after - before).abs() < 1e-9, "{before} vs {after}"); + // The params give it back, and the native format keeps it. + s.execute("paint.editGradient", &json!({"aspect": 60})).unwrap(); + let want = fill_gradient(&s, id); + let params = vectorcraft_tools::params::gradient_params(&want); + assert_eq!((params["kind"].as_str(), params["aspect"].as_f64()), (Some("diamond"), Some(60.0))); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setFill", &json!({ "gradient": params })).unwrap(); + let got = fill_gradient(&s, id); + assert_eq!((&got.gradient, got.geom), (&want.gradient, want.geom)); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Paint::Gradient(g) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") }; + assert_eq!((g.gradient.kind, g.geom), (GradientKind::Diamond, want.geom)); +} + +/// A diamond refuses a negative aspect and a focal point, from every command that gives one, and +/// the gradient stays as it was; a null focal point is allowed. +#[test] +fn a_diamond_refuses_a_negative_aspect_and_a_focal_point() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "aspect": 50}})).unwrap(); + let before = fill_gradient(&s, id); + for p in [ + json!({"gradient": {"kind": "diamond", "aspect": -50}}), + json!({"gradient": {"kind": "diamond", "start": [0, 0], "end": [10, 0], "aspect": -50}}), + ] { + assert!(s.execute("paint.setFill", &p).unwrap_err().to_string().contains("aspect"), "{p}"); + } + assert!(s.execute("paint.editGradient", &json!({"aspect": -50})).is_err()); + assert!(s.execute("paint.setGradientGeom", &json!({"aspect": -50})).is_err()); + assert!(s.execute("paint.editGradient", &json!({"kind": "radial", "aspect": -50})).is_err()); + let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "focal": [210, 150]}})); + assert!(e.unwrap_err().to_string().contains("focal")); + assert!(s.execute("paint.setGradientGeom", &json!({"focal": [210, 150]})).unwrap_err().to_string().contains("focal")); + assert_eq!(fill_gradient(&s, id), before); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [200, 150], "end": [260, 150], "focal": null}})).unwrap(); + assert_eq!(fill_gradient(&s, id).geom.unwrap().focal, None); +} + +/// A free distort that is not affine moves a diamond by the warp near its center, as it moves a +/// radial gradient. +#[test] +fn a_warp_moves_a_diamond_by_its_center() { + let warped = |kind: &str| { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [20, 30], "end": [90, 30], "aspect": 60}})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [140, 130], [-20, 100]]})).unwrap(); + fill_geom(&s, id) + }; + let (diamond, radial) = (warped("diamond"), warped("radial")); + assert!(diamond.start.distance(radial.start) < 1e-9, "{diamond:?} vs {radial:?}"); +} + +/// Saved as `.ai`, as PDF with its editing data and as SVG with its editing data, then opened, a +/// turned, squashed diamond comes back as it was. +#[test] +fn a_diamond_survives_saving_as_ai_pdf_and_svg() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "diamond", "start": [180, 140], "end": [240, 110], "aspect": 60}})).unwrap(); + let want = fill_gradient(&s, id); + for format in ["ai", "pdf", "svg"] { + let r = s.execute("file.saveCopy", &json!({"format": format, "preserveEditing": true})).unwrap(); + let mut back = session(); + back.execute("document.open", &json!({"name": format!("t.{format}"), "dataBase64": r["dataBase64"]})).unwrap(); + let mut found = None; + back.doc().unwrap().doc.walk(|n| { + if let (None, Paint::Gradient(g)) = (&found, n.appearance.fill_paint()) { + found = Some(*g.clone()); + } + }); + let got = found.unwrap_or_else(|| panic!("{format}: the gradient is lost")); + assert_eq!((got.gradient.kind, got.geom), (GradientKind::Diamond, want.geom), "{format}"); + } +} + +/// Turning a gradient diamond is one undo step, and undoing it gives the gradient back as it was. +#[test] +fn making_a_gradient_diamond_is_one_undo_step() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}})).unwrap(); + let (before, steps) = (fill_gradient(&s, id), s.doc().unwrap().history.undo.len()); + s.execute("paint.editGradient", &json!({"kind": "diamond", "angle": 45})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_gradient(&s, id), before); +} diff --git a/crates/engine/src/tests/gradpanel.rs b/crates/engine/src/tests/gradpanel.rs index 85fd4cf02c..680abfa9e8 100644 --- a/crates/engine/src/tests/gradpanel.rs +++ b/crates/engine/src/tests/gradpanel.rs @@ -132,6 +132,44 @@ fn graphic_styles_keep_gradients_relative_to_the_bounds() { assert!(close(fill_geom(&s, dst).unwrap().start, Point::new(0.2, 0.5)), "legacy styles are applied as stored"); } +/// Applying a style with a placed gradient to objects of different sizes gives each its own +/// appearance with the gradient on its own bounds, through undo and redo; a style from an older +/// file applies the same stored gradient to each, as one shared appearance. +#[test] +fn a_style_places_its_gradient_on_each_object() { + let (mut s, src, dst) = source_and_target(); + let other = rect(&mut s, 100.0, 300.0, 50.0, 200.0); + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Glow"})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Glow", "ids": [dst.0, other.0]})).unwrap(); + let placed = |s: &Session| { + let (g, h) = (fill_geom(s, dst).unwrap(), fill_geom(s, other).unwrap()); + close(g.start, Point::new(540.0, 60.0)) + && close(g.end, Point::new(660.0, 60.0)) + && close(h.start, Point::new(110.0, 400.0)) + && close(h.end, Point::new(140.0, 400.0)) + }; + let shared = |s: &Session| { + let d = &s.doc().unwrap().doc; + vectorcraft_doc::Shared::ptr_eq(&d.node(dst).unwrap().appearance, &d.node(other).unwrap().appearance) + }; + assert!(placed(&s) && !shared(&s)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(placed(&s) && !shared(&s)); + + let glow = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == "Glow").cloned().unwrap(); + let legacy = vectorcraft_doc::GraphicStyle { name: "Old".into(), id: 0, unit_box: false, ..glow }; + s.edit("Add", |d, _| { + d.graphic_styles.push(legacy); + Ok(()) + }) + .unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Old", "ids": [dst.0, other.0]})).unwrap(); + assert!(shared(&s)); + assert!(close(fill_geom(&s, other).unwrap().start, Point::new(0.2, 0.5)), "legacy styles are applied as stored"); +} + #[test] fn eyedropper_options_choose_what_copy_from_takes() { let mut s = session(); diff --git a/crates/engine/src/tests/gradpresets.rs b/crates/engine/src/tests/gradpresets.rs index 437f96d26c..4328361b8b 100644 --- a/crates/engine/src/tests/gradpresets.rs +++ b/crates/engine/src/tests/gradpresets.rs @@ -38,7 +38,19 @@ fn built_in_presets_are_the_gradient_libraries_by_theme_with_unique_names() { // Grouped by library, the gradient libraries first, then the swatch libraries holding gradients. let mut libraries: Vec<&str> = rows.iter().map(|r| r["library"].as_str().unwrap()).collect(); libraries.dedup(); - assert_eq!(libraries, ["Spectrum Gradients", "Sky Gradients", "Neutral Gradients", "Duotone Gradients", "Radial Glows", "Metallic Gradients"]); + assert_eq!( + libraries, + [ + "Spectrum Gradients", + "Sky Gradients", + "Neutral Gradients", + "Organic Fades", + "Holographic", + "Duotone Gradients", + "Radial Glows", + "Metallic Gradients" + ] + ); let mut seen = std::collections::HashSet::new(); assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset"); let vignette = rows.iter().find(|r| r["name"] == "Vignette").unwrap(); @@ -65,6 +77,56 @@ fn applying_a_preset_edits_the_gradient_in_place_as_one_undo_step() { assert_eq!(paint(&s, id, false), before); } +#[test] +fn an_organic_fade_applies_with_its_method_midpoints_and_opacities() { + let (mut s, id) = session_with(json!({"color": "#336699"})); + let mist = s.gradient_preset("Mist").unwrap(); + assert_eq!((mist.library, mist.gradient.method), (Some("Organic Fades"), GradientMethod::Perceptual)); + s.execute("gradient.presets.apply", &json!({"name": "Mist"})).unwrap(); + let g = paint(&s, id, false).gradient; + assert_eq!((g.kind, g.method, &g.stops), (GradientKind::Linear, GradientMethod::Perceptual, &mist.gradient.stops)); + assert_eq!(s.gradient_preset_name(&g).as_deref(), Some("Mist")); + let list = s.execute("gradient.presets.list", &json!({})).unwrap(); + let row = list["presets"].as_array().unwrap().iter().find(|r| r["name"] == "Mist").unwrap().clone(); + assert_eq!(row["gradient"]["method"], "perceptual"); +} + +#[test] +fn a_holographic_foil_applies_in_place_as_one_undo_step() { + let (mut s, id) = session_with(json!({"gradient": {"angle": 30}})); + let before = paint(&s, id, false); + let undo = s.doc().unwrap().history.undo.len(); + let veil = s.gradient_preset("prism veil").unwrap(); + assert_eq!((veil.library, veil.gradient.method), (Some("Holographic"), GradientMethod::Perceptual)); + let r = s.execute("gradient.presets.apply", &json!({"name": "prism veil"})).unwrap(); + assert_eq!(r["name"].as_str(), Some("Prism Veil")); + let g = paint(&s, id, false); + assert_eq!((g.gradient.kind, g.gradient.method, &g.gradient.stops), (GradientKind::Linear, GradientMethod::Perceptual, &veil.gradient.stops)); + assert_eq!(g.gradient.stops.len(), 6); + assert_eq!(g.angle, before.angle, "the placement stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(s.gradient_preset_name(&g.gradient).as_deref(), Some("Prism Veil")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paint(&s, id, false), before); +} + +/// A preset saved as "Mint Halo" before Holographic existed stays listed under a free name. +#[test] +fn a_saved_preset_named_like_a_holographic_glow_gets_a_free_name() { + let (mut s, id) = session_with(json!({"gradient": {"kind": "radial"}})); + let halo = s.gradient_preset("Mint Halo").unwrap().gradient; + let mut own = paint(&s, id, false).gradient; + own.dither = true; + let mut prefs = s.prefs.clone(); + prefs.gradient_presets = vec![crate::cmd::GradientPreset { name: "MINT HALO".into(), gradient: own.clone() }]; + s.apply_prefs(prefs); + assert_eq!(s.prefs.gradient_presets.iter().map(|p| p.name.as_str()).collect::>(), ["MINT HALO 2"]); + s.execute("gradient.presets.apply", &json!({"name": "mint halo 2"})).unwrap(); + assert_eq!(paint(&s, id, false).gradient, own); + s.execute("gradient.presets.apply", &json!({"name": "Mint Halo"})).unwrap(); + assert_eq!(paint(&s, id, false).gradient.stops, halo.stops); +} + #[test] fn a_preset_applies_to_the_stroke_and_to_a_solid_paint() { let (mut s, id) = session_with(json!({"color": "#336699"})); @@ -334,3 +396,37 @@ fn saved_presets_round_trip_with_the_preferences() { fresh.apply_prefs(back); assert!(fresh.gradient_preset("mine").is_some_and(|e| e.library.is_none())); } + +/// Preferences can hold saved presets named like a built-in preset (saved before it existed) or +/// like each other (edited by hand): applied, each gets a name of its own, any case. +#[test] +fn saved_presets_named_like_a_built_in_or_another_saved_one_get_a_free_name() { + let (mut s, id) = session_with(json!({"gradient": {"kind": "radial"}})); + let mist = s.gradient_preset("Mist").unwrap().gradient; + let mut own = paint(&s, id, false).gradient; + own.dither = true; + let preset = |name: &str| crate::cmd::GradientPreset { name: name.into(), gradient: own.clone() }; + let mut prefs = s.prefs.clone(); + prefs.gradient_presets = + vec![preset("mist"), preset("Mine"), preset("MINE"), preset("Mist 2"), preset("Plain"), preset("PLAIN"), preset("plain")]; + s.apply_prefs(prefs); + let saved: Vec<&str> = s.prefs.gradient_presets.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(saved, ["mist 3", "Mine", "MINE 2", "Mist 2", "Plain", "PLAIN 2", "plain 3"]); + let list = s.execute("gradient.presets.list", &json!({})).unwrap(); + let mut seen = std::collections::HashSet::new(); + assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset"); + // The renamed one applies and deletes; the built-in Mist stays as it was. + s.execute("gradient.presets.apply", &json!({"name": "mist 3"})).unwrap(); + assert_eq!(paint(&s, id, false).gradient, own); + assert_eq!(s.gradient_preset("Mist").unwrap().gradient, mist); + assert_eq!(s.execute("gradient.presets.delete", &json!({"name": "Mist 3"})).unwrap()["deleted"], "mist 3"); + assert!(s.execute("gradient.presets.delete", &json!({"name": "Mist"})).is_err(), "built in"); + assert_eq!(s.prefs.gradient_presets.len(), 6); + // Many presets with one name each get their own number. + let mut prefs = s.prefs.clone(); + prefs.gradient_presets = (0..2000).map(|_| preset("Same")).collect(); + s.apply_prefs(prefs); + let mut seen = std::collections::HashSet::new(); + assert!(s.prefs.gradient_presets.iter().all(|p| seen.insert(p.name.to_lowercase()))); + assert_eq!(s.prefs.gradient_presets.last().map(|p| p.name.as_str()), Some("Same 2000")); +} diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs index d509dfa206..4211511021 100644 --- a/crates/engine/src/tests/guide_clipboard.rs +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -12,7 +12,7 @@ fn run(s: &mut Session, id: &str, p: Value) -> Value { /// The active document's guides: (vertical, pos, layer). fn guides(s: &Session) -> Vec<(bool, f64, Option)> { - s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos, g.layer)).collect() + s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos, g.layer)).collect() } #[test] @@ -31,7 +31,7 @@ fn ruler_guides_copy_and_paste_into_another_document() { let r = run(&mut s, "edit.paste", json!({})); assert_eq!(r["guides"], 2); assert_eq!(guides(&s), [(true, 120.0, Some(layer)), (false, 80.0, Some(layer))], "where they were, not offset"); - assert_eq!(s.doc().unwrap().selection.guides, [0, 1]); + assert_eq!(super::selected_guides(&s), [0, 1]); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); run(&mut s, "edit.undo", json!({})); assert!(guides(&s).is_empty()); @@ -104,9 +104,9 @@ fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() { assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (the app empties the system clipboard)"); let layer = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); run(&mut s, "edit.paste", json!({})); - assert_eq!(s.doc().unwrap().selection.guides, [1], "the first paste selects its own guide"); + assert_eq!(super::selected_guides(&s), [1], "the first paste selects its own guide"); run(&mut s, "edit.paste", json!({})); - assert_eq!(s.doc().unwrap().selection.guides, [2], "the second paste selects its own guide"); + assert_eq!(super::selected_guides(&s), [2], "the second paste selects its own guide"); let g = guides(&s); assert_eq!(g.len(), 3, "two pastes, two more guides: {g:?}"); assert_eq!((g[1].2, g[2].2), (Some(layer), Some(layer)), "on the layer new art goes to"); @@ -116,7 +116,7 @@ fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() { // Hiding that layer hides the guides pasted on it: they follow its visibility (and lock). run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": false})); let st = s.doc().unwrap(); - let shown: Vec = st.doc.guides.iter().map(|g| st.doc.guide_shown(g)).collect(); + let shown: Vec = st.doc.ruler_guides().iter().map(|g| st.doc.guide_shown(g)).collect(); assert_eq!(shown, [true, false, false]); // With an object, the SVG holds the object and no guide. run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": true})); diff --git a/crates/engine/src/tests/halftone.rs b/crates/engine/src/tests/halftone.rs index caef57ddb4..d836502baa 100644 --- a/crates/engine/src/tests/halftone.rs +++ b/crates/engine/src/tests/halftone.rs @@ -65,3 +65,29 @@ fn halftone_options() { assert!(s.execute("object.vectorHalftone", &bad).is_err(), "{bad}"); } } + +#[test] +fn halftone_refuses_a_param_of_the_wrong_type() { + for bad in [ + json!({"frequency": "60"}), + json!({"angle": "30"}), + json!({"shape": 1}), + json!({"mode": true}), + json!({"invert": "true"}), + json!({"clip": "false"}), + json!({"keepOriginal": 1}), + json!({"color": 0}), + ] { + let mut s = session(); + let id = red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("object.vectorHalftone", &bad).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().doc, before, "{bad} changed the document"); + assert!(s.doc().unwrap().doc.node(id).is_some()); + } + // Null stands for an omitted value. + let mut s = session(); + red_rect(&mut s); + let p = json!({"frequency": null, "angle": null, "shape": null, "mode": null, "color": null, "invert": null, "clip": null, "keepOriginal": null}); + assert!(s.execute("object.vectorHalftone", &p).is_ok()); +} diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index 8e26577f94..24a1635c30 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -94,10 +94,49 @@ fn run_fresh( params: &serde_json::Value, ) -> (std::result::Result, Option>) { let (mut s, ..) = doc_with_type(); - let r = s.execute(cmd, params).map_err(|e| e.to_string()); + let r = s.execute(cmd, params).map(|v| without_plugin_effects(cmd, v)).map_err(|e| e.to_string()); (r, s.doc().ok().map(|d| d.doc.clone())) } +/// `cmd`'s result with the plug-in effects (`plugin.`) taken out of `effect.list`'s catalog. +/// The plug-in tests install and remove plug-ins in the process-wide registry while these +/// comparisons run, so two runs of `effect.list` can list different plug-ins. +fn without_plugin_effects(cmd: &str, mut r: serde_json::Value) -> serde_json::Value { + if cmd == "effect.list" + && let Some(catalog) = r.get_mut("catalog").and_then(serde_json::Value::as_array_mut) + { + catalog.retain(|e| !e["id"].as_str().is_some_and(|id| id.starts_with(vectorcraft_plugins::PREFIX))); + } + r +} + +/// Whether two results of `cmd` are the same, apart from the plug-in effects in `effect.list`'s +/// catalog ([`without_plugin_effects`]). +fn same_without_plugin_effects(cmd: &str, x: &serde_json::Value, y: &serde_json::Value) -> bool { + if cmd == "effect.list" { without_plugin_effects(cmd, x.clone()) == without_plugin_effects(cmd, y.clone()) } else { x == y } +} + +/// Two `effect.list` results that differ only in a plug-in effect in the catalog compare the same; +/// a difference in a built-in effect, in `applied` or in `activeItem`, or in another command's +/// result, does not. +#[test] +fn plugin_effects_are_left_out_of_the_effect_list_comparison() { + let list = |catalog: &[&str], applied: serde_json::Value, active: serde_json::Value| { + let catalog: Vec<_> = catalog.iter().map(|id| json!({"id": id, "label": id})).collect(); + json!({"catalog": catalog, "applied": applied, "activeItem": active}) + }; + let base = list(&["stylize.dropShadow"], json!([]), json!(null)); + let with_plugin = list(&["stylize.dropShadow", "plugin.test.glow"], json!([]), json!(null)); + assert!(same_without_plugin_effects("effect.list", &base, &with_plugin)); + assert!(same_without_plugin_effects("effect.list", &with_plugin, &base)); + assert_eq!(without_plugin_effects("effect.list", with_plugin.clone()), base); + assert!(!same_without_plugin_effects("effect.list", &base, &list(&[], json!([]), json!(null))), "a built-in effect"); + assert!(!same_without_plugin_effects("effect.list", &base, &list(&["stylize.dropShadow"], json!([{"id": 3}]), json!(null))), "applied"); + assert!(!same_without_plugin_effects("effect.list", &base, &list(&["stylize.dropShadow"], json!([]), json!(0))), "activeItem"); + assert!(!same_without_plugin_effects("object.transform", &base, &with_plugin), "another command"); + assert_eq!(without_plugin_effects("object.transform", with_plugin.clone()), with_plugin); +} + /// Every command whose params description names both `id` and `ids` (`{ids?|id?}`, `{id?, ids?: /// … (instead of id)}`), with nothing selected: `id` does what `ids` of that one object does (the /// same result or the same error, and the same document), for objects of the document and for an @@ -265,7 +304,7 @@ fn ids_and_selection(cmd: &str, picks: &[usize]) -> std::result::Result x == y, + (Ok(x), Ok(y)) => same_without_plugin_effects(cmd, x, y), (Err(x), Err(y)) => x.to_string() == y.to_string(), _ => false, }; @@ -436,9 +475,7 @@ fn an_ids_entry_that_is_not_an_id_is_refused_and_changes_nothing() { /// With the rectangle apart (`d`) selected, the same commands with `ids` (or `slices`) left out and /// with it null do the same: what the selection's list does for the commands that take the /// selection, and the command's own default for the others (`object.slice.select` deselects the -/// slices). `addon.color.filter` and `addon.color.applyNearestSwatch` read `ids` through -/// [`cmd::checked_ids_or_selection`], which refuses null as a value that is not a list and changes -/// nothing. +/// slices). #[test] fn ids_left_out_or_null_take_the_selection_or_the_default() { let (_, [.., d], _) = doc_with_type(); @@ -450,15 +487,7 @@ fn ids_left_out_or_null_take_the_selection_or_the_default() { let mut null = params.clone(); null[key] = serde_json::Value::Null; let with_null = outcome(cmd, &null, &[d], slice); - if matches!(cmd, "addon.color.filter" | "addon.color.applyNearestSwatch") { - let (mut s, ..) = doc_with_type(); - s.execute("select.set", &json!({ "ids": [d] })).unwrap(); - let st = s.doc().unwrap(); - let refused = with_null.0.as_ref().is_err_and(|e| e.ends_with("ids must be an array of non-negative integer object ids")); - if !refused || (&with_null.1, &with_null.2, with_null.3) != (&*st.doc, &st.selection, st.history.undo.len()) { - failures.push(format!("{cmd} {key}: null is not refused with nothing changed ({:.160?})", with_null.0)); - } - } else if with_null != left_out { + if with_null != left_out { failures.push(format!("{cmd} {key}: null does not do what leaving it out does ({:.160?})", left_out.0)); } let mut listed = params.clone(); @@ -477,6 +506,65 @@ fn ids_left_out_or_null_take_the_selection_or_the_default() { assert!(failures.is_empty(), "{} fail:\n{}", failures.len(), failures.join("\n")); } +/// The commands that read `ids` through [`cmd::checked_ids_or_selection`] take `ids: null` as left +/// out: with the rectangle apart (`d`) or the type object (`t`) selected, null gives the same +/// result or error, document, selection and undo history as leaving `ids` out. Print Ink Fixes +/// runs in a CMYK document. +#[test] +fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() { + let (_, [.., d], t) = doc_with_type(); + let mut failures = vec![]; + let (rect, both, text) = (&[d][..], &[d, t][..], &[t][..]); + let cases = [ + ("addon.arrange.randomizeOpacity", json!({"seed": 1}), rect), + ("addon.arrange.sort", json!({"by": "area", "apply": "x"}), both), + ("addon.cleanup.simplify", json!({}), rect), + ("addon.cleanup.deepUngroup", json!({}), rect), + ("addon.cleanup.rejoin", json!({}), rect), + ("addon.color.nearestSwatch", json!({}), rect), + ("addon.pathtools.cornerSet", json!({"radius": 2}), rect), + ("addon.pathtools.cornerRemove", json!({}), rect), + ("addon.pathtools.shape.convert", json!({}), rect), + ("addon.pathtools.erase", json!({"points": [[0, 20], [200, 20]]}), rect), + ("addon.pathtools.crossings", json!({}), rect), + ("addon.pathtools.expandDashes", json!({}), rect), + ("object.path.smooth", json!({}), rect), + ("object.textWrap.make", json!({}), rect), + ("object.textWrap.release", json!({}), rect), + ("object.textWrap.options", json!({}), rect), + ("variable.bind", json!({"variable": "v"}), rect), + ("variable.unbind", json!({}), rect), + ("addon.cleanup.breakText", json!({}), text), + ("addon.cleanup.combineText", json!({}), text), + ("addon.cleanup.joinText", json!({}), text), + ("addon.cleanup.removeBreaks", json!({"kind": "line"}), text), + ("addon.cleanup.resetTextTransform", json!({}), text), + ("addon.cleanup.alignInPlace", json!({"align": "left"}), text), + ]; + for (cmd, params, selected) in cases { + let left_out = outcome(cmd, ¶ms, selected, false); + let mut null = params.clone(); + null["ids"] = serde_json::Value::Null; + let with_null = outcome(cmd, &null, selected, false); + if with_null != left_out { + failures.push(format!("{cmd}: null gives {:.160?}; left out gives {:.160?}", with_null.0, left_out.0)); + } + } + let print_fixes = |p: &serde_json::Value| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "colorMode": "cmyk", "created": null})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let r = s.execute("addon.color.printFixes", p).map_err(|e| e.to_string()); + let st = s.doc().unwrap(); + (r, (*st.doc).clone(), st.selection.clone(), st.history.undo.len()) + }; + let (left_out, with_null) = (print_fixes(&json!({"inkLimit": 200})), print_fixes(&json!({"inkLimit": 200, "ids": null}))); + if with_null != left_out { + failures.push(format!("addon.color.printFixes: null gives {:.160?}; left out gives {:.160?}", with_null.0, left_out.0)); + } + assert!(failures.is_empty(), "{} fail:\n{}", failures.len(), failures.join("\n")); +} + /// With no document open, every command that takes `ids` refuses a list with an entry that is not /// a non-negative integer, and a value that is not a list, with the same error as with a document /// open (`effect.list` and `links.findFiles` run without a document). diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 7dd2983c29..f6ee8015be 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -128,6 +128,39 @@ fn a_batch_passes_its_artboard_to_each_step_when_it_runs() { assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "in the new document"); } +/// A Paste in Place, in Front or in Back step that names `artboards` keeps them inside a batch +/// given `artboard`, and pastes a copy on each; one that names neither takes the batch's artboard, +/// unless the Artboard tool is chosen with several artboards selected: then it pastes on those. +#[test] +fn a_batch_keeps_the_artboards_a_paste_step_names() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + let boards: Vec<_> = s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + s.execute("shape.rectangle", &json!({"x": boards[0].x0 + 10.0, "y": boards[0].y0 + 10.0, "width": 20, "height": 20})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let step = |command: &str, params: Value| json!({"command": command, "params": params}); + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + let origins = |r: &Value, s: &Session| { + let ids = r["results"][0]["ids"].as_array().unwrap().iter().map(|i| vectorcraft_doc::NodeId(i.as_u64().unwrap())).collect::>(); + ids.iter().map(|i| s.doc().unwrap().doc.bounds_of(&[*i], false).unwrap().origin().x).collect::>() + }; + let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({"artboards": [0, 2]}))]})).unwrap(); + assert_eq!(origins(&r, &s), [boards[0].x0 + 10.0, boards[2].x0 + 10.0], "{id}"); + let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({}))]})).unwrap(); + assert_eq!(origins(&r, &s), [boards[1].x0 + 10.0], "{id}: the batch's artboard"); + } + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 0])); + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({}))]})).unwrap(); + let ids = r["results"][0]["ids"].as_array().unwrap().iter().map(|i| vectorcraft_doc::NodeId(i.as_u64().unwrap())).collect::>(); + let xs: Vec = ids.iter().map(|i| s.doc().unwrap().doc.bounds_of(&[*i], false).unwrap().origin().x).collect(); + assert_eq!(xs, [boards[0].x0 + 10.0, boards[2].x0 + 10.0], "{id}: the Artboard tool's selection"); + let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({"artboard": 1}))]})).unwrap(); + assert_eq!(r["results"][0]["ids"].as_array().map(Vec::len), Some(1), "{id}: a step's own `artboard` wins"); + } +} + /// A batch passes its `artboard` to each Fit to Artwork Bounds and Fit to Selected Art step that /// names no `index`, as their `index` (past the document's last artboard, the last one), and a /// step's own `index` is kept. A recorded action leaves out the `index` or `indices` the app diff --git a/crates/engine/src/tests/keyguide.rs b/crates/engine/src/tests/keyguide.rs index 09acdd726d..327c0b4b24 100644 --- a/crates/engine/src/tests/keyguide.rs +++ b/crates/engine/src/tests/keyguide.rs @@ -37,14 +37,14 @@ fn a_clicked_guide_is_the_key_and_align_lines_the_objects_up_on_it() { // Click an object, Shift-click the guide, then click the guide again. click(&mut s, 110.0, 110.0, false); click(&mut s, 500.0, 400.0, true); - assert_eq!((s.doc().unwrap().selection.objects.clone(), s.doc().unwrap().selection.guides.clone()), (vec![a], vec![0])); + assert_eq!((s.doc().unwrap().selection.objects.clone(), super::selected_guides(&s)), (vec![a], vec![0])); click(&mut s, 500.0, 400.0, false); - assert_eq!(s.doc().unwrap().selection.key_guide, Some(0), "the guide is the key"); + assert_eq!(super::key_guide(&s), Some(0), "the guide is the key"); assert_eq!(s.execute("document.inspect", &json!({})).unwrap()["keyGuide"], 0); // Shift-click a third object: the guide stays the key. click(&mut s, 310.0, 260.0, true); assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]); - assert_eq!(s.doc().unwrap().selection.key_guide, Some(0)); + assert_eq!(super::key_guide(&s), Some(0)); let (ya, yb) = (bounds(&s, a).y0, bounds(&s, b).y0); s.execute("object.align", &json!({"horizontal": "center", "vertical": "center"})).unwrap(); // Both centred on the guide's x; a vertical guide fixes no y, so they keep theirs. @@ -52,12 +52,12 @@ fn a_clicked_guide_is_the_key_and_align_lines_the_objects_up_on_it() { let r = bounds(&s, id); assert!((r.center().x - 500.0).abs() < 1e-6 && (r.y0 - y).abs() < 1e-6, "{id:?}: {r:?}"); } - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 500.0, "the guide stays put"); + assert_eq!(positions(&s)[0], 500.0, "the guide stays put"); s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); assert!((bounds(&s, a).x0 - 500.0).abs() < 1e-6 && (bounds(&s, b).x0 - 500.0).abs() < 1e-6); // A click on the key guide again: no key. click(&mut s, 500.0, 400.0, false); - assert_eq!(s.doc().unwrap().selection.key_guide, None); + assert_eq!(super::key_guide(&s), None); } #[test] @@ -96,22 +96,22 @@ fn select_key_takes_only_a_selected_guide_with_objects() { s.execute("select.key", &json!({"guide": 1})).unwrap(); // An object key replaces the guide key, and the other way round. s.execute("select.key", &json!({"id": b.0})).unwrap(); - assert_eq!((s.doc().unwrap().selection.key, s.doc().unwrap().selection.key_guide), (Some(b), None)); + assert_eq!((s.doc().unwrap().selection.key, super::key_guide(&s)), (Some(b), None)); s.execute("select.key", &json!({"guide": 1})).unwrap(); - assert_eq!((s.doc().unwrap().selection.key, s.doc().unwrap().selection.key_guide), (None, Some(1))); + assert_eq!((s.doc().unwrap().selection.key, super::key_guide(&s)), (None, Some(1))); // Deleting a guide before it keeps the key on the same guide. s.execute("guide.remove", &json!({"index": 0})).unwrap(); - assert_eq!(s.doc().unwrap().selection.key_guide, Some(0)); - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 600.0); + assert_eq!(super::key_guide(&s), Some(0)); + assert_eq!(positions(&s)[0], 600.0); // Taking the guide out of the selection, or every object, lets the key go. s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); - assert_eq!(s.doc().unwrap().selection.key_guide, None); + assert_eq!(super::key_guide(&s), None); s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); s.execute("select.key", &json!({"guide": 0})).unwrap(); s.execute("select.toggle", &json!({"id": a.0})).unwrap(); - assert_eq!(s.doc().unwrap().selection.key_guide, Some(0), "one object is enough"); + assert_eq!(super::key_guide(&s), Some(0), "one object is enough"); s.execute("select.toggle", &json!({"id": b.0})).unwrap(); - assert_eq!(s.doc().unwrap().selection.key_guide, None, "no object to align"); + assert_eq!(super::key_guide(&s), None, "no object to align"); } #[test] @@ -141,12 +141,12 @@ fn selected_guides_align_to_a_clicked_key_object() { click(&mut s, 110.0, 110.0, false); click(&mut s, 500.0, 300.0, true); click(&mut s, 300.0, 400.0, true); - assert_eq!(s.doc().unwrap().selection.guides, vec![0, 1]); + assert_eq!(super::selected_guides(&s), vec![0, 1]); click(&mut s, 110.0, 110.0, false); assert_eq!(s.doc().unwrap().selection.key, Some(a), "the object is the key"); let before = bounds(&s, a); s.execute("object.align", &json!({"horizontal": "center", "vertical": "center"})).unwrap(); - let guides = |s: &Session| s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect::>(); + let guides = positions; assert_eq!(guides(&s), [120.0, 110.0], "the vertical guide on the centre's x, the horizontal one on its y"); assert_eq!(bounds(&s, a), before, "the key stays put"); s.execute("object.align", &json!({"horizontal": "right"})).unwrap(); @@ -174,15 +174,15 @@ fn guides_align_to_a_key_object_among_others_and_parallel_ones_to_a_key_guide() s.execute("select.key", &json!({"id": b.0})).unwrap(); s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); assert_eq!(bounds(&s, a).x0, 300.0); - assert!(s.doc().unwrap().doc.guides.iter().all(|g| g.pos == 300.0)); + assert!(positions(&s).iter().all(|p| *p == 300.0)); // Aligning to the selection leaves guides alone. s.execute("object.align", &json!({"horizontal": "right", "to": "selection"})).unwrap(); - assert!(s.doc().unwrap().doc.guides.iter().all(|g| g.pos == 300.0)); + assert!(positions(&s).iter().all(|p| *p == 300.0)); // A key guide stays put, and the other vertical guide lines up on it. s.execute("guide.move", &json!({"index": 1, "pos": 700})).unwrap(); s.execute("select.key", &json!({"guide": 1})).unwrap(); s.execute("object.align", &json!({"horizontal": "center"})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect::>(), [700.0, 700.0]); + assert_eq!(positions(&s), [700.0, 700.0]); } /// Objects 40 pt wide at `xs` (y 100) and a vertical guide at `pos` that is their key. @@ -208,7 +208,7 @@ fn distribute_with_a_spacing_spaces_the_objects_from_a_key_guide() { for (h, want) in [("left", [330.0, 340.0, 360.0]), ("center", [310.0, 320.0, 340.0]), ("right", [290.0, 300.0, 320.0])] { s.execute("object.distribute", &json!({"horizontal": h, "spacing": 10})).unwrap(); assert_eq!(lefts(&s, &ids), want, "{h}"); - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 350.0, "{h}: the guide stays put"); + assert_eq!(positions(&s)[0], 350.0, "{h}: the guide stays put"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(lefts(&s, &ids), [100.0, 300.0, 500.0], "{h}: one undo step"); } @@ -300,14 +300,14 @@ fn guides_alone(vertical: &[f64], horizontal: &[f64]) -> Session { /// Selects the objects `ids` and the ruler guides `guides`, and nothing else. fn select_with_guides(s: &mut Session, ids: &[NodeId], guides: &[usize]) { s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); - let now = s.doc().unwrap().selection.guides.clone(); - let flip: Vec = (0..s.doc().unwrap().doc.guides.len()).filter(|i| now.contains(i) != guides.contains(i)).collect(); + let now = super::selected_guides(s); + let flip: Vec = (0..positions(s).len()).filter(|i| now.contains(i) != guides.contains(i)).collect(); s.execute("guide.select", &json!({"indexes": flip, "toggle": true})).unwrap(); assert_eq!((s.doc().unwrap().selection.objects.len(), s.doc().unwrap().selection.guides.len()), (ids.len(), guides.len())); } fn positions(s: &Session) -> Vec { - s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect() + s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect() } #[test] diff --git a/crates/engine/src/tests/library_roots.rs b/crates/engine/src/tests/library_roots.rs new file mode 100644 index 0000000000..30a8776b35 --- /dev/null +++ b/crates/engine/src/tests/library_roots.rs @@ -0,0 +1,239 @@ +//! The swatch, brush, symbol and graphic style library commands under automation roots: a confined +//! request sees a library's file, the user library folder and the path in a loaded library's id only +//! inside its read roots, and the id it is shown finds the library. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::file_access::{AutomationRoots, confine}; +use crate::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn text(p: &Path) -> String { + p.to_string_lossy().to_string() +} + +/// A fresh scratch folder for one test, with the folders `in`, `out`, `a`, `b` and `user`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-library-roots-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for sub in ["in", "out", "a", "b", "user"] { + std::fs::create_dir_all(dir.join(sub)).unwrap(); + } + dir +} + +/// One kind of library and its commands. +struct Kind { + name: &'static str, + list: &'static str, + get: &'static str, + save: &'static str, + load: &'static str, + ext: &'static str, + /// Adds an item named by the second argument to the document. + add: fn(&mut Session, &str), + set_user_dir: fn(&mut Session, Option), +} + +fn rectangle(s: &mut Session) -> u64 { + run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap() +} + +const SWATCHES: Kind = Kind { + name: "swatches", + list: "swatch.library.list", + get: "swatch.library.get", + save: "swatch.library.save", + load: "swatch.library.load", + ext: "vcswatches", + add: |s, name| { + run(s, "swatch.new", json!({"name": name, "color": "#3366cc"})); + }, + set_user_dir: |s, dir| s.swatch_libraries.set_user_dir(dir), +}; + +const BRUSHES: Kind = Kind { + name: "brushes", + list: "brush.libraries", + get: "brush.library", + save: "brush.saveLibrary", + load: "brush.loadLibrary", + ext: crate::cmd::brushlib::BRUSHES_EXT, + add: |s, name| { + run(s, "brush.new", json!({"type": "calligraphic", "name": name, "params": {"angle": 20, "roundness": 40, "size": 7}})); + }, + set_user_dir: |s, dir| s.brush_libraries.set_user_dir(dir), +}; + +const SYMBOLS: Kind = Kind { + name: "symbols", + list: "symbol.libraries", + get: "symbol.library", + save: "symbol.saveLibrary", + load: "symbol.loadLibrary", + ext: crate::cmd::symbollib::SYMBOLS_EXT, + add: |s, name| { + let id = rectangle(s); + run(s, "symbol.new", json!({"name": name, "ids": [id]})); + }, + set_user_dir: |s, dir| s.symbol_libraries.set_user_dir(dir), +}; + +const STYLES: Kind = Kind { + name: "styles", + list: "graphicStyle.libraries", + get: "graphicStyle.library", + save: "graphicStyle.saveLibrary", + load: "graphicStyle.loadLibrary", + ext: vectorcraft_doc::style_libs::STYLES_EXT, + add: |s, name| { + let id = rectangle(s); + run(s, "graphicStyle.new", json!({"name": name, "id": id})); + }, + set_user_dir: |s, dir| s.style_libraries.set_user_dir(dir), +}; + +/// The loaded libraries of a list reply: id, path and count. +fn loaded(list: &Value) -> Vec<(Value, Value, Value)> { + let libs = list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "loaded"); + libs.map(|l| (l["id"].clone(), l["path"].clone(), l["count"].clone())).collect() +} + +/// Does `reply` hold `path` anywhere, as JSON writes it? +fn holds(reply: &Value, path: &Path) -> bool { + let written = json!(text(path)).to_string(); + reply.to_string().contains(written.trim_matches('"')) +} + +/// Three libraries the person loaded, one inside the client's read root and two outside it in +/// different folders under the same file name (the one in `b` holds one more item), and a user +/// library folder outside the root. → the session, the folder and the three files. +fn three_libraries(kind: &Kind, test: &str) -> (Session, PathBuf, [PathBuf; 3]) { + let base = folder(&format!("{}-{test}", kind.name)); + let file = format!("Kit.{}", kind.ext); + let files = [base.join("in").join(&file), base.join("a").join(&file), base.join("b").join(&file)]; + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + (kind.add)(&mut s, "First"); + for path in &files[..2] { + run(&mut s, kind.save, json!({"path": text(path), "name": "Kit"})); + } + (kind.add)(&mut s, "Second"); + run(&mut s, kind.save, json!({"path": text(&files[2]), "name": "Kit"})); + (kind.set_user_dir)(&mut s, Some(text(&base.join("user")))); + for path in &files { + run(&mut s, kind.load, json!({"path": text(path)})); + } + (s, base, files) +} + +fn lists_leave_out_paths_outside_the_read_root(kind: &Kind) { + let (mut s, base, [inside, a, b]) = three_libraries(kind, "list"); + let file = format!("Kit.{}", kind.ext); + let person = run(&mut s, kind.list, json!({})); + let rows = loaded(&person); + assert_eq!(rows.len(), 3, "{person}"); + let (small, large) = (rows[1].2.clone(), rows[2].2.clone()); + assert_ne!(small, large, "{person}"); + let row = |p: &Path, count: &Value| (json!(format!("loaded/{}", text(p))), json!(text(p)), count.clone()); + assert_eq!(rows, [row(&inside, &small), row(&a, &small), row(&b, &large)], "the person sees every path: {person}"); + assert_eq!(person["userFolder"], json!(text(&base.join("user")))); + + // The client sees the paths inside its read root; the others' rows stay, in the same order, + // under the file's name, numbered in the order of their full ids. + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap(); + let client = confine(roots.as_ref(), || run(&mut s, kind.list, json!({}))); + let shown = [format!("loaded/{file}"), format!("loaded/{file} (2)")]; + let hidden = |id: &str, count: &Value| (json!(id), Value::Null, count.clone()); + assert_eq!(loaded(&client), [row(&inside, &small), hidden(&shown[0], &small), hidden(&shown[1], &large)], "{client}"); + assert_eq!(client["userFolder"], Value::Null, "{client}"); + for outside in ["a", "b", "user", "out"] { + assert!(!holds(&client, &base.join(outside)), "no path outside the read root: {client}"); + } + let everything = |l: &Value| l["libraries"].as_array().unwrap().iter().map(|l| (l["name"].clone(), l["category"].clone())).collect::>(); + assert_eq!(everything(&client), everything(&person), "every library is still listed"); + + // The id shown finds its library, and replies about it show that id. + let got = confine(roots.as_ref(), || run(&mut s, kind.get, json!({"library": shown[1]}))); + assert_eq!(got["id"], json!(shown[1]), "{got}"); + assert!(!holds(&got, &base.join("b")), "{got}"); + let got = confine(roots.as_ref(), || run(&mut s, kind.get, json!({"library": shown[0]}))); + assert_eq!(got["id"], json!(shown[0]), "{got}"); + assert!(s.execute(kind.get, &json!({"library": shown[0]})).is_err(), "the person has no such id"); + assert_eq!(run(&mut s, kind.list, json!({})), person, "the person's list is not changed"); + + // A write root alone lets the client read none of them. + let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap(); + let client = confine(write_only.as_ref(), || run(&mut s, kind.list, json!({}))); + assert!(loaded(&client).iter().all(|(_, path, _)| path.is_null()), "{client}"); + assert!(!holds(&client, &base), "{client}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn swatch_library_list_leaves_out_paths_outside_the_read_root() { + lists_leave_out_paths_outside_the_read_root(&SWATCHES); +} + +#[test] +fn brush_libraries_leave_out_paths_outside_the_read_root() { + lists_leave_out_paths_outside_the_read_root(&BRUSHES); +} + +#[test] +fn symbol_libraries_leave_out_paths_outside_the_read_root() { + lists_leave_out_paths_outside_the_read_root(&SYMBOLS); +} + +#[test] +fn graphic_style_libraries_leave_out_paths_outside_the_read_root() { + lists_leave_out_paths_outside_the_read_root(&STYLES); +} + +/// Adding from a concealed library, copying it into the user library folder and saving into that +/// folder show neither the library's file nor the folder outside the read root. +#[test] +fn swatch_library_replies_leave_out_paths_outside_the_read_root() { + let (mut s, base, [inside, ..]) = three_libraries(&SWATCHES, "replies"); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap(); + let shown = "loaded/Kit.vcswatches"; + let added = confine(roots.as_ref(), || run(&mut s, "swatch.library.add", json!({"library": shown, "names": ["First"]}))); + assert_eq!(added["library"], shown, "{added}"); + // A library whose file is outside the root is not copied, and the error does not name the file. + let refused = confine(roots.as_ref(), || s.execute("swatch.library.copyToUser", &json!({"library": shown}))); + let message = refused.map(|r| r.to_string()).unwrap_err().to_string(); + assert!(message.contains("outside the read roots"), "{message}"); + assert!(!message.contains(&text(&base)) && !message.contains("Kit.vcswatches"), "{message}"); + assert!(!base.join("user/Kit.vcswatches").exists()); + // The file inside the root is copied into the user library folder, which is outside it. + let mine = format!("loaded/{}", text(&inside)); + let copied = confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": mine}))); + assert_eq!((copied["library"].as_str(), copied["copied"].as_bool()), (Some("user/Kit.vcswatches"), Some(true)), "{copied}"); + assert_eq!(copied["path"], Value::Null, "{copied}"); + let saved = confine(roots.as_ref(), || run(&mut s, "swatch.library.save", json!({"user": true, "name": "Mine"}))); + assert_eq!((saved["library"].as_str(), saved.get("path")), (Some("user/Mine.vcswatches"), None), "{saved}"); + for reply in [&added, &copied, &saved] { + assert!(!holds(reply, &base.join("a")) && !holds(reply, &base.join("user")), "{reply}"); + } + // A library loaded from data under the file name keeps its id; each concealed one takes the next + // free one, so no two rows share an id. + let data = run(&mut s, "swatch.library.save", json!({}))["data"].as_str().unwrap().to_string(); + run(&mut s, "swatch.library.load", json!({"data": data, "name": "Kit.vcswatches"})); + let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({}))); + let ids: Vec = loaded(&list).into_iter().map(|(id, ..)| id).collect(); + assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches")], "{list}"); + // Copied into the user library folder, it is still found by that id, which no other library takes. + confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": "loaded/Kit.vcswatches"}))); + let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({}))); + let ids: Vec = loaded(&list).into_iter().map(|(id, ..)| id).collect(); + assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)")], "{list}"); + // The person sees the folder. + let saved = run(&mut s, "swatch.library.save", json!({"user": true, "name": "Theirs"})); + assert_eq!(saved["path"], json!(text(&base.join("user").join("Theirs.vcswatches")))); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/linkfiles.rs b/crates/engine/src/tests/linkfiles.rs index 695ea41419..ef9127042a 100644 --- a/crates/engine/src/tests/linkfiles.rs +++ b/crates/engine/src/tests/linkfiles.rs @@ -271,7 +271,7 @@ fn stop_ends_only_the_search_it_names() { let (tx, rx) = mpsc::channel(); let search = findfiles::start(root.clone(), s.search_rules.clone(), Limits::default(), 1, 2, Arc::new(Blocked(Mutex::new(rx)))).unwrap(); let links = vec![Sought { name: "a.png".into(), path: "/gone/a.png".into(), ids: vec![], size: None, hash: None }]; - s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), links, sizes: Arc::default(), search }); + s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), doc: None, links, sizes: Arc::default(), search }); let until = Instant::now() + WAIT; while s.execute("links.findFiles", &json!({})).unwrap()["searched"]["read"] != 1 && Instant::now() < until { std::thread::sleep(Duration::from_millis(2)); @@ -284,6 +284,116 @@ fn stop_ends_only_the_search_it_names() { drop(tx); } +/// A caller confined by read roots sees, in the replies to a search another caller started and to +/// its own, only the paths inside its read roots: the files found outside them, a link's saved path +/// outside them and the folder searched are left out, and the rows, ids and counts stay. Without +/// roots, the replies are as before. +#[test] +fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() { + let root = folder("read-roots"); + let mut s = session_for(&root); + let photo = png(40, 30, RED); + write(&root.join("lrf-away/photo.png"), &photo); + let id = placed(&mut s, &root.join("lrf-away/photo.png")); + std::fs::remove_file(root.join("lrf-away/photo.png")).unwrap(); + // Files of the name with other contents: the search reads every folder. + let other = png(40, 30, BLUE); + let (home, wide) = (root.join("home"), root.join("lrf-wide")); + write(&home.join("photo.png"), &other); + write(&wide.join("photo.png"), &other); + let roots = |read: &[&Path], write: &[&Path]| crate::file_access::AutomationRoots::new(read, write).unwrap().unwrap(); + let (narrow, write_only, broad) = (roots(&[&home], &[]), roots(&[], &[&root]), roots(&[&root], &[])); + let ask = |s: &mut Session, r: &Arc, p: Value| { + crate::file_access::confine(Some(r), || s.execute("links.findFiles", &p).unwrap()) + }; + let hidden = |r: &Value| { + let text = r.to_string(); + assert!(!text.contains("lrf-away") && !text.contains("lrf-wide") && r.get("folder").is_none(), "{r}"); + let row = &r["links"][0]; + assert_eq!((row["name"].as_str(), &row["ids"], row.get("path")), (Some("photo.png"), &json!([id]), None), "{r}"); + }; + // Started with the broad roots, over the whole folder. + let r = ask(&mut s, &broad, json!({"folder": root})); + assert_eq!(r["folder"], json!(root), "{r}"); + finished(&mut s); + let all = ask(&mut s, &broad, json!({})); + assert_eq!(all["links"][0]["files"].as_array().map(Vec::len), Some(2), "{all}"); + for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] { + hidden(&r); + assert_eq!(r["links"][0]["files"], json!([{"path": home.join("photo.png"), "size": other.len(), "match": "name"}]), "{r}"); + assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}"); + } + let r = ask(&mut s, &write_only, json!({})); + hidden(&r); + assert_eq!(r["links"][0]["files"], json!([]), "{r}"); + // Without roots, every path shows. + let r = s.execute("links.findFiles", &json!({})).unwrap(); + assert_eq!((&r["folder"], &r["links"][0]["path"]), (&json!(root), &json!(root.join("lrf-away/photo.png"))), "{r}"); + assert_eq!(r["links"][0]["files"].as_array().map(Vec::len), Some(2), "{r}"); + // The narrow caller's own search shows the folder it gave. + let r = ask(&mut s, &narrow, json!({"folder": home})); + assert_eq!(r["folder"], json!(home), "{r}"); + finished(&mut s); + let r = ask(&mut s, &narrow, json!({})); + assert_eq!((&r["folder"], r["links"][0].get("path")), (&json!(home), None), "{r}"); + // A search that failed: the reason shows without the path to a caller outside its folder. + ask(&mut s, &broad, json!({"folder": root.join("lrf-wide/gone")})); + let r = finished(&mut s); + assert!(r["error"].as_str().is_some_and(|e| e.contains("lrf-wide")), "{r}"); + let r = ask(&mut s, &narrow, json!({})); + assert_eq!((r["state"].as_str(), r["error"].as_str()), (Some("failed"), Some("the folder can't be read")), "{r}"); + hidden(&r); + let _ = std::fs::remove_dir_all(&root); +} + +/// A link's saved path relative to the document is shown to a confined caller when it leads to a +/// file inside its read roots, and left out when `..` leads out of them. +#[test] +fn a_relative_link_path_is_judged_from_the_documents_folder() { + let root = folder("read-roots-relative"); + let mut s = session_for(&root); + let home = root.join("home"); + write(&root.join("lrf-away/photo.png"), &png(40, 30, RED)); + let id = placed(&mut s, &root.join("lrf-away/photo.png")); + std::fs::create_dir_all(&home).unwrap(); + s.execute("document.save", &json!({"path": home.join("poster.vectorcraft")})).unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&home], &[]).unwrap().unwrap(); + for (saved, shown) in [("sub/photo.png", true), ("../lrf-away/photo.png", false)] { + s.edit("relative 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(); + let r = crate::file_access::confine(Some(&narrow), || s.execute("links.findFiles", &json!({"folder": home, "ids": [id]})).unwrap()); + assert_eq!(r["links"][0].get("path"), shown.then(|| json!(saved)).as_ref(), "{saved}: {r}"); + finished(&mut s); + } + let _ = std::fs::remove_dir_all(&root); +} + +/// `image.info` leaves a linked file outside the confined caller's read roots unnamed (`link` +/// null), as `links.info` leaves it out, and keeps the other fields. +#[test] +fn image_info_leaves_out_a_link_outside_the_read_roots() { + let root = folder("read-roots-info"); + let mut s = session_for(&root); + let pic = root.join("lrf-away/photo.png"); + write(&pic, &png(40, 30, RED)); + let id = placed(&mut s, &pic); + std::fs::create_dir_all(root.join("home")).unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&root.join("home")], &[]).unwrap().unwrap(); + let ask = |s: &mut Session, cmd: &str| crate::file_access::confine(Some(&narrow), || s.execute(cmd, &json!({"id": id})).unwrap()); + let r = ask(&mut s, "image.info"); + assert_eq!((&r["link"], &r["linked"], &r["pixelWidth"], &r["id"]), (&Value::Null, &json!(true), &json!(40), &json!(id)), "{r}"); + assert!(!r.to_string().contains("lrf-away"), "{r}"); + let info = ask(&mut s, "links.info"); + assert!(info.get("link").is_none() && !info.to_string().contains("lrf-away"), "{info}"); + assert_eq!(s.execute("image.info", &json!({"id": id})).unwrap()["link"], json!(pic)); + let _ = std::fs::remove_dir_all(&root); +} + #[test] fn relinking_with_copy_puts_the_file_in_the_documents_folder() { let root = folder("copy"); diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index 56784b69d9..f029eccd3d 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -296,6 +296,59 @@ fn link_info_stays_within_the_asking_callers_roots() { assert_ne!(i["status"], "ok", "{i}"); } +/// A confined caller's `links.list`, `links.check` and `links.info` replies, and its +/// `document.open` reply, leave out the path and folder of a linked file outside its read roots +/// and keep the row with the file's name. A file found by name inside the roots shows its path. +#[test] +fn link_paths_outside_the_read_roots_are_left_out() { + let away = Folder::new("lrr-away"); + let home = Folder::new("lrr-home"); + let pic = away.file("photo.png"); + let bytes = png(60, 30, RED); + write(&pic, &bytes); + let mut s = session(); + let id = place(&mut s, &pic); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap(); + let ask = |s: &mut Session, cmd: &str, p: Value| crate::file_access::confine(Some(&roots), || run(s, cmd, p)); + let hidden = |r: &Value| assert!(!r.to_string().contains("lrr-away"), "{r}"); + let list = ask(&mut s, "links.list", json!({})); + hidden(&list); + let row = &list["links"][0]; + assert_eq!((row["id"].as_u64(), row["name"].as_str(), row["status"].as_str()), (Some(id.0), Some("photo.png"), Some("missing")), "{list}"); + let check = ask(&mut s, "links.check", json!({})); + hidden(&check); + assert_eq!((check["links"][0]["name"].as_str(), check["missing"].as_u64()), (Some("photo.png"), Some(1)), "{check}"); + let info = ask(&mut s, "links.info", json!({"id": id.0})); + hidden(&info); + assert_eq!( + (info["fileName"].as_str(), info["status"].as_str(), info["linked"].as_bool()), + (Some("photo.png"), Some("missing"), Some(true)), + "{info}" + ); + for k in ["path", "link", "location", "fileSize", "modified", "created"] { + assert!(info.get(k).is_none(), "{k}: {info}"); + } + // Unconfined, the same replies carry the paths. + assert_eq!(run(&mut s, "links.list", json!({}))["links"][0]["path"], json!(pic)); + let i = run(&mut s, "links.info", json!({"id": id.0})); + assert_eq!((&i["path"], &i["link"], i["fileSize"].as_u64()), (&json!(pic), &json!(pic), Some(bytes.len() as u64)), "{i}"); + // Saved inside the roots next to a copy of the file: the copy is found by name and shown. + save(&mut s, &home.file("poster.vectorcraft")); + let copy = home.file("photo.png"); + write(©, &bytes); + let check = ask(&mut s, "links.check", json!({})); + hidden(&check); + assert_eq!((check["links"][0]["status"].as_str(), &check["links"][0]["found"]), (Some("ok"), &json!(copy)), "{check}"); + let list = ask(&mut s, "links.list", json!({})); + hidden(&list); + assert_eq!(list["links"][0]["found"], json!(copy), "{list}"); + // Opened again without the copy: the missing link's row has no path. + std::fs::remove_file(©).unwrap(); + let opened = ask(&mut Session::new(), "document.open", json!({"path": home.file("poster.vectorcraft")})); + hidden(&opened); + assert_eq!(opened["missingLinks"][0]["name"], "photo.png", "{opened}"); +} + /// A 600×300 pt image at the centre of the artboard, its placement options set to `options`, /// relinked to a 300×100 px file → the image's id and session. fn relinked(name: &str, options: Value) -> (Session, NodeId, Folder) { diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 9fc790efa2..f2ab135817 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -424,6 +424,93 @@ fn blend_replace_spine_follows_path() { assert!(first.distance(Point::new(100.0, 300.0)) < 1.0, "{first:?}"); } +/// #6809: after Replace Spine, moving a key object moves the drawn key and its end of the spine, +/// not only the key's selection outline. +#[test] +fn moving_a_key_of_a_replaced_spine_blend_moves_what_is_drawn() { + let mut s = session(); + let (a, _, g) = blend(&mut s, json!({"steps": 5})); + let arc = id_of(&s.execute("path.create", &json!({"d": "M100 300 C100 245 145 200 200 200 C255 200 300 245 300 300"})).unwrap()); + sel(&mut s, &[g, arc]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let center = |n: &Node| n.geometric_bounds().unwrap().center(); + let before = steps_of(&s, g); + assert!(center(&before[0]).distance(Point::new(100.0, 300.0)) < 1e-6); + // Direct Selection picks the key inside the blend; the drag moves it. + sel(&mut s, &[a]); + s.execute("object.move", &json!({"dx": -50, "dy": 40})).unwrap(); + let key = center(&node(&s, a)); + assert!(key.distance(Point::new(50.0, 340.0)) < 1e-6, "{key:?}"); + let after = steps_of(&s, g); + assert_eq!(after.len(), before.len()); + let drawn = center(&after[0]); + assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}"); + assert!(center(&after[1]).distance(center(&before[1])) > 1.0, "the first step follows the moved key"); + let last = center(&after[after.len() - 1]); + assert!(last.distance(Point::new(300.0, 300.0)) < 1e-6, "the other key stays put: {last:?}"); + // Undo puts the key back on the spine as Replace Spine left it. + s.execute("edit.undo", &json!({})).unwrap(); + let back = steps_of(&s, g); + assert!(center(&back[0]).distance(Point::new(100.0, 300.0)) < 1e-6); + assert!(center(&back[1]).distance(center(&before[1])) < 1e-6); +} + +/// #6809 on a closed spine, where both end keys start on its first point: moving the first key +/// moves its end of the spine without dragging the last key's end along. +#[test] +fn moving_the_first_key_of_a_closed_replaced_spine_blend_moves_what_is_drawn() { + let mut s = session(); + let (a, _, g) = blend(&mut s, json!({"steps": 5})); + let square = id_of(&s.execute("path.create", &json!({"d": "M100 100 L300 100 L300 300 L100 300 Z"})).unwrap()); + sel(&mut s, &[g, square]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let center = |n: &Node| n.geometric_bounds().unwrap().center(); + let before = steps_of(&s, g); + assert!(center(&before[0]).distance(Point::new(100.0, 100.0)) < 1e-6); + sel(&mut s, &[a]); + s.execute("object.move", &json!({"dx": -50, "dy": -40})).unwrap(); + let key = center(&node(&s, a)); + assert!(key.distance(Point::new(50.0, 60.0)) < 1e-6, "{key:?}"); + let after = steps_of(&s, g); + assert_eq!(after.len(), before.len()); + let drawn = center(&after[0]); + assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}"); + assert!(center(&after[1]).distance(center(&before[1])) > 1.0, "the first step follows the moved key"); + let last = center(&after[after.len() - 1]); + assert!(last.distance(Point::new(100.0, 100.0)) < 1e-6, "the other key stays put: {last:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let back = steps_of(&s, g); + assert!(center(&back[0]).distance(Point::new(100.0, 100.0)) < 1e-6); + assert!(center(&back[1]).distance(center(&before[1])) < 1e-6); +} + +/// #6809 on a closed spine pinned by a spine edit: the end keys get points of their own, so +/// moving the first key afterwards still moves only its end. +#[test] +fn moving_the_first_key_of_a_pinned_closed_spine_blend_moves_what_is_drawn() { + let mut s = session(); + let (a, _, g) = blend(&mut s, json!({"steps": 5})); + let square = id_of(&s.execute("path.create", &json!({"d": "M100 100 L300 100 L300 300 L100 300 Z"})).unwrap()); + sel(&mut s, &[g, square]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + // Dragging a corner away from the keys pins the spine to them. + s.execute("object.blend.spine.moveAnchor", &json!({"id": g.0, "anchor": 2, "x": 320, "y": 320})).unwrap(); + let NodeKind::Blend { spec, .. } = node(&s, g).kind else { panic!() }; + assert_eq!(spec.key_anchors.len(), 2, "{:?}", spec.key_anchors); + let center = |n: &Node| n.geometric_bounds().unwrap().center(); + let before = steps_of(&s, g); + sel(&mut s, &[a]); + s.execute("object.move", &json!({"dx": -50, "dy": -40})).unwrap(); + let key = center(&node(&s, a)); + assert!(key.distance(Point::new(50.0, 60.0)) < 1e-6, "{key:?}"); + let after = steps_of(&s, g); + assert_eq!(after.len(), before.len()); + let drawn = center(&after[0]); + assert!(drawn.distance(key) < 1e-6, "the key is drawn where it was moved to: {drawn:?}, outline at {key:?}"); + let last = center(&after[after.len() - 1]); + assert!(last.distance(Point::new(100.0, 100.0)) < 1e-6, "the other key stays put: {last:?}"); +} + #[test] fn blend_align_to_path_rotates_steps() { let mut s = session(); @@ -483,8 +570,8 @@ fn envelope_warp_make_and_content_stays_inside_bounds() { let pts = all_anchors(&out); assert!(pts.len() > 4, "curves are subdivided"); assert!(pts.iter().all(|p| b.contains(*p)), "{b:?}"); - // It really is bent: the sides moved down. - assert!(pts.iter().any(|p| p.y > 201.0)); + // It really is bent: the top corners swung out past the sides. + assert!(pts.iter().any(|p| p.x < 99.0) && pts.iter().any(|p| p.x > 301.0)); } #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index e1def8a6fa..44a0ddde1b 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1855,6 +1855,38 @@ fn convert_to_artboards_names_by_the_artboards_the_document_has() { assert_eq!(name_after(&|s| _ = s.execute("edit.undo", &json!({})).unwrap()), "Artboard 3"); } +/// Convert to Artboards on several objects gives each new artboard an id above the ids given out +/// before and the deleted artboard's, and names it one past the highest id the artboards have, +/// counting the artboards it has just added. With an artboard whose id is `u32::MAX` (a damaged +/// file), each new artboard takes the smallest free id and the name stays at `u32::MAX`. +#[test] +fn convert_to_artboards_gives_each_object_the_next_id_and_name() { + let convert = |s: &mut Session| { + let ids: Vec = (0..3).map(|i| rect(s, 3000.0 + 300.0 * f64::from(i), 0.0, 200.0, 100.0)).collect(); + sel(s, &ids); + assert_eq!(s.execute("artboard.convertToArtboards", &json!({})).unwrap()["artboards"], 3); + let d = &s.doc().unwrap().doc; + d.artboards.iter().map(|a| (a.id, a.name.clone())).collect::>() + }; + let named = |pairs: &[(u32, &str)]| pairs.iter().map(|&(id, n)| (id, n.to_string())).collect::>(); + + // Artboards 1 and 2 are left after artboard 3 is deleted, so its id stays given out. + let mut s = session(); + s.execute("artboard.new", &json!({})).unwrap(); + s.execute("artboard.new", &json!({})).unwrap(); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect(); + assert_eq!(ids, [1, 2]); + let got = convert(&mut s); + assert_eq!(got, named(&[(1, "Artboard 1"), (2, "Artboard 2"), (4, "Artboard 3"), (5, "Artboard 5"), (6, "Artboard 6")])); + + let mut s = session(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[0].id = u32::MAX; + let got = convert(&mut s); + let top = format!("Artboard {}", u32::MAX); + assert_eq!(got, named(&[(u32::MAX, "Artboard 1"), (1, &top), (2, &top), (3, &top)])); +} + /// Rearrange All Artboards refuses `columns` that are not a whole number (a fraction, a negative number or a string), /// and the artboards stay where they were; 1.0, as the Rearrange All Artboards dialog sends a count, is one column. #[test] @@ -3686,7 +3718,7 @@ fn make_release_clear_guides() { s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); let n = undo_len(&s); assert_eq!(s.execute("view.guides.clear", &json!({})).unwrap()["count"], 2); - assert!(s.doc().unwrap().doc.guides.is_empty()); + assert!(s.doc().unwrap().doc.ruler_guides().is_empty()); assert!(s.doc().unwrap().doc.node(a).is_none()); assert_eq!(undo_len(&s), n + 1); } @@ -3751,13 +3783,13 @@ fn ruler_guides_and_lock() { let mut s = session(); assert_eq!(s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap()["index"], 0); s.execute("guide.move", &json!({"index": 0, "pos": 70})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 70.0); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 70.0); assert_eq!(s.execute("view.guides.lock", &json!({})).unwrap()["locked"], true); assert!(s.guides_locked()); assert!(matches!(s.execute("guide.remove", &json!({"index": 0})), Err(EngineError::Disabled(..)))); s.execute("view.guides.lock", &json!({})).unwrap(); s.execute("guide.remove", &json!({"index": 0})).unwrap(); - assert!(s.doc().unwrap().doc.guides.is_empty()); + assert!(s.doc().unwrap().doc.ruler_guides().is_empty()); assert!(s.execute("guide.remove", &json!({"index": 0})).is_err()); } @@ -3804,7 +3836,7 @@ fn invalid_guide_lock_parameters_keep_guides_selected() { 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!(selected_guides(&s), 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. @@ -3987,11 +4019,11 @@ fn a_failed_preview_leaves_locked_guides_deselected() { } fn guides(s: &Session) -> Vec<(bool, f64)> { - s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect() + s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect() } fn selected_guides(s: &Session) -> Vec { - s.doc().unwrap().selection.guides.clone() + super::selected_guides(s) } /// #414: ruler guides are selected, moved, copied, nudged and deleted like art, over commands. @@ -4107,6 +4139,60 @@ fn invalid_clear_guides_parameters_delete_nothing() { assert_eq!(guides(&s).len(), 1); } +/// Run `cmd` with `params`, expect an error naming `msg`, and check that the documents, the undo +/// history, the guides, the saved selections and the selection are as they were. +fn refuses_wrong_type(s: &mut Session, cmd: &str, params: Value, msg: &str) { + let state = |s: &Session| { + let st = s.doc().unwrap(); + (s.documents().len(), undo_len(s), guides(s), st.doc.saved_selections.clone(), st.selection.clone()) + }; + let before = state(s); + match s.execute(cmd, ¶ms) { + Ok(v) => panic!("{cmd} accepted {params}: {v}"), + Err(e) => assert!(e.to_string().contains(msg), "{cmd} {params}: {e}"), + } + assert!(state(s) == before, "{cmd} changed something for {params}"); +} + +#[test] +fn edit_guide_and_slice_commands_refuse_params_of_the_wrong_type() { + 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(); + let slice = s.execute("object.slice.fromSelection", &json!({"ids": [a.0]})).unwrap()["id"].as_u64().unwrap(); + sel(&mut s, &[a]); + s.execute("select.save", &json!({"name": "A"})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + for (cmd, params, msg) in [ + ("edit.duplicate", json!({"dx": "5"}), "`dx` must be a number, not \"5\""), + ("edit.duplicate", json!({"dy": true}), "`dy` must be a number, not true"), + ("edit.paste", json!({"dx": "5"}), "`dx` must be a number, not \"5\""), + ("edit.paste", json!({"dy": [1]}), "`dy` must be a number, not [1]"), + ("document.node", json!({"id": a.0, "summary": "yes"}), "`summary` must be true or false"), + ("file.close", json!({"index": "0"}), "`index` must be a non-negative integer"), + ("guide.add", json!({"pos": 50, "vertical": "true"}), "`vertical` must be true or false"), + ("guide.select", json!({"indexes": [0], "toggle": 1}), "`toggle` must be true or false"), + ("select.save", json!({"name": 5}), "`name` must be a string"), + ("select.editSaved", json!({"name": "A", "delete": "yes"}), "`delete` must be true or false"), + ("select.editSaved", json!({"name": "A", "newName": 5}), "`newName` must be a string"), + ] { + refuses_wrong_type(&mut s, cmd, params, msg); + } + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + refuses_wrong_type(&mut s, "guide.move", json!({"dx": "10"}), "`dx` must be a number, not \"10\""); + refuses_wrong_type(&mut s, "guide.move", json!({"dy": 5, "copy": "yes"}), "`copy` must be true or false"); + s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap(); + refuses_wrong_type(&mut s, "object.slice.duplicate", json!({"dx": "10"}), "`dx` must be a number, not \"10\""); + refuses_wrong_type(&mut s, "object.slice.select", json!({"slices": [slice], "toggle": "no"}), "`toggle` must be true or false"); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + refuses_wrong_type(&mut s, "edit.undoGroup.end", json!({"cancel": "yes"}), "`cancel` must be true or false"); + // Null is read as a key left out. + s.execute("edit.undoGroup.end", &json!({"cancel": null})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("guide.move", &json!({"dx": 10, "dy": null, "copy": null})).unwrap(); + assert_eq!(guides(&s), vec![(true, 210.0)]); +} + /// 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] @@ -4219,10 +4305,12 @@ fn guides_and_art_later_cases(s: &mut Session, a: NodeId) { assert_eq!(guides(s).len(), 4); assert_eq!(guides(s)[2], (true, 210.0)); assert_eq!(guides(s)[3], (false, 320.0)); - assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The layer's art (its ruler guides are listed after it). + let art = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().filter(|c| !c.is_ruler_guide()).count(); + assert_eq!(art(s), 2); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(guides(s).len(), 2); - assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); + assert_eq!(art(s), 1); } /// #451: an artboard guide (`guide.add {artboard}`) runs across its artboard only, and is moved, @@ -4244,7 +4332,7 @@ fn artboard_guides_go_with_their_artboard() { ); let spans = |s: &Session| { let d = &s.doc().unwrap().doc; - d.guides.iter().map(|g| d.guide_span(g)).collect::>() + d.ruler_guides().iter().map(|g| d.guide_span(g)).collect::>() }; assert_eq!(spans(&s), [Some((0.0, 300.0)), None]); for bad in [json!(5), json!("x"), json!(-1)] { @@ -4270,7 +4358,7 @@ fn artboard_guides_go_with_their_artboard() { // Rearranged, they follow their artboards. s.execute("artboard.rearrange", &json!({"columns": 4})).unwrap(); let d = &s.doc().unwrap().doc; - for (g, ab) in d.guides.iter().filter_map(|g| Some((g, d.artboards.iter().find(|a| Some(a.id) == g.artboard)?))) { + for (g, ab) in d.ruler_guides().iter().filter_map(|g| Some((g, d.artboards.iter().find(|a| Some(a.id) == g.artboard)?))) { assert_eq!(g.pos - ab.rect.x0, 160.5, "{g:?} on {ab:?}"); } // Deleted, the artboard takes its guides; the selected ones left stay selected. @@ -4401,17 +4489,55 @@ fn cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on( assert_eq!(owners(&mut s)[4..], [Value::Null, json!(1)]); } +/// The rulers' origin dragged out of their corner snaps as a drawn point does: onto a shape's +/// corner and edge, the artboard's centre, and with Snap to Point along a ruler guide; with +/// nothing on it stays at the pointer. The drag changes nothing, and its guides go when it ends. +#[test] +fn the_ruler_origin_dragged_from_the_corner_snaps_as_a_drawn_point() { + use vectorcraft_geom::Point; + let mut s = session(); + rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + let (n, doc) = (undo_len(&s), s.doc().unwrap().doc.clone()); + let v = ViewInfo::default(); + let at = |s: &mut Session, x, y| s.ruler_origin_drag(Some(Point::new(x, y)), v).unwrap(); + assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0), "the corner"); + assert!(!s.overlays(v).is_empty(), "the guide showing it"); + assert_eq!(at(&mut s, 130.0, 202.0), Point::new(130.0, 200.0), "the bottom edge"); + assert_eq!(at(&mut s, 398.0, 301.5), Point::new(400.0, 300.0), "the artboard's centre"); + assert_eq!(at(&mut s, 302.0, 50.0).x, 300.0, "along the ruler guide"); + assert_eq!(s.ruler_origin_drag(None, v), None, "off the canvas"); + assert!(s.overlays(v).is_empty()); + assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0)); + s.end_ruler_origin_drag(); + assert!(s.overlays(v).is_empty()); + assert_eq!((undo_len(&s), &*s.doc().unwrap().doc), (n, &*doc), "nothing changed"); + // Nothing on: it stays at the pointer. + let off = ViewInfo { smart_guides: false, snap_to_point: false, ..v }; + assert_eq!(s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), off), Some(Point::new(101.5, 98.5))); + s.end_ruler_origin_drag(); + // Snap to Grid: onto a gridline crossing. + let grid = ViewInfo { snap_to_grid: true, ..v }; + let p = s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), grid).unwrap(); + s.end_ruler_origin_drag(); + assert_eq!(p, Point::new(p.x.round(), p.y.round()), "{p:?}"); + assert_ne!(p, Point::new(101.5, 98.5)); +} + /// Guides saved before guides had layers are put on a layer when the document opens. #[test] fn guides_from_older_files_are_put_on_a_layer() { let mut s = Session::new(); - let mut d = vectorcraft_doc::Document::new(400.0, 300.0); - d.guides.push(vectorcraft_doc::Guide::new(true, 50.0)); - d.guides.push(vectorcraft_doc::Guide::new(false, 80.0)); + // A document read with its guides on no layer, as such a file holds them. + let mut v = serde_json::to_value(vectorcraft_doc::Document::new(400.0, 300.0)).unwrap(); + v["guides"] = json!([{"vertical": true, "pos": 50.0}, {"vertical": false, "pos": 80.0}]); + let d: vectorcraft_doc::Document = serde_json::from_value(v).unwrap(); s.add_document(d, None); let st = s.doc().unwrap(); let top = st.doc.default_layer(); - assert!(top.is_some() && st.doc.guides.iter().all(|g| g.layer == top), "{:?}", st.doc.guides); + let guides = st.doc.ruler_guides(); + assert_eq!(guides.len(), 2); + assert!(top.is_some() && guides.iter().all(|g| g.layer == top), "{guides:?}"); } /// Ruler guides are layer objects: made on the current layer, hidden, locked and deleted with it, @@ -4421,10 +4547,10 @@ fn ruler_guides_live_on_layers() { let mut s = session(); let first = s.doc().unwrap().current_layer().unwrap(); s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides[0].layer, Some(first), "on the current layer"); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].layer, Some(first), "on the current layer"); let second = id_of(&s.execute("layer.new", &json!({"name": "Guides"})).unwrap()); s.execute("guide.add", &json!({"vertical": false, "pos": 300})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides[1].layer, Some(second), "the new layer is current"); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[1].layer, Some(second), "the new layer is current"); assert!(s.execute("guide.add", &json!({"vertical": true, "pos": 1, "layer": 99999})).is_err()); // Hidden or locked with its layer. s.execute("layer.setProps", &json!({"ids": [second.0], "visible": false})).unwrap(); @@ -4435,12 +4561,12 @@ fn ruler_guides_live_on_layers() { s.execute("layer.setProps", &json!({"ids": [second.0], "locked": false})).unwrap(); // Moved to the first layer, then back. s.execute("guide.setLayer", &json!({"index": 1, "layer": first.0})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides[1].layer, Some(first)); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[1].layer, Some(first)); s.execute("guide.setLayer", &json!({"index": 1, "layer": second.0})).unwrap(); assert!(s.execute("guide.setLayer", &json!({"index": 1, "layer": 99999})).is_err()); // Several at once, as dragging their rows onto a layer's row does. s.execute("guide.setLayer", &json!({"indexes": [0, 1], "layer": first.0})).unwrap(); - assert!(s.doc().unwrap().doc.guides.iter().all(|g| g.layer == Some(first))); + assert!(s.doc().unwrap().doc.ruler_guides().iter().all(|g| g.layer == Some(first))); s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap(); assert!(s.execute("guide.setLayer", &json!({"indexes": [7], "layer": first.0})).is_err()); // Deleting a layer deletes its guides; undo brings them back. @@ -4476,7 +4602,7 @@ fn guides_on_hidden_or_locked_layers_are_left_alone() { s.execute("layer.setProps", &json!({"ids": [first.0], "locked": false})).unwrap(); // The current layer locked: the new guide goes on the top shown, unlocked layer. s.execute("guide.add", &json!({"vertical": true, "pos": 20})).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides[2].layer, Some(first)); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[2].layer, Some(first)); assert_eq!(guides(&s).len(), 3); } @@ -4489,7 +4615,7 @@ fn guides_go_with_their_layers_when_duplicated_merged_and_flattened() { s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); let second = id_of(&s.execute("layer.new", &json!({})).unwrap()); s.execute("guide.add", &json!({"vertical": false, "pos": 300})).unwrap(); - let on = |s: &Session, l: NodeId| s.doc().unwrap().doc.guides_on(l).map(|(_, g)| (g.vertical, g.pos)).collect::>(); + let on = |s: &Session, l: NodeId| s.doc().unwrap().doc.guides_on(l).iter().map(|g| (g.vertical, g.pos)).collect::>(); // Duplicate Layer copies its guides onto the copy. let copy = s.execute("layer.duplicate", &json!({"ids": [second.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); assert_eq!((on(&s, second), on(&s, copy)), (vec![(false, 300.0)], vec![(false, 300.0)])); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 067631eeca..4bc58e5f6b 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -292,6 +292,57 @@ fn a_saved_preset_with_the_resolution_out_of_range_reads_in_range() { assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 1.0); } +/// Advanced Options › Align New Objects to Pixel Grid starts on in the Mobile and Web presets and +/// off in the others and without a preset; a `file.new` param overrides the preset; the document +/// takes the value; saved presets and Recent keep it, and a saved preset from before it reads off. +#[test] +fn align_new_objects_to_pixel_grid_follows_the_preset() { + let align = |s: &Session| s.doc().unwrap().doc.setup.align_new_objects_to_pixel_grid; + let mut s = Session::new(); + for category in ["Mobile", "Web"] { + assert!(presets(&mut s, category).iter().all(|p| p["alignNewObjectsToPixelGrid"] == true), "{category}"); + } + for category in ["Print", "Film & Video", "Art & Illustration", "Branding", "Social"] { + assert!(presets(&mut s, category).iter().all(|p| p["alignNewObjectsToPixelGrid"] == false), "{category}"); + } + s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(align(&s)); + assert_eq!(presets(&mut s, "Recent")[0]["alignNewObjectsToPixelGrid"], true); + s.execute("file.new", &json!({"preset": "Phone 390×844"})).unwrap(); + assert!(align(&s)); + s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert!(!align(&s)); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + assert!(!align(&s)); + s.execute("file.new", &json!({"preset": "Web 1920×1080", "alignNewObjectsToPixelGrid": false})).unwrap(); + assert!(!align(&s)); + s.execute("file.new", &json!({"preset": "A4", "alignNewObjectsToPixelGrid": true})).unwrap(); + assert!(align(&s)); + assert!(Session::new().execute("file.new", &json!({"alignNewObjectsToPixelGrid": "on"})).is_err()); + // A Recent entry passed back makes the document it was made as. + let recent = presets(&mut s, "Recent")[0].clone(); + assert_eq!((recent["name"].as_str(), recent["alignNewObjectsToPixelGrid"].as_bool()), (Some("A4"), Some(true))); + s.execute("file.new", &recent).unwrap(); + assert!(align(&s)); + // Saved presets keep it. + s.execute("file.newPresets.save", &json!({"name": "Icons", "width": 64, "height": 64, "alignNewObjectsToPixelGrid": true})).unwrap(); + s.execute("file.newPresets.save", &json!({"name": "Banner", "preset": "Web 1920×1080", "alignNewObjectsToPixelGrid": false})).unwrap(); + let saved: Vec = presets(&mut s, "Saved").iter().map(|p| p["alignNewObjectsToPixelGrid"].clone()).collect(); + assert_eq!(saved, [json!(true), json!(false)]); + s.execute("file.new", &json!({"preset": "Icons"})).unwrap(); + assert!(align(&s)); + s.execute("file.new", &json!({"preset": "Banner"})).unwrap(); + assert!(!align(&s)); + let prefs: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(prefs.new_doc_presets, s.prefs.new_doc_presets); + // A saved preset from before the setting reads off, whatever its name. + let mut old = Session::new(); + old.apply_prefs(serde_json::from_value(json!({"newDocPresets": [{"name": "My Web", "width": 100, "height": 100}]})).unwrap()); + assert_eq!(presets(&mut old, "Saved")[0]["alignNewObjectsToPixelGrid"], false); + old.execute("file.new", &json!({"preset": "My Web"})).unwrap(); + assert!(!align(&old)); +} + #[test] fn rearrange_keeps_its_grid() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 2930bf1721..84e5559851 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -321,6 +321,149 @@ fn a_radial_gradient_becomes_concentric_ellipses() { assert!(f.opacity < 1.0 && f.opacity > 0.5, "the centre band is translucent: {}", f.opacity); } +/// Three opaque stops sweeping once around the center. +fn conic_stops() -> Value { + json!({"kind": "conic", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ff00ff"}, {"offset": 1, "color": "#004080"}]}) +} + +#[test] +fn a_conic_gradient_becomes_wedges_or_a_mesh_that_paint_it() { + // Objects: a wedge per step from the center, together painting what the canvas painted. + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), conic_stops(), false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 180})); + let g = selected(&s); + let (_, wedges) = clip_parts(&g); + assert_eq!(wedges.len(), 180); + let first = wedges[0].path_data().unwrap().subpaths[0].anchors[0].p; + assert!(first.distance(vectorcraft_geom::Point::new(100.0, 100.0)) < 1e-9, "wedges start at the center: {first:?}"); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.0, "{}", mean_diff(&before, &after)); + // Translucent stops: each wedge is just its share of the turn, ending where the next starts, + // so none doubles up (only the anti-aliased seams between them differ from the canvas). + let mut s = session(); + let gr = json!({"kind": "conic", "stops": [{"offset": 0, "color": "#ff0000", "opacity": 0.5}, {"offset": 1, "color": "#0000ff"}]}); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 36})); + let g = selected(&s); + let (_, wedges) = clip_parts(&g); + let outline = |n: &Node| n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::>(); + for pair in wedges.windows(2) { + let (a, b) = (outline(pair[0]), outline(pair[1])); + assert!(a.last().unwrap().distance(b[1]) < 1e-6, "{a:?} then {b:?}"); + } + assert!(mean_diff(&before, &render(&s)) < 4.0, "{}", mean_diff(&before, &render(&s))); + // Mesh: columns around the center. + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), conic_stops(), false); + let before = render(&s); + run(&mut s, "object.expand", json!({"gradient": "mesh"})); + let g = selected(&s); + let (_, content) = clip_parts(&g); + let NodeKind::Mesh(m) = &content[0].kind else { panic!("a mesh node: {:?}", content[0].kind) }; + assert!(m.is_valid()); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.5, "{}", mean_diff(&before, &after)); +} + +/// A mirrored conic, and one whose extent ellipse is flat (as a file can hold it), expand as the +/// canvas draws them. +#[test] +fn a_mirrored_or_flat_conic_expands_as_the_canvas_draws_it() { + for aspect in [-0.6, 0.0] { + for how in [json!({"steps": 180}), json!({"gradient": "mesh"})] { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), conic_stops(), false); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let n = d.node_mut(id).unwrap(); + let Paint::Gradient(mut g) = n.appearance.fill_paint().clone() else { panic!("a gradient fill") }; + let (start, end) = (vectorcraft_geom::Point::new(90.0, 110.0), vectorcraft_geom::Point::new(130.0, 80.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect, focal: None }); + n.appearance.set_fill(Paint::Gradient(g)); + let before = render(&s); + run(&mut s, "object.expand", how.clone()); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{aspect} {how}: {}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.5, "{aspect} {how}: {}", mean_diff(&before, &after)); + } + } +} + +/// Three opaque stops running from the center out to the square. +fn diamond_stops() -> Value { + json!({"kind": "diamond", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ff00ff"}, {"offset": 1, "color": "#004080"}]}) +} + +#[test] +fn a_diamond_gradient_becomes_nested_squares_or_a_mesh_that_paint_it() { + // Objects: nested squares about the center, largest first, together painting what the + // canvas painted. + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 120})); + let g = selected(&s); + let (_, squares) = clip_parts(&g); + assert_eq!(squares.len(), 120); + let corners = |n: &Node| n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::>(); + let (outer, inner) = (corners(squares[0]), corners(squares[119])); + assert_eq!((outer.len(), inner.len()), (4, 4)); + let reach = |pts: &[vectorcraft_geom::Point]| pts.iter().map(|p| p.distance(vectorcraft_geom::Point::new(100.0, 100.0))).fold(0.0, f64::max); + assert!(reach(&outer) > reach(&inner) * 100.0, "largest first: {outer:?} then {inner:?}"); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.0, "{}", mean_diff(&before, &after)); + // Translucent stops: each square is a ring with the next one cut out, so none doubles up. + let mut s = session(); + let gr = json!({"kind": "diamond", "stops": [{"offset": 0, "color": "#ff0000", "opacity": 0.5}, {"offset": 1, "color": "#0000ff"}]}); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false); + let before = render(&s); + run(&mut s, "object.expand", json!({"steps": 60})); + let g = selected(&s); + let (_, squares) = clip_parts(&g); + assert!(squares[..59].iter().all(|n| n.path_data().unwrap().subpaths.len() == 2), "rings"); + assert!(mean_diff(&before, &render(&s)) < 4.0, "{}", mean_diff(&before, &render(&s))); + // Mesh: rings of patches about the center. + let mut s = session(); + gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false); + let before = render(&s); + run(&mut s, "object.expand", json!({"gradient": "mesh"})); + let g = selected(&s); + let (_, content) = clip_parts(&g); + let NodeKind::Mesh(m) = &content[0].kind else { panic!("a mesh node: {:?}", content[0].kind) }; + assert!(m.is_valid()); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.5, "{}", mean_diff(&before, &after)); +} + +/// A turned, squashed diamond, and one whose square is flat (as a file can hold it), expand as +/// the canvas draws them. +#[test] +fn a_turned_or_flat_diamond_expands_as_the_canvas_draws_it() { + for aspect in [0.6, 0.0] { + for how in [json!({"steps": 120}), json!({"gradient": "mesh"})] { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), diamond_stops(), false); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let n = d.node_mut(id).unwrap(); + let Paint::Gradient(mut g) = n.appearance.fill_paint().clone() else { panic!("a gradient fill") }; + let (start, end) = (vectorcraft_geom::Point::new(90.0, 110.0), vectorcraft_geom::Point::new(130.0, 80.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect, focal: None }); + n.appearance.set_fill(Paint::Gradient(g)); + let before = render(&s); + run(&mut s, "object.expand", how.clone()); + let after = render(&s); + assert!(differing(&before, &after, 48) < 200, "{aspect} {how}: {}", differing(&before, &after, 48)); + assert!(mean_diff(&before, &after) < 2.5, "{aspect} {how}: {}", mean_diff(&before, &after)); + } + } +} + #[test] fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() { for gradient in [ diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index 166c88725e..d3394d1481 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -73,14 +73,13 @@ fn arrowheads_are_part_of_the_outline() { assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape"); } -/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle. +/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle. #[test] -fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() { +fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() { let mut s = session(); line(&mut s, json!({"weight": 10, "profile": "lens"})); let n = outline(&mut s); - // Each half of the lens swells on a cubic, flat at the middle (#5714). - assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); + assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); } #[test] diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index cade55db97..15fbb721e2 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -198,6 +198,30 @@ fn overprints(s: &Session, id: NodeId) -> (bool, bool) { (a.fill().unwrap().overprint, a.stroke().unwrap().overprint) } +/// Overprint Black refuses a switch or `percentage` of the wrong type, which it would otherwise +/// replace with the default: `{"fill": "false"}` marked the fills. +#[test] +fn overprint_black_refuses_a_param_of_the_wrong_type() { + let mut s = session(); + let k = rect(&mut s, [0.0, 0.0, 10.0, 10.0], black_ink(), Some(black_ink()), 1.0); + let before = undo_len(&s); + for (p, want) in [ + (json!({"ids": [k.0], "fill": "false"}), "`fill` must be true or false"), + (json!({"ids": [k.0], "stroke": 0}), "`stroke` must be true or false"), + (json!({"ids": [k.0], "remove": "true"}), "`remove` must be true or false"), + (json!({"ids": [k.0], "includeCmyBlacks": "yes"}), "`includeCmyBlacks` must be true or false"), + (json!({"ids": [k.0], "includeSpotBlacks": 1}), "`includeSpotBlacks` must be true or false"), + (json!({"ids": [k.0], "percentage": "75"}), "`percentage` must be a number"), + ] { + let e = s.execute("edit.colors.overprintBlack", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!((overprints(&s, k), undo_len(&s)), ((false, false), before), "nothing changed, no undo step"); + // A null is read as a key left out. + s.execute("edit.colors.overprintBlack", &json!({"ids": [k.0], "fill": null, "percentage": null})).unwrap(); + assert_eq!(overprints(&s, k), (true, true)); +} + #[test] fn overprint_black_options() { let mut s = session(); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index e15258bec6..c1da365740 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -98,6 +98,33 @@ fn an_unsaved_document_cant_be_packaged() { assert!(Session::new().execute("file.package", &json!({})).is_err(), "no document"); } +#[test] +fn a_param_of_the_wrong_type_is_refused_and_null_keeps_the_default() { + let dir = Folder::new("package-types"); + let mut s = poster(&dir); + let out = dir.file("out"); + for (p, msg) in [ + (json!({"folder": out, "copyLinks": "false"}), "`copyLinks` must be true or false"), + (json!({"folder": out, "linksFolder": 0}), "`linksFolder` must be true or false"), + (json!({"folder": out, "relink": "no"}), "`relink` must be true or false"), + (json!({"folder": out, "copyFonts": "false"}), "`copyFonts` must be true or false"), + (json!({"folder": out, "report": 1}), "`report` must be true or false"), + (json!({"folder": out, "name": 5}), "`name` must be a string"), + (json!({"folder": 5}), "`folder` must be a string"), + ] { + let e = match s.execute("file.package", &p) { + Ok(r) => panic!("{p} gave {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains(msg), "{p}: {e}"); + assert!(!std::path::Path::new(&out).exists(), "{p} wrote nothing"); + } + let r = run(&mut s, "file.package", json!({"folder": null, "name": null, "copyLinks": null, "copyFonts": null, "report": null})); + assert_eq!(r["name"], "poster Folder.zip"); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + assert_eq!(files, ["poster.vectorcraft", "Links/red.png", "Links/blue.png", "Fonts/SourceSans3-Regular.ttf", "poster Report.txt"]); +} + #[test] fn without_a_folder_the_zip_has_the_same_files() { let dir = Folder::new("package-zip"); @@ -253,6 +280,103 @@ fn a_missing_link_is_reported_not_copied() { assert!(report.contains("blue.png: not found"), "{report}"); } +/// Packaged for a client whose read root holds neither the document's file nor its links: the report, +/// its Document Info part included, names them by their file names, and `document.info` gives no +/// link. The person's report names them whole. +#[test] +fn a_confined_package_names_files_outside_the_read_root_by_name() { + let dir = Folder::new("package-roots"); + let mut s = poster(&dir); + std::fs::create_dir_all(dir.file("in")).unwrap(); + std::fs::remove_file(dir.file("art/blue.png")).unwrap(); + open(&mut s, &dir.file("poster.vectorcraft")); + let report = |r: &Value| { + let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap() + }; + let person = report(&run(&mut s, "file.package", json!({}))); + assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}"); + assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}"); + assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}"); + + let in_root = dir.0.join("in"); + let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap(); + let client = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({}))); + let text = report(&client); + assert!(text.contains("From: poster.vectorcraft\n"), "{text}"); + assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}"); + let base = dir.0.to_string_lossy().into_owned(); + assert!(!text.contains(&base), "{text}"); + for key in ["missingLinks", "warnings", "files"] { + assert!(!client[key].to_string().contains(&base), "{key}: {client}"); + } + // Document Info, whose report the package holds, gives no link either. + for p in [json!({}), json!({"format": "text"})] { + let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone())); + assert!(!info.to_string().contains(&base), "{p}: {info}"); + } + let info = run(&mut s, "document.info", json!({"format": "text"})); + assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}"); +} + +/// A missing link stored as a path relative to the document names a file inside a confined +/// request's read root: the package report and Document Info give its stored path. +#[test] +fn a_relative_link_inside_the_read_root_keeps_its_path() { + let dir = Folder::new("package-roots-relative"); + write(&dir.file("art/near.png"), &png(8, 8, RED)); + let mut s = session(); + let id = place(&mut s, &dir.file("art/near.png")); + let mut doc = (*s.doc().unwrap().doc).clone(); + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") }; + im.link = Some(vectorcraft_doc::LinkInfo::new("art/near.png")); + write(&dir.file("near.vectorcraft"), &vectorcraft_format::save(&doc, false)); + // Missing, the link keeps its stored path when the document opens (the package copies the + // image the document holds). + std::fs::remove_file(dir.file("art/near.png")).unwrap(); + open(&mut s, &dir.file("near.vectorcraft")); + let roots = crate::file_access::AutomationRoots::new(&[dir.0.as_path()], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({}))); + let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap(); + assert!(text.contains("\nart/near.png → Links/near.png\n"), "{text}"); + let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({}))); + let links: Vec<&Value> = info["images"].as_object().unwrap().values().map(|i| &i["link"]).collect(); + assert_eq!(links, [&json!("art/near.png")], "{info}"); + let text = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({"format": "text"}))); + assert!(text.to_string().contains("art/near.png"), "{text}"); +} + +/// A link whose stored path names a place outside a confined request's read root, with its file +/// found by name beside the document inside the root: the package report and reply give the file +/// name, not the stored path. +#[test] +fn a_stored_path_outside_the_read_root_is_left_out_when_its_file_is_found_inside() { + let dir = Folder::new("package-roots-stale"); + write(&dir.file("in/near.png"), &png(8, 8, RED)); + let mut s = session(); + let id = place(&mut s, &dir.file("in/near.png")); + let mut doc = (*s.doc().unwrap().doc).clone(); + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") }; + let stale = dir.file("out/near.png"); + im.link = Some(vectorcraft_doc::LinkInfo::new(&stale)); + write(&dir.file("in/near.vectorcraft"), &vectorcraft_format::save(&doc, false)); + // Missing when the document opens, the link keeps its stored path; the file then appears beside it. + std::fs::remove_file(dir.file("in/near.png")).unwrap(); + open(&mut s, &dir.file("in/near.vectorcraft")); + write(&dir.file("in/near.png"), &png(8, 8, RED)); + let in_root = dir.0.join("in"); + let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({}))); + let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap(); + assert!(text.contains("\nnear.png → Links/near.png\n"), "{text}"); + assert!(!text.contains(&stale), "{text}"); + for key in ["missingLinks", "warnings", "files"] { + assert!(!r[key].to_string().contains(&stale), "{key}: {r}"); + } +} + /// A file missing from a document that moved keeps the place its relative path names from the /// document's folder: the packaged document writes its relative path from there. #[test] @@ -393,7 +517,7 @@ fn the_document_info_report_has_every_category() { "BRUSHES", "SPOT COLORS", "PATTERN OBJECTS", - "GRADIENT SWATCHES", + "GRADIENT OBJECTS", "SYMBOLS", "FONTS", "FONT DETAILS", diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 4d549c31ef..28f81587ab 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -64,7 +64,7 @@ fn edit_gradient_angle_reverse_and_errors() { assert_eq!(g.gradient.stops[0].color.to_hex(), "#0000ff"); assert!((g.gradient.stops[0].midpoint - 0.8).abs() < 1e-6, "{:?}", g.gradient.stops); assert!(s.execute("paint.editGradient", &json!({"stops": [{"offset": 0, "color": "#fff"}]})).is_err()); - assert!(s.execute("paint.editGradient", &json!({"kind": "conic"})).is_err()); + assert!(s.execute("paint.editGradient", &json!({"kind": "spiral"})).is_err()); } #[test] @@ -798,7 +798,7 @@ fn copied_artboards_take_a_free_id_and_keep_their_own_guides() { let mut kept = vec![]; for i in [1, 0] { s.execute("artboard.delete", &json!({"index": i})).unwrap(); - kept.push(s.doc().unwrap().doc.guides.iter().map(|g| g.artboard).collect::>()); + kept.push(s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.artboard).collect::>()); s.execute("edit.undo", &json!({})).unwrap(); } got.push((cmd, s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect::>(), kept)); @@ -1675,12 +1675,12 @@ fn delete_empty_artboards_deletes_those_with_no_art_in_one_step() { assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [0, 2]})); let st = s.doc().unwrap(); assert_eq!(artboard_names(&s), ["Artboard 2"]); - assert_eq!(st.doc.guides.len(), 1, "the deleted artboards' guides go with them"); + assert_eq!(st.doc.ruler_guides().len(), 1, "the deleted artboards' guides go with them"); assert_eq!(st.doc.node(art).map(|n| n.geometric_bounds()), before.node(art).map(|n| n.geometric_bounds()), "the art stays"); assert_eq!(st.history.undo.len(), steps + 1); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(artboard_names(&s), ["Artboard 1", "Artboard 2", "Artboard 3"]); - assert_eq!(s.doc().unwrap().doc.guides.len(), 3); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 3); } /// What counts as art: hidden and locked objects, an object straddling two artboards and one diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index b0345db4ff..6850715b0e 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -400,6 +400,90 @@ fn stroke_set_refuses_an_unknown_key() { } } +/// An object id given as something other than a whole number (`"5"`, `-1`) is refused as such, +/// naming its key, not as a missing id; an id left out is still a missing one. +#[test] +fn a_malformed_object_id_is_not_reported_as_missing() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + let points = json!([[0, 0], [10, 10], [20, 0]]); + for bad in [json!("5"), json!(-1)] { + let id = || json!({ "id": bad }); + let with = |extra: serde_json::Value| { + let mut p = id(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + for (cmd, p, key) in [ + ("stroke.widthPoint.set", id(), "id"), + ("stroke.widthPoint.copy", id(), "id"), + ("stroke.widthPoint.remove", id(), "id"), + ("path.curvatureEdit", id(), "id"), + ("path.removeAnchor", id(), "id"), + ("path.convertAnchor", id(), "id"), + ("path.reshapeSegment", id(), "id"), + ("path.split", id(), "id"), + ("path.appendAnchor", id(), "id"), + ("path.close", id(), "id"), + ("path.setHandle", id(), "id"), + ("path.moveAnchor", id(), "id"), + ("path.setAnchors", id(), "id"), + ("path.reshape", id(), "id"), + ("path.insertAnchor", id(), "id"), + ("path.freehand", json!({"points": points, "extend": {"id": bad}}), "id"), + ("path.freehand", json!({"points": points, "redraw": {"id": bad}}), "id"), + ("document.node", id(), "id"), + ("layer.target", id(), "id"), + ("layer.setCurrent", id(), "id"), + ("layer.selectAll", id(), "id"), + ("layer.move", with(json!({"target": 1})), "id"), + ("layer.move", json!({"ids": [1], "target": bad}), "target"), + ("node.move", id(), "id"), + ("node.move", json!({"id": 1, "parent": bad}), "parent"), + ("text.reshapeArea", with(json!({"anchors": []})), "id"), + ("text.reshapeArea", json!({"items": [{"id": bad, "anchors": []}]}), "id"), + ("text.reshapePath", id(), "id"), + ("text.setPathHandle", id(), "id"), + ("text.editRange", id(), "id"), + ("text.startList", id(), "id"), + ("text.getRange", id(), "id"), + ("text.setGlyphAlternate", id(), "id"), + ("text.glyphAlternates", id(), "id"), + ("text.touchType", id(), "id"), + ("text.discardEmpty", id(), "id"), + ("text.createInPath", json!({"path": bad}), "path"), + ("object.envelope.setMeshPoint", id(), "id"), + ("object.mesh.setPointColor", with(json!({"index": 0})), "id"), + ("object.mesh.movePoint", with(json!({"index": 0, "x": 0, "y": 0})), "id"), + ("object.mesh.movePoints", json!({"items": [{"id": bad, "index": 0}]}), "id"), + ("object.mesh.addLine", with(json!({"x": 0, "y": 0})), "id"), + ("object.mesh.deletePoint", with(json!({"index": 0})), "id"), + ("object.slice.setRect", id(), "id"), + ("appearance.transfer", json!({"source": bad, "target": 1}), "source"), + ("appearance.transfer", json!({"source": 1, "target": bad}), "target"), + ("appearance.copyFrom", json!({"source": bad}), "source"), + ("livePaint.strokeEdge", json!({"point": [0, 0], "group": bad}), "group"), + ("livePaint.fill", json!({"point": [0, 0], "group": bad}), "group"), + ("livePaint.info", json!({"group": bad}), "group"), + ("livePaint.info", id(), "id"), + ("select.magicWand", id(), "id"), + ] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + // `layer.move` checks an `id` that stands in for `ids` before it runs. + let named = e.contains(&format!("`{key}` must be a whole number")) || (cmd == "layer.move" && e.contains("invalid object id")); + assert!(named, "{cmd} {p}: {e}"); + } + } + for cmd in ["path.close", "layer.target", "text.reshapePath", "object.mesh.movePoint", "select.magicWand"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains("missing"), "{cmd}: {e}"); + } + assert_eq!(undo(&s), before); +} + /// A command that takes the keys of one that isn't checked yet isn't checked either. #[test] fn a_reference_to_an_unchecked_command_is_unchecked() { diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 72aa559ae0..1397357061 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -656,13 +656,13 @@ fn simplify_refreshes_changed_path_selection_and_undo() { let kept = NodeId(s.execute("path.create", &json!({"anchors": [{"x": 350, "y": 180}]})).unwrap()["id"].as_u64().unwrap()); let unrelated = rect(&mut s, 400.0, 200.0, 40.0, 30.0); s.edit("selection fixture", |d, sel| { - d.guides.push(vectorcraft_doc::Guide::new(true, 30.0)); + let guide = d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 30.0)); sel.set([kept, id]); sel.anchors.insert(id, [(0, 19)].into_iter().collect()); sel.anchors.insert(kept, [(0, 0)].into_iter().collect()); sel.key = Some(kept); sel.target = Some(id); - sel.guides.push(0); + sel.guides.push(guide); Ok(()) }) .unwrap(); @@ -781,7 +781,7 @@ fn split_into_grid_options() { rect(&mut s, 10.0, 20.0, 110.0, 50.0); let r = s.execute("object.path.splitIntoGrid", &p).unwrap(); let cells: Vec = ids(&r).iter().map(|id| bounds(&s, *id)).collect(); - let guides: Vec<(bool, f64)> = s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect(); + let guides: Vec<(bool, f64)> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect(); assert_eq!(r["guides"], guides.len()); (cells, guides) }; @@ -812,13 +812,16 @@ fn split_into_grid_options() { assert!(close(bounds(&s, r[0]), Rect::new(0.0, 0.0, 40.0, 60.0), 1e-9) && close(bounds(&s, r[1]), Rect::new(60.0, 0.0, 100.0, 60.0), 1e-9)); let st = s.doc().unwrap(); assert!(r.iter().all(|id| node(&s, *id).appearance == node(&s, r[0]).appearance) && st.doc.node(back).is_none() && st.doc.node(front).is_none()); - assert_eq!(st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect::>(), [kept, r[0], r[1]], "above the path left alone"); + let art: Vec = st.doc.layers[0].children().unwrap().iter().filter(|n| !n.is_ruler_guide()).map(|n| n.id).collect(); + assert_eq!(art, [kept, r[0], r[1]], "above the path left alone"); + let children = st.doc.layers[0].children().unwrap(); + assert!(children.len() == 9 && children[3..].iter().all(|n| n.is_ruler_guide()), "the six guides are above the art"); assert_eq!(st.selection.objects, r); - assert!(st.doc.guides.iter().all(|g| g.layer == Some(st.doc.layers[0].id))); + assert!(st.doc.ruler_guides().iter().all(|g| g.layer == Some(st.doc.layers[0].id))); assert_eq!(st.history.undo.len(), undo + 1); s.execute("edit.undo", &json!({})).unwrap(); let st = s.doc().unwrap(); - assert!(st.doc.node(back).is_some() && st.doc.node(front).is_some() && st.doc.guides.is_empty()); + assert!(st.doc.node(back).is_some() && st.doc.node(front).is_some() && st.doc.ruler_guides().is_empty()); // A grid with no room for its gutters is refused and changes nothing. assert!(s.execute("object.path.splitIntoGrid", &json!({"columns": 4, "gutter": 50})).is_err()); assert!(s.execute("object.path.splitIntoGrid", &json!({"width": -5})).is_err()); diff --git a/crates/engine/src/tests/pathtype.rs b/crates/engine/src/tests/pathtype.rs index 5ead0cbd22..8aa8c05684 100644 --- a/crates/engine/src/tests/pathtype.rs +++ b/crates/engine/src/tests/pathtype.rs @@ -184,6 +184,184 @@ fn a_flip_round_a_closed_path_keeps_the_type_in_place() { assert!(origins(&s, id)[0].distance(first) < 8.0); } +/// A circle of radius 100 round (200, 200), starting at 9 o'clock and running clockwise, with +/// type on it from its start. +fn on_circle(s: &mut Session, text: &str) -> NodeId { + path_type(s, "M100 200 A100 100 0 1 1 300 200 A100 100 0 1 1 100 200 Z", [90.0, 200.0], text) +} + +#[test] +fn center_on_top_and_bottom_of_a_circle() { + let mut s = session(); + let id = on_circle(&mut s, "OOOO"); + assert!(near(brackets(&s, id).0, 0.0), "{:?}", brackets(&s, id)); + let steps = undo_len(&s); + let r = s.execute("type.pathCenter.top", &json!({})).unwrap(); + // Once round, its middle at 12 o'clock, a quarter of the way round: the type sits on the top, centered. + let (start, end) = brackets(&s, id); + assert!(near(start, 0.75) && end.is_none(), "{start} {end:?}"); + assert_eq!((r["ids"].clone(), r["end"].clone()), (json!([id.0]), Value::Null)); + assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center); + let top = ink(&s, id); + assert!((top.center().x - 200.0).abs() < 0.5 && top.y1 < 101.0, "{top:?}"); + assert_eq!((undo_len(&s), last_step(&s)), (steps + 1, "Center on Top".to_string())); + // Again: nothing moves, and no undo step is recorded. + s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert_eq!(undo_len(&s), steps + 1); + // The bottom: 6 o'clock, outside the circle (the type is not flipped). + s.execute("type.pathCenter.bottom", &json!({})).unwrap(); + let (start, end) = brackets(&s, id); + assert!(near(start, 0.25) && end.is_none(), "{start} {end:?}"); + let bottom = ink(&s, id); + assert!((bottom.center().x - 200.0).abs() < 0.5 && bottom.y0 > 299.0, "{bottom:?}"); + assert_eq!((undo_len(&s), last_step(&s)), (steps + 2, "Center on Bottom".to_string())); + // Justify Center stays as it is. + s.execute("text.setStyle", &json!({"justify": "justifyCenter"})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::JustifyCenter); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(brackets(&s, id).0, 0.25)); + // Brackets already in place with another alignment: only the alignment changes, in one step. + s.execute("text.setStyle", &json!({"justify": "left"})).unwrap(); + let (steps, before) = (undo_len(&s), brackets(&s, id)); + s.execute("type.pathCenter.bottom", &json!({})).unwrap(); + assert_eq!((undo_len(&s), brackets(&s, id)), (steps + 1, before)); + assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center); +} + +#[test] +fn center_on_top_twice_records_one_step_for_any_span() { + let mut s = session(); + let id = on_circle(&mut s, "OOOO"); + for (start, end) in [(0.0, 0.2), (0.13, 0.41), (0.37, 0.52), (0.61, 0.97), (0.89, 0.07), (0.3, 0.3001)] { + s.execute("type.pathOptions", &json!({"start": start, "end": end})).unwrap(); + for c in ["type.pathCenter.top", "type.pathCenter.bottom"] { + s.execute(c, &json!({})).unwrap(); + let (steps, placed) = (undo_len(&s), brackets(&s, id)); + // Again: the brackets stay exactly where they are, and no undo step is recorded. + s.execute(c, &json!({})).unwrap(); + assert_eq!((undo_len(&s), brackets(&s, id)), (steps, placed), "{c} {start} {end}"); + } + } +} + +#[test] +fn center_on_top_keeps_the_span_and_measures_the_path_as_drawn() { + let mut s = session(); + let id = on_circle(&mut s, "OOOO"); + // A span of a fifth of the path keeps its length. + s.execute("type.pathOptions", &json!({"end": 0.2})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + let (start, end) = brackets(&s, id); + assert!(near(start, 0.15) && end.is_some_and(|e| near(e, 0.35)), "{start} {end:?}"); + // Turned a quarter turn counter-clockwise, its 3 o'clock point, halfway round, is at the top. + s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap(); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + let (start, _) = brackets(&s, id); + assert!(near(start.rem_euclid(1.0), 0.0) || near(start, 1.0), "{start}"); + let bounds = text(&s, id).bounds().unwrap(); + let top = ink(&s, id); + assert!((top.center().x - bounds.center().x).abs() < 0.5 && top.y1 < bounds.y0 + 1.0, "{top:?} {bounds:?}"); + // A rectangle: the middle of its top edge. + let id = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO"); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + let (start, end) = brackets(&s, id); + assert!(near(start, 0.625) && end.is_none(), "{start} {end:?}"); + assert!((ink(&s, id).center().x - 200.0).abs() < 0.5); +} + +#[test] +fn center_on_top_moves_every_selected_type_on_a_path_in_one_step() { + let mut s = session(); + let a = on_circle(&mut s, "OOOO"); + let b = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO"); + let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0, p]})).unwrap(); + let steps = undo_len(&s); + let r = s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([a.0, b.0])); + assert!(near(brackets(&s, a).0, 0.75) && near(brackets(&s, b).0, 0.625)); + assert_eq!(undo_len(&s), steps + 1); + // Dynamic Text stays on, and the layout fits the text to the span where it now runs: a fifth of + // the circle, at its bottom. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("type.pathOptions", &json!({"start": 0, "end": 0.2})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("type.pathCenter.bottom", &json!({})).unwrap(); + assert!(text(&s, a).dynamic_text && near(brackets(&s, a).0, 0.65), "{:?}", brackets(&s, a)); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, a)); + assert!(lay.fit_scale > 1.5 && !lay.overflow, "{}", lay.fit_scale); + let bottom = ink(&s, a); + assert!((bottom.center().x - 200.0).abs() < 1.0 && bottom.y1 > 300.0, "{bottom:?}"); + // Vertical type on a path moves the same way. + s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap(); + s.execute("type.orientation.vertical", &json!({})).unwrap(); + s.execute("type.pathCenter.top", &json!({})).unwrap(); + assert!(near(brackets(&s, a).0, 0.75)); +} + +#[test] +fn center_on_top_refuses_open_compound_and_threaded_type() { + let mut s = session(); + let circle = on_circle(&mut s, "OOOO"); + let line = on_line(&mut s); + s.execute("select.set", &json!({"ids": [circle.0, line.0]})).unwrap(); + let steps = undo_len(&s); + let before = brackets(&s, circle); + let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string(); + assert!(e.contains("type on an open or compound path cannot be centered on its top or bottom") && e.ends_with(&line.0.to_string()), "{e}"); + // Nothing changes, the type on the circle included, and the same holds for an explicit list. + assert_eq!((undo_len(&s), brackets(&s, circle)), (steps, before)); + let e = s.execute("type.pathCenter.bottom", &json!({"ids": [circle.0, line.0]})).unwrap_err().to_string(); + assert!(e.contains("open or compound path") && e.ends_with(&line.0.to_string()), "{e}"); + s.execute("select.set", &json!({"ids": [circle.0]})).unwrap(); + for bad in [json!({"ids": "all"}), json!({"ids": [999_999]})] { + assert!(s.execute("type.pathCenter.top", &bad).is_err(), "{bad}"); + } + assert_eq!(undo_len(&s), steps); + // Two circles side by side in one path: a compound path. + let pair = path_type( + &mut s, + "M100 450 A40 40 0 1 1 180 450 A40 40 0 1 1 100 450 Z M300 450 A40 40 0 1 1 380 450 A40 40 0 1 1 300 450 Z", + [90.0, 450.0], + "OOOO", + ); + let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string(); + assert!(e.contains("open or compound path") && e.ends_with(&pair.0.to_string()), "{e}"); + // A closed path that is level all round has no height. + let flat = path_type(&mut s, "M100 400 L300 400 Z", [90.0, 400.0], "OOOO"); + let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string(); + assert!(e.contains("type on a path with no length or no height cannot be centered") && e.ends_with(&flat.0.to_string()), "{e}"); + // A frame of a thread is refused, alone or with other type on a closed path. + let threaded = on_circle(&mut s, "Threaded story"); + let frame = s.execute("shape.rectangle", &json!({"x": 400, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [threaded.0]})).unwrap(); + let before = brackets(&s, threaded); + for ids in [json!([threaded.0]), json!([circle.0, threaded.0])] { + let steps = undo_len(&s); + let e = s.execute("type.pathCenter.top", &json!({ "ids": ids })).unwrap_err().to_string(); + assert!(e.contains("type on a path in a thread cannot be centered on its top or bottom") && e.ends_with(&threaded.0.to_string()), "{e}"); + assert_eq!((undo_len(&s), brackets(&s, threaded)), (steps, before)); + } + // Without type on one closed path selected, the commands are not available. + let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + for (ids, why) in [ + (json!([p]), "select type on a closed path"), + (json!([line.0]), "open or compound path"), + (json!([circle.0, line.0]), "open or compound path"), + (json!([threaded.0]), "in a thread"), + ] { + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + for c in ["type.pathCenter.top", "type.pathCenter.bottom"] { + let e = s.execute(c, &json!({})).unwrap_err().to_string(); + assert!(e.contains(why), "{c} {ids}: {e}"); + } + } +} + #[test] fn align_to_path_and_spacing() { let mut s = session(); diff --git a/crates/engine/src/tests/pdfpresets.rs b/crates/engine/src/tests/pdfpresets.rs index eee88c5d17..7de08463f3 100644 --- a/crates/engine/src/tests/pdfpresets.rs +++ b/crates/engine/src/tests/pdfpresets.rs @@ -123,6 +123,46 @@ fn presets_export_and_import_round_trip() { assert!(is_bad_params(Session::new().execute("pdf.preset.export", &json!({}))), "nothing saved to export"); } +/// `longPagesInPoints` is saved with a preset, comes back through a presets file and the +/// preferences, shows in `document.pdfSettings`, and a 10 m page exported with it reopens at 10 m. +/// A value that isn't a boolean is refused. +#[test] +fn long_pages_in_points_round_trips_through_presets_and_reopens_at_full_size() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 28_346.456_692_913_386, "height": 2_834.645_669_291_338_5})).unwrap(); + s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": true, "preserveEditing": false})).unwrap(); + assert!(s.prefs.pdf_presets[0].settings.long_pages_in_points); + let back: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.pdf_presets, s.prefs.pdf_presets); + let text = s.execute("pdf.preset.export", &json!({"names": ["Banner"]})).unwrap()["data"].as_str().unwrap().to_string(); + let mut t = session(); + t.execute("pdf.preset.import", &json!({"data": text})).unwrap(); + assert_eq!(t.prefs.pdf_presets, s.prefs.pdf_presets); + let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": true})).unwrap(); + assert_eq!((&v["settings"]["longPagesInPoints"], &v["changed"]), (&json!(true), &json!([{"option": "longPagesInPoints", "value": true}])), "{v}"); + assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(false)); + // The preset writes the page in points; the file reopens at 10 m. + let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap(); + let bytes = pdf(&v); + assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); + assert!( + v["warnings"] + .as_array() + .unwrap() + .iter() + .any(|w| w.as_str().unwrap().ends_with("written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in")), + "{v}" + ); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + let rect = o.doc().unwrap().doc.artboards[0].rect; + assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}"); + for bad in [json!("yes"), json!(1)] { + assert!(is_bad_params(s.execute("document.exportPdf", &json!({"longPagesInPoints": bad}))), "{bad}"); + assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "Bad", "longPagesInPoints": bad}))), "{bad}"); + } +} + #[test] fn saved_presets_persist_with_the_preferences() { let mut s = session(); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index d348b13ae3..adb8bae15d 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -766,3 +766,196 @@ fn objects_on_path_members_stay_on_the_grid() { assert!(whole(&points(&s, a)), "path edited: {:?}", points(&s, a)); assert!(points(&s, a).iter().all(|(_, y)| *y > 105.0), "followed the path: {:?}", points(&s, a)); } + +fn align_new(s: &Session) -> bool { + s.doc().unwrap().doc.setup.align_new_objects_to_pixel_grid +} + +/// Align New Objects to Pixel Grid (`document.setup`): while it is on, a rectangle and an open path +/// drawn in the document are pixel-aligned and snapped in the step that makes them, and type is +/// not; art already in the document, duplicates and pastes keep their own setting; turning it off +/// leaves the next drawing as it is drawn, and the object's own setting can be turned off while +/// the document's stays on. +#[test] +fn align_new_objects_makes_new_paths_pixel_aligned() { + let mut s = new_doc(); + assert!(!align_new(&s)); + assert_eq!(s.execute("document.setup", &json!({})).unwrap()["alignNewObjectsToPixelGrid"], false); + let old = path(&mut s, "M10.3 120.6 L40.7 120.6 L40.7 130.3 L10.3 130.3 Z", 2.0); + let old_points = points(&s, old); + let steps = undo_len(&s); + let r = s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + assert_eq!(r["alignNewObjectsToPixelGrid"], true); + assert!(align_new(&s)); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + // Art already in the document stays as it was. + assert!(!aligned(&s, old)); + assert_eq!(points(&s, old), old_points); + // A rectangle is drawn pixel-aligned: with the 2 pt stroke `path` left as the current one, its + // edges go to whole points. + let steps = undo_len(&s); + let rect = s.execute("shape.rectangle", &json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap(); + assert!(aligned(&s, rect)); + assert_eq!(points(&s, rect), [(10.0, 21.0), (41.0, 21.0), (41.0, 30.0), (10.0, 30.0)]); + assert_eq!(undo_len(&s), steps + 1, "made and snapped in one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(aligned(&s, rect)); + // An open path from the Pen. + let line = s.execute("path.create", &json!({"anchors": [{"x": 50.3, "y": 60.2}, {"x": 90.6, "y": 60.2}]})).unwrap()["id"].as_u64().unwrap(); + assert!(aligned(&s, line)); + // Its horizontal segment goes to a whole point. + assert!(points(&s, line).iter().all(|(_, y)| *y == 60.0), "{:?}", points(&s, line)); + // Type cannot be pixel-aligned. + let text = s.execute("text.create", &json!({"x": 10.3, "y": 200.6, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, text)); + // A duplicate and a paste of art that is not pixel-aligned keep it so. + s.execute("select.set", &json!({"ids": [old]})).unwrap(); + s.execute("edit.duplicate", &json!({"dx": 100.3, "dy": 0.4})).unwrap(); + let copy = s.doc().unwrap().selection.objects[0].0; + assert!(copy != old && !aligned(&s, copy)); + s.execute("select.set", &json!({"ids": [old]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects[0].0; + assert!(pasted != old && pasted != copy && !aligned(&s, pasted)); + // The object's own setting turns off while the document's stays on. + s.execute("object.setPixelAligned", &json!({"ids": [rect], "on": false})).unwrap(); + assert!(!aligned(&s, rect) && align_new(&s)); + // Off: the next rectangle is drawn as it is given, and the first one stays pixel-aligned. + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap(); + let plain = s.execute("shape.rectangle", &json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, plain)); + let drawn = [(10.3, 20.6), (40.7, 20.6), (40.7, 30.3), (10.3, 30.3)]; + assert!(points(&s, plain).iter().zip(drawn).all(|(a, b)| close(*a, b)), "{:?}", points(&s, plain)); + assert!(aligned(&s, line)); + // A value that is not true or false changes nothing. + let steps = undo_len(&s); + assert!(s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": "yes"})).is_err()); + assert!(!align_new(&s)); + assert_eq!(undo_len(&s), steps); +} + +/// While Align New Objects to Pixel Grid is on, the paths of a new rectangular grid, polar grid +/// and flare are pixel-aligned (the group is not), and a new 3D Box add-on shape is snapped as +/// Align to Pixel Grid snaps the same box drawn without it. +#[test] +fn align_new_objects_reaches_grids_flares_and_add_on_shapes() { + let mut s = new_doc(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let doc = |s: &Session| s.doc().unwrap().doc.clone(); + let children = |s: &Session, id: u64| -> Vec { doc(s).node(NodeId(id)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect() }; + let grid = s.execute("shape.rectangularGrid", &json!({"x": 10.3, "y": 20.6, "width": 100.4, "height": 50.7})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, grid)); + let lines = children(&s, grid); + assert!(!lines.is_empty() && lines.iter().all(|id| aligned(&s, *id))); + // Under the 1 pt stroke, a divider sits on a half point across its length, and the frame + // has every corner on half points. + let half = |v: f64| ((v - 0.5) - (v - 0.5).round()).abs() < 1e-9; + let snapped = + |p: &[(f64, f64)]| halves(p) || (p.iter().all(|q| q.1 == p[0].1) && half(p[0].1)) || (p.iter().all(|q| q.0 == p[0].0) && half(p[0].0)); + assert!(lines.iter().all(|id| snapped(&points(&s, *id))), "{:?}", lines.iter().map(|id| points(&s, *id)).collect::>()); + let polar = s.execute("shape.polarGrid", &json!({"x": 200.3, "y": 20.6, "width": 80.4, "height": 80.7})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, polar) && children(&s, polar).iter().all(|id| aligned(&s, *id))); + let flare = s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6})).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, flare) && children(&s, flare).iter().all(|id| aligned(&s, *id))); + // Seen straight on, the box's front face has horizontal and vertical edges to snap. + let params = json!({"x": 20.3, "y": 300.6, "width": 60.4, "height": 40.7, "angleX": 0, "angleY": 0, "angleZ": 0}); + let drawn = s.execute("addon.shapes.box3d", ¶ms).unwrap()["id"].as_u64().unwrap(); + assert!(aligned(&s, drawn)); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap(); + let later = s.execute("addon.shapes.box3d", ¶ms).unwrap()["id"].as_u64().unwrap(); + assert!(!aligned(&s, later)); + let unaligned = points(&s, later); + s.execute("object.setPixelAligned", &json!({"ids": [later]})).unwrap(); + assert_eq!(points(&s, drawn), points(&s, later)); + assert_ne!(points(&s, drawn), unaligned, "the box has segments to snap"); +} + +/// The document's Align New Objects to Pixel Grid is saved in the native file only when on and +/// read back; a file from before it opens with it off. +#[test] +fn align_new_objects_is_saved_and_read_back() { + let mut s = new_doc(); + let off = serde_json::to_value(&s.doc().unwrap().doc.setup).unwrap(); + assert!(off.get("alignNewObjectsToPixelGrid").is_none(), "{off}"); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert!(!back.setup.align_new_objects_to_pixel_grid); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let on = serde_json::to_value(&s.doc().unwrap().doc.setup).unwrap(); + assert_eq!(on["alignNewObjectsToPixelGrid"], true); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert!(back.setup.align_new_objects_to_pixel_grid); + let mut older = on; + older.as_object_mut().unwrap().remove("alignNewObjectsToPixelGrid"); + assert!(!serde_json::from_value::(older).unwrap().align_new_objects_to_pixel_grid); +} + +fn selected_ids(s: &Session) -> Vec { + let mut ids: Vec = s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect(); + ids.sort_unstable(); + ids +} + +/// Select › Object › Not Aligned to Pixel Grid selects the paths and compound paths whose +/// property is off, whole coordinates or not, in groups too, and replaces the selection; a compound +/// path counts as one object; type, guides and aligned paths stay out; the art, its property and +/// the undo history stay as they are. +#[test] +fn not_aligned_to_pixel_grid_selects_paths_without_the_property() { + let mut s = new_doc(); + let fractional = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0); + let whole_but_off = path(&mut s, "M50 50 L60 50 L60 60 L50 60 Z", 1.0); + let on = path(&mut s, "M70.4 70 L80 70 L80 80 L70.4 80 Z", 1.0); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let guide = path(&mut s, "M0 200 L400 200", 1.0); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 100, "y": 100, "text": "type"})).unwrap(); + let m1 = path(&mut s, "M100 100 L120 100 L120 120 L100 120 Z", 1.0); + let m2 = path(&mut s, "M130 100 L150 100 L150 120 L130 120 Z", 1.0); + s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let grouped = path(&mut s, "M200 200 L210 200 L210 210 L200 210 Z", 1.0); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [on]})).unwrap(); + let before = points(&s, fractional); + let steps = undo_len(&s); + let r = s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap(); + let mut want = vec![fractional, whole_but_off, compound, grouped]; + want.sort_unstable(); + assert_eq!(r["count"], 4); + assert_eq!(selected_ids(&s), want); + assert!(!selected_ids(&s).contains(&guide)); + assert_eq!(points(&s, fractional), before); + assert!(!aligned(&s, fractional) && aligned(&s, on)); + assert_eq!(undo_len(&s), steps); + // With every such object aligned, nothing is selected. + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let r = s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap(); + assert_eq!(r["count"], 0); + assert!(selected_ids(&s).is_empty()); +} + +/// Not Aligned to Pixel Grid leaves out hidden and locked paths and, in isolation mode, the art +/// outside the isolated group. +#[test] +fn not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected() { + let mut s = new_doc(); + let hidden = path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0); + s.execute("object.setProps", &json!({"ids": [hidden], "visible": false})).unwrap(); + let locked = path(&mut s, "M30 10 L40 10 L40 20 L30 20 Z", 1.0); + s.execute("object.setProps", &json!({"ids": [locked], "locked": true})).unwrap(); + let outside = path(&mut s, "M50 10 L60 10 L60 20 L50 20 Z", 1.0); + let inside = path(&mut s, "M70 10 L80 10 L80 20 L70 20 Z", 1.0); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap()["count"], 2); + assert_eq!(selected_ids(&s), { + let mut v = vec![outside, inside]; + v.sort_unstable(); + v + }); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + assert_eq!(s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap()["count"], 1); + assert_eq!(selected_ids(&s), vec![inside]); +} diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 39e13ee40c..a0a8ededa0 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -954,6 +954,51 @@ fn bad_place_params_are_errors() { assert!(top_children(&s).is_empty()); } +#[test] +fn place_params_of_the_wrong_type_are_refused_and_null_keeps_the_default() { + let mut s = session(); + let ok = png(2, 2, [0; 4], None); + let with = |extra: Value| { + let mut p = file("x.png", &ok); + if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) { + o.extend(e); + } + p + }; + let queue = |extra: Value| { + let mut p = json!({ "files": [file("x.png", &ok)] }); + if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) { + o.extend(e); + } + p + }; + for (cmd, p, msg) in [ + ("file.place", with(json!({"link": "false"})), "`link` must be true or false"), + ("file.place", with(json!({"replace": 1})), "`replace` must be true or false"), + ("file.place", with(json!({"template": "true"})), "`template` must be true or false"), + ("file.place.queue", queue(json!({"link": "false"})), "`link` must be true or false"), + ("file.place.queue", queue(json!({"template": 1})), "`template` must be true or false"), + ("file.place.queue", queue(json!({"thumbnail": "8"})), "`thumbnail` must be a number"), + ("file.place.info", with(json!({"link": "no"})), "`link` must be true or false"), + ("file.place.info", with(json!({"thumbnail": "8"})), "`thumbnail` must be a number"), + ] { + let e = match s.execute(cmd, &p) { + Ok(r) => panic!("{cmd} gave {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains(msg), "{cmd}: {e}"); + assert_eq!(s.tool_id(), "selection", "{cmd}: the tool stays"); + assert!(top_children(&s).is_empty(), "{cmd}: nothing placed"); + } + let placed = s.execute("file.place", &with(json!({"link": null, "replace": null, "template": null}))).unwrap(); + assert_eq!(placed["ids"].as_array().unwrap().len(), 1); + assert_eq!(top_children(&s).len(), 1, "placed on the current layer, not a template layer"); + let info = s.execute("file.place.info", &with(json!({"link": null, "thumbnail": null}))).unwrap(); + assert!(info.get("thumbnailBase64").is_none(), "{info}"); + let r = s.execute("file.place.queue", &queue(json!({"link": null, "template": null, "thumbnail": null}))).unwrap(); + assert_eq!(r["count"], 1, "{r}"); +} + /// An SVG placed with `crop: "crop"` given is framed and clipped by its viewBox, as a PDF by its /// page, so art drawn on a shared canvas keeps its place and scale; by default (and with /// "bounding") it is fitted by its art's bounds (#788). diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 5871b85a31..e7d3c7cd7a 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -1060,6 +1060,30 @@ fn link_info_gives_the_artboards_size_not_pixels() { ); } +/// A confined caller's Link Info of a placed document whose file is outside its read roots has no +/// `link`, `path` or `location`, and keeps the file's name. +#[test] +fn link_info_leaves_out_a_placed_documents_path_outside_the_read_roots() { + let away = Folder::new("placed-lrr-away"); + let home = Folder::new("placed-lrr-home"); + let src = away.file("logo.vectorcraft"); + source(&src, 100.0, 50.0, RED, 0); + let mut s = session(); + let id = place(&mut s, &src); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[]).unwrap().unwrap(); + let i = crate::file_access::confine(Some(&roots), || s.execute("links.info", &json!({"id": id.0}))).unwrap(); + assert!(!i.to_string().contains("placed-lrr-away"), "{i}"); + assert_eq!( + (i["fileName"].as_str(), i["document"].as_bool(), i["status"].as_str()), + (Some("logo.vectorcraft"), Some(true), Some("missing")), + "{i}" + ); + let l = crate::file_access::confine(Some(&roots), || s.execute("links.list", &json!({}))).unwrap(); + assert!(!l.to_string().contains("placed-lrr-away") && l["links"][0]["name"] == "logo.vectorcraft", "{l}"); + let i = s.execute("links.info", &json!({"id": id.0})).unwrap(); + assert_eq!((&i["link"], &i["path"]), (&json!(src), &json!(src)), "unconfined: {i}"); +} + /// Save As reads its defaults from the catalog; using them must retain current editable links. #[test] fn native_save_catalog_defaults_keep_placed_documents_editable() { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 3c647deb01..a1e615a08d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -13,6 +13,11 @@ use crate::*; const DESATURATE: &[u8] = include_bytes!("../../../plugins/tests/fixtures/desaturate.wasm"); const DESATURATE_ID: &str = "org.vectorcraft.example.desaturate"; +/// Held by the tests that set the Additional Plug-ins Folder preference or run `plugin.reload`: +/// the folder last loaded and its report are kept for the whole process, so another test loading +/// its own folder between two steps would change what the next step loads or lists. +static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); + fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) } @@ -1148,6 +1153,98 @@ fn deferred_stages_in_symbol_art_are_listed_and_refreshed() { assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([])); } +/// `effect.refreshDeferred` takes the id of an object in the art of a symbol, pattern, brush or +/// opacity mask, as `effect.deferredStatus` lists it: one with a deferred stage is refreshed, and +/// one without (or whose stage is gone) adds nothing to the counts. The id of art that is no +/// longer in the document is an error. +#[test] +fn refresh_takes_objects_in_definition_art() { + let mut s = session(); + const FX: &str = "plugin.test.engine.deferred.nested"; + let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.nested", "effect", "{}"), &out)); + // A symbol whose art holds an object with the effect and one without. + let staged = rect(&mut s, 10.0, "#ff0000"); + let plain = rect(&mut s, 30.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"ids": [staged.0], "effect": FX})); + run(&mut s, "select.set", json!({"ids": [staged.0, plain.0]})); + run(&mut s, "symbol.new", json!({"name": "Nested"})); + // A pattern, an art brush (its source deleted) and an opacity mask, none with a stage. + let tile = rect(&mut s, 50.0, "#00ff00"); + run(&mut s, "select.set", json!({"ids": [tile.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Tile", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let bar = rect(&mut s, 70.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [bar.0]})); + run(&mut s, "brush.new", json!({"type": "art", "name": "Bar"})); + run(&mut s, "edit.clear", json!({"ids": [bar.0]})); + let masked = rect(&mut s, 90.0, "#ff0000"); + let mask = rect(&mut s, 90.0, "#ffffff"); + run(&mut s, "select.set", json!({"ids": [masked.0, mask.0]})); + run(&mut s, "transparency.makeOpacityMask", json!({})); + // A layer object with a stage that stays deferred, and one without. + let kept = rect(&mut s, 130.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"ids": [kept.0], "effect": FX})); + let bare = rect(&mut s, 150.0, "#ff0000"); + + // The ids of the objects of `art` that are not in the layers. + let nested = |s: &Session, art: &vectorcraft_doc::Node| { + let d = &s.doc().unwrap().doc; + let mut ids = Vec::new(); + vectorcraft_doc::swatches::walk_with_masks(art, &mut |n| { + if d.node(n.id).is_none() { + ids.push(n.id.0); + } + }); + ids + }; + let d = s.doc().unwrap().doc.clone(); + let in_symbol = nested(&s, &d.symbols[0].art); + let in_pattern = d.patterns.iter().flat_map(|p| p.art.iter().flat_map(|a| nested(&s, a))).collect::>(); + let brushes = vectorcraft_brush::library(&d); + let in_brush = brushes.iter().flat_map(|b| b.art().into_iter().flat_map(|a| nested(&s, a)).collect::>()).collect::>(); + let in_mask = d.node(masked).and_then(|n| n.extras().mask.as_ref()).map(|m| nested(&s, &m.art)).unwrap_or_default(); + for (what, ids) in [("symbol", &in_symbol), ("pattern", &in_pattern), ("brush", &in_brush), ("opacity mask", &in_mask)] { + assert!(!ids.is_empty(), "the {what} art has an object outside the layers"); + } + + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + fx.view(|| drawn(&s)); + fx.first_view_done(); + let listed = |s: &mut Session| { + run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::>() + }; + let deferred = listed(&mut s); + let [nested_staged, last] = deferred[..] else { panic!("two stages: {deferred:?}") }; + assert!(in_symbol.contains(&nested_staged) && last == kept.0, "{deferred:?} {in_symbol:?}"); + let Some(&nested_plain) = in_symbol.iter().find(|i| **i != nested_staged) else { panic!("{in_symbol:?}") }; + + // Objects without a stage, each on its own and together: nothing to refresh. + let none = json!({"refreshed": 0, "stillDeferred": 0, "failed": 0}); + let mut plain_ids = vec![nested_plain, in_pattern[0], in_brush[0], in_mask[0], bare.0]; + for id in &plain_ids { + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": id})), none, "object {id}"); + } + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), none); + assert_eq!(listed(&mut s), [nested_staged, kept.0]); + + // The staged object of the symbol's art, by its id, with the others. + step.store(0, std::sync::atomic::Ordering::Relaxed); + plain_ids.push(nested_staged); + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + assert_eq!(listed(&mut s), [kept.0]); + // Its stage is gone; the object is still there. + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": nested_staged})), none); + + // Art no longer in the document, and an id of no object. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).patterns.clear(); + assert!(s.execute("effect.refreshDeferred", &json!({"id": in_pattern[0]})).is_err(), "the pattern is gone"); + assert!(s.execute("effect.refreshDeferred", &json!({"ids": [nested_plain, 999_999]})).is_err(), "not an object of the document"); + assert_eq!(listed(&mut s), [kept.0]); +} + /// `CRAFT_PLUGIN_PAINTS_WASM=` saves a test live effect to try in the app /// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its /// object's stroke is 5 pt wide, and hands the geometry back otherwise. @@ -1278,6 +1375,7 @@ fn filters_keep_their_data_with_the_document() { #[test] fn plugin_management_commands() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let mut s = session(); install(&mut s, DESATURATE); let list = run(&mut s, "plugin.list", json!({})); @@ -1319,6 +1417,7 @@ fn plugin_management_commands() { /// installs what is in it, as setting any other folder does. #[test] fn plugins_folder_set_again_after_clearing_installs_its_plugins() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let dir = crate::tests_links::Folder::new("plugin-folder-cleared"); let id = "test.engine.foldercleared"; let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); @@ -1580,7 +1679,7 @@ fn a_module_without_permissions_ends_the_grant_of_its_id() { /// that holds such a module and a grant for its id has that grant forgotten when it is attached. #[test] fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { - use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex}; let folder = crate::tests_links::Folder::new("plugin-store-stale-grant"); let id = "test.engine.permissions.storedstale"; let other = "test.engine.permissions.storedother"; @@ -1627,7 +1726,11 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); vectorcraft_plugins::registry::remove(id); - vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&approved), permissions: vec![Permission::DocRead] }); + vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { + id: id.into(), + hash: sha256_hex(&approved), + permissions: vec![Permission::DocRead], + })); let mut fourth = session(); fourth.attach_plugin_store(folder.0.clone()); assert_eq!(ids(), vec![other.to_string()]); @@ -1809,11 +1912,11 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { run(&mut s, "plugin.remove", json!({"id": id})); } -/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for -/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load. -/// A grant recorded later counts again, and another store starts with nothing ignored. +/// A grant that a load of the plug-in store should forget and can't stays out of the approvals in +/// the process: both when `grants.json` can't be rewritten and when it can't be read at the load. +/// A grant recorded later counts again, and another store's grant for the id counts. #[test] -fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { +fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { use vectorcraft_plugins::permissions::sha256_hex; let folder = crate::tests_links::Folder::new("plugin-store-load-forget"); let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other"); @@ -1845,8 +1948,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { next.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); + // A load that can rewrite the file forgets the grant, and the store has nothing ignored again. + std::fs::write(&grants, &recorded).unwrap(); + next.attach_plugin_store(folder.0.clone()); + assert!(!grants.exists(), "the load removes the grant"); + // A directory at the file's path gives a read error on every platform. - std::fs::remove_file(&grants).unwrap(); std::fs::create_dir(&grants).unwrap(); vectorcraft_plugins::registry::remove(id); let mut third = session(); @@ -1872,6 +1979,180 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { run(&mut third, "plugin.remove", json!({"id": id})); } +/// A grant one session stops counting stops counting for every session in the process attached to +/// the same folder, by any path to it: one attached before, one attached after with no stored module +/// to try the removal for, and one that comes back from another folder. A successful write of the +/// grant in any of them makes it count in all of them again. +#[test] +fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-shared-ignore"); + let elsewhere = crate::tests_links::Folder::new("plugin-store-shared-ignore-other"); + let id = "test.engine.permissions.sharedignore"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let needs_approval = json!({"dataBase64": approved_data}); + let grants = folder.0.join("grants.json"); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + let mut first = session(); + first.attach_plugin_store(folder.0.clone()); + let inside = folder.0.join("inside"); + std::fs::create_dir(&inside).unwrap(); + let mut other = session(); + other.attach_plugin_store(inside.join("..")); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); + + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); + let file = first.stored_plugin_file(id).unwrap(); + assert!(!std::path::Path::new(&file).exists(), "the store keeps no module"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it"); + let refused = other.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); + assert!(refused.contains("doc.read"), "{refused}"); + std::fs::write(&file, &approved).unwrap(); + vectorcraft_plugins::registry::remove(id); + other.load_stored_plugins(); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded"); + std::fs::remove_file(&file).unwrap(); + + let mut later = session(); + later.attach_plugin_store(folder.0.clone()); + assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it"); + + std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + other.attach_plugin_store(elsewhere.0.clone()); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); + other.attach_plugin_store(folder.0.clone()); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't"); + + std::fs::write(&grants, &recorded).unwrap(); + assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); + for s in [&mut first, &mut other, &mut later] { + assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); + } + std::fs::remove_file(&grants).unwrap(); +} + +/// A plug-in folder that doesn't exist yet gets the key it gets once it is made, and every path to a +/// folder gets the same key. +#[test] +fn a_plugin_folder_has_one_key_for_every_path_to_it() { + use crate::store::plugin_store_key; + let folder = crate::tests_links::Folder::new("plugin-store-key"); + let dir = folder.0.join("Plug-ins"); + let before = plugin_store_key(&dir); + assert_eq!(plugin_store_key(&dir.join("sub").join("..")), before); + assert_eq!(plugin_store_key(&folder.0.join(".").join("Plug-ins")), before); + std::fs::create_dir(&dir).unwrap(); + assert_eq!(plugin_store_key(&dir), before, "the key stays when the folder is made"); + assert_eq!(plugin_store_key(&dir.join(".")), before); + #[cfg(windows)] + { + let plain = std::path::absolute(&dir).unwrap(); + let verbatim = std::path::PathBuf::from(format!(r"\\?\{}", plain.display())); + assert_eq!(plugin_store_key(&verbatim), before, "a verbatim path names the same folder"); + } +} + +/// Sessions attached to a plug-in folder before it exists, by paths that only name the same folder +/// once it is made, share the grants the process doesn't count for it. A grant that one session +/// writes while another fails to remove it keeps counting. +#[test] +fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-late-folder"); + let id = "test.engine.permissions.latefolder"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + std::fs::create_dir_all(folder.0.join("a").join("b")).unwrap(); + let dir = folder.0.join("a").join("Plug-ins"); + // On disk `link/..` is `a`, so `link/../Plug-ins` is the folder; by name it is a `Plug-ins` beside `a`. + // On Windows the folder is named in other letter case. + #[cfg(unix)] + let alias = { + std::os::unix::fs::symlink(folder.0.join("a").join("b"), folder.0.join("link")).unwrap(); + folder.0.join("link").join("..").join("Plug-ins") + }; + #[cfg(windows)] + let alias = folder.0.join("A").join("PLUG-INS"); + #[cfg(not(any(unix, windows)))] + let alias = dir.clone(); + let mut first = session(); + first.attach_plugin_store(dir.clone()); + let mut other = session(); + other.attach_plugin_store(alias); + std::fs::create_dir(&dir).unwrap(); + std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); + + first.ignore_stored_grant(id, first.grant_writes()); + assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it"); + assert!(other.store_grant(id, Some(serde_json::from_value(entry.clone()).unwrap())), "the file can be written"); + assert_eq!(run(&mut first, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); + + // A write that fails in one session while another writes the grant for the id leaves the grant + // counting. + let before = first.grant_writes(); + assert!(other.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the other session writes the grant"); + first.ignore_stored_grant(id, before); + assert_eq!(run(&mut first, "plugin.inspect", needs_approval)["needsApproval"], false, "the written grant counts"); + std::fs::remove_file(dir.join("grants.json")).unwrap(); +} + +/// Grant writes that change nothing, each for another id, don't grow what the process keeps past its +/// limit. +#[test] +fn the_process_keeps_a_bounded_number_of_grant_writes() { + let folder = crate::tests_links::Folder::new("plugin-store-writes-kept"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + for n in 0..300 { + assert!(s.store_grant(&format!("test.engine.permissions.unknown{n}"), None), "nothing to remove is a success"); + } + assert!(Session::grant_writes_kept() <= 256, "{}", Session::grant_writes_kept()); +} + +/// A session attached by a link to a plug-in folder matches the grants the process doesn't count +/// with the folder the link leads to now, not the one it led to when the session was attached. +#[cfg(unix)] +#[test] +fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-relinked"); + let id = "test.engine.permissions.relinked"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins")); + for dir in [&old, &new] { + std::fs::create_dir(dir).unwrap(); + std::fs::write(dir.join("grants.json"), &recorded).unwrap(); + } + std::os::unix::fs::symlink(&old, &link).unwrap(); + let mut linked = session(); + linked.attach_plugin_store(link.clone()); + assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); + + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&new, &link).unwrap(); + let mut direct = session(); + direct.attach_plugin_store(new.clone()); + direct.ignore_stored_grant(id, direct.grant_writes()); + assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the link leads to the ignored grant"); + assert!(linked.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); + assert_eq!(run(&mut direct, "plugin.inspect", needs_approval)["needsApproval"], false, "it counts again"); +} + /// A grants file that can't be opened or read may name the old module once it reads again, so /// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the /// file's path gives a read error on every platform. @@ -1966,6 +2247,125 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() { assert!(!std::path::Path::new(&file).exists()); } +/// When `plugin.remove` can't remove the grant and can't move the settings back either, its error +/// says where the settings are, and the plug-in gets no storage until they are back. A second +/// removal that can't remove the grant moves them back rather than deleting them, and so does the +/// next load of the plug-in. +#[test] +fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() { + let folder = crate::tests_links::Folder::new("plugin-store-failed-move-back"); + let id = "test.engine.permissions.movebackfail"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + let recorded = std::fs::read(&grants).unwrap(); + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + let data = crate::store::plugin_data_dir(&folder.0, id); + let settings = br#"{"zoom":"aGVsbG8="}"#; + std::fs::create_dir_all(&data).unwrap(); + std::fs::write(data.join("settings.json"), settings).unwrap(); + let mut aside = data.clone().into_os_string(); + aside.push(".removed"); + let aside = std::path::PathBuf::from(aside); + + crate::store::MOVE_BACK_FAILS.set(true); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + crate::store::MOVE_BACK_FAILS.set(false); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert!(refused.contains(&aside.display().to_string()) && refused.contains("the folder is in use"), "{refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert!(!data.exists()); + assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings); + assert!(vectorcraft_plugins::registry::storage(id).is_none(), "no empty settings take their place"); + + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert_eq!(refused, crate::store::GRANT_NOT_REMOVED); + assert_eq!(std::fs::read(data.join("settings.json")).unwrap(), settings, "the second removal moves the settings back"); + assert!(!aside.exists()); + + crate::store::MOVE_BACK_FAILS.set(true); + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err()); + crate::store::MOVE_BACK_FAILS.set(false); + assert!(!data.exists()); + + // A folder of the plug-in's own made meanwhile is used, and a removal that can't remove the + // grant leaves both. + let newer = br#"{"zoom":"bmV3"}"#; + std::fs::create_dir_all(&data).unwrap(); + std::fs::write(data.join("settings.json"), newer).unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert_eq!(refused, crate::store::GRANT_NOT_REMOVED); + assert_eq!(std::fs::read(data.join("settings.json")).unwrap(), newer); + assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings, "the kept settings stay"); + std::fs::remove_dir_all(&data).unwrap(); + + // A restart loads the plug-in again with its settings. + std::fs::write(&grants, &recorded).unwrap(); + vectorcraft_plugins::registry::remove(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in loads"); + assert_eq!(std::fs::read(data.join("settings.json")).unwrap(), settings, "the load moves the settings back"); + assert!(!aside.exists()); + + run(&mut next, "plugin.remove", json!({"id": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert!(!data.exists() && !aside.exists(), "the removal deletes the settings"); + assert_eq!(std::fs::read_dir(data.parent().unwrap()).unwrap().count(), 0, "nothing is left beside them"); +} + +/// What a deletion left in a plug-in's renamed settings folder, marked by the `.delete` file beside +/// it, isn't moved back. When that file can't be written, nothing is deleted, so the folder stays +/// whole and counts as kept settings. +#[test] +fn a_removal_deletes_only_folders_it_marked() { + let folder = crate::tests_links::Folder::new("plugin-store-delete-mark"); + let id = "test.engine.permissions.deletemark"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let install = json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + let data = crate::store::plugin_data_dir(&folder.0, id); + let settings = br#"{"zoom":"aGVsbG8="}"#; + let mut aside = data.clone().into_os_string(); + aside.push(".removed"); + let aside = std::path::PathBuf::from(aside); + let mut marker = aside.clone().into_os_string(); + marker.push(".delete"); + + // The next install starts with no settings, and its removal deletes the leftover and the mark. + std::fs::create_dir_all(&aside).unwrap(); + std::fs::write(aside.join("settings.json"), settings).unwrap(); + std::fs::write(&marker, b"").unwrap(); + run(&mut next, "plugin.install", install.clone()); + assert!(!data.exists(), "a leftover of a deletion isn't moved back"); + run(&mut next, "plugin.remove", json!({"id": id})); + assert_eq!(std::fs::read_dir(data.parent().unwrap()).unwrap().count(), 0, "the leftover and its mark are deleted"); + + // When the mark can't be written, the removal deletes nothing: installing the id again needs + // `replace`, and a removal of the id that isn't installed deletes the folder. + run(&mut next, "plugin.install", install.clone()); + std::fs::create_dir_all(&data).unwrap(); + std::fs::write(data.join("settings.json"), settings).unwrap(); + crate::store::MARKER_WRITE_FAILS.set(true); + let removed = next.execute("plugin.remove", &json!({"id": id})); + crate::store::MARKER_WRITE_FAILS.set(false); + assert_eq!(removed.unwrap(), json!({"removed": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings, "nothing is deleted without the mark"); + assert!(!std::path::Path::new(&marker).exists()); + assert!(next.execute("plugin.install", &install).is_err(), "the kept settings go to a new install only with `replace`"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings); + run(&mut next, "plugin.remove", json!({"id": id})); + assert_eq!(std::fs::read_dir(data.parent().unwrap()).unwrap().count(), 0, "the removal of the id deletes the kept folder"); +} + /// Windows keeps a file another program holds open without delete sharing, so the last grant can't /// be removed by deleting `grants.json`. #[cfg(windows)] @@ -1993,11 +2393,41 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module +/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant +/// still covers, and the grant is left as it was. +#[test] +fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { + let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants"); + let id = "test.engine.permissions.undeletablegrants"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + let recorded = std::fs::read(&grants).unwrap(); + + crate::store::GRANTS_DELETE_FAILS.set(true); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + crate::store::GRANTS_DELETE_FAILS.set(false); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was"); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module"); + + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists(), "a removal that can delete the file forgets the grant"); +} + /// A plug-in folder that leaves a module listing no permissions under an id forgets the process's /// grant for it, unless a later file in the folder leaves a granted module there. A grant kept in /// the plug-in store stays, with the stored module it covers. #[test] fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let mut s = session(); let id = "test.engine.permissions.folderstale"; let empty = json!({"objects": []}); @@ -2038,7 +2468,7 @@ fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() { /// With a store attached, a matching grant held only by the process doesn't count. #[test] fn a_stored_grant_covers_only_the_stored_module_it_recorded() { - use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex}; let folder = crate::tests_links::Folder::new("plugin-store-recorded-module"); let id = "test.engine.permissions.storedbytes"; let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); @@ -2083,7 +2513,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() { assert!(starts()); let mut attached = session(); attached.attach_plugin_store(folder.0.clone()); - vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&changed), permissions: vec![Permission::DocRead] }); + vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { + id: id.into(), + hash: sha256_hex(&changed), + permissions: vec![Permission::DocRead], + })); let inspected = run(&mut attached, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&changed)})); assert_eq!(inspected["needsApproval"], true, "a grant held only by the process doesn't count with a store attached"); run(&mut attached, "plugin.remove", json!({"id": id})); @@ -2170,11 +2604,200 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { vectorcraft_plugins::registry::revoke(id); } +/// Runs the test `name` of this module again in a process of its own → whether this is that +/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here +/// read it again each time they attach a plug-in store. +fn in_own_process(name: &str) -> bool { + const CHILD: &str = "VECTORCRAFT_TEST_PLUGIN_DISABLED_LIST"; + if std::env::var_os(CHILD).is_some() { + return true; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &format!("tests::plugins::{name}"), "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "{name} failed in its own process:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + false +} + +/// An update whose grant can't be written, and whose old module can't be put back either, stays in +/// the store: a disabled plug-in is turned on, as for any update the store holds. The old grant +/// doesn't cover the new module, so the next start skips it until it is approved. +#[test] +fn an_update_left_in_the_store_by_a_failed_put_back_turns_a_disabled_plugin_on() { + if !in_own_process("an_update_left_in_the_store_by_a_failed_put_back_turns_a_disabled_plugin_on") { + return; + } + use vectorcraft_plugins::{permissions::sha256_hex, registry, safe_mode}; + let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back-update"); + let id = "test.engine.permissions.putbackupdate"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false})); + let grants = folder.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir_all(grants.join("block")).unwrap(); + + crate::store::PUT_BACK_FAILS.set(true); + let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true}); + let installed = s.execute("plugin.install", &update); + crate::store::PUT_BACK_FAILS.set(false); + assert_eq!(installed.unwrap()["hash"], sha256_hex(&changed), "the new module runs in this session"); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&changed))); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), changed, "the store holds the new module"); + assert!(safe_mode::disabled().is_empty(), "the module the store holds is turned on"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved"); + + std::fs::remove_dir_all(&grants).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + registry::remove(id); + registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(registry::get(id).is_none(), "the old grant doesn't cover the new module"); + safe_mode::set_disabled(vec![]); +} + +/// An update whose grant can't be written, and whose put-back writes the old module and then +/// reports a failure, leaves the old module in the store: a disabled plug-in stays disabled, and the +/// next start doesn't load it. +#[test] +fn an_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off() { + if !in_own_process("an_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off") { + return; + } + use vectorcraft_plugins::{registry, safe_mode}; + let folder = crate::tests_links::Folder::new("plugin-store-put-back-fails-after-write"); + let id = "test.engine.permissions.putbacklate"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let changed = asking(id, r#"["doc.read","doc.write"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false})); + let disabled = safe_mode::disabled(); + assert!(!disabled.is_empty()); + let grants = folder.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir_all(grants.join("block")).unwrap(); + + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); + let update = json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read", "doc.write"], "replace": true}); + let installed = s.execute("plugin.install", &update); + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(false); + installed.unwrap(); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), first, "the store holds the old module"); + assert_eq!(safe_mode::disabled(), disabled, "the plug-in stays disabled"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(!safe_mode::parse_disabled_file(&saved).is_empty(), "the disabled list on disk is kept"); + + std::fs::remove_dir_all(&grants).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + registry::remove(id); + registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(registry::get(id).is_none(), "the disabled old module doesn't load"); + safe_mode::set_disabled(vec![]); +} + +/// A module without permissions whose install can't remove the old grant, and whose put-back writes +/// the old module and then reports a failure, leaves the old module in the store: a disabled plug-in +/// stays disabled. +#[test] +fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off() { + if !in_own_process("a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off") { + return; + } + use vectorcraft_plugins::safe_mode; + let folder = crate::tests_links::Folder::new("plugin-store-plain-put-back-fails-after-write"); + let id = "test.engine.permissions.plainputbacklate"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + run(&mut s, "plugin.setEnabled", json!({"id": id, "enabled": false})); + let disabled = safe_mode::disabled(); + assert!(!disabled.is_empty()); + let file = s.stored_plugin_file(id).unwrap(); + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); + let installed = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(false); + installed.unwrap(); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store holds the old module"); + assert_eq!(safe_mode::disabled(), disabled, "the plug-in stays disabled"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(!safe_mode::parse_disabled_file(&saved).is_empty(), "the disabled list on disk is kept"); + + std::fs::remove_file(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + safe_mode::set_disabled(vec![]); +} + +/// A first install whose grant can't be written, and whose module can't be taken out of the store +/// again, stays in the store: the plug-in's file is turned on. No grant covers the module, so the +/// next start skips it until it is approved. +#[test] +fn a_first_install_left_in_the_store_by_a_failed_put_back_turns_its_file_on() { + if !in_own_process("a_first_install_left_in_the_store_by_a_failed_put_back_turns_its_file_on") { + return; + } + use vectorcraft_plugins::{registry, safe_mode}; + let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back-first"); + let id = "test.engine.permissions.putbackfirst"; + let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let module = s.stored_plugin_file(id).unwrap(); + run(&mut s, "plugin.setEnabled", json!({"file": module, "enabled": false})); + let grants = folder.0.join("grants.json"); + std::fs::create_dir_all(grants.join("block")).unwrap(); + + crate::store::PUT_BACK_FAILS.set(true); + let installed = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]})); + crate::store::PUT_BACK_FAILS.set(false); + installed.unwrap(); + assert!(registry::get(id).is_some(), "the module runs in this session"); + assert_eq!(std::fs::read(&module).unwrap(), first, "the store holds the module"); + assert!(safe_mode::disabled().is_empty(), "the file the store holds is turned on"); + let saved = std::fs::read(folder.0.join(crate::store::DISABLED_FILE)).unwrap(); + assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved"); + + std::fs::remove_dir_all(&grants).unwrap(); + registry::remove(id); + registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert!(registry::get(id).is_none(), "no grant covers the module"); + safe_mode::set_disabled(vec![]); +} + /// A plug-in folder reports a changed module as needing approval and still loads the other files; /// granted on its own, the changed module loads from the folder. A session without a store uses the /// grants held by the process. #[test] fn a_plugin_folder_skips_a_changed_module_until_it_is_approved() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let mut s = session(); let id = "test.engine.permissions.folderbytes"; let plain = "test.engine.permissions.folderplain"; @@ -2352,8 +2975,15 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() { params.join(",") ); let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap(); - // One page of memory: the input and the parameters share 32 KiB. - registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap()); + // One page of memory: the input and the parameters share 32 KiB. The module lists permissions, + // so its grant is recorded first. + let plugin = Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap(); + registry::grant(vectorcraft_plugins::permissions::GrantToken::after_engine_approval(vectorcraft_plugins::permissions::Grant { + id: id.into(), + hash: plugin.hash().to_string(), + permissions: plugin.manifest().permissions(), + })); + registry::install(plugin).unwrap(); let mut s = session(); let small = rect(&mut s, 10.0, "#ff0000"); let long = rect(&mut s, 30.0, "#00ff00"); @@ -2394,7 +3024,7 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() { assert!(e.contains(says), "{says}: {e}"); assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}"); } - assert!(registry::remove(id)); + assert!(registry::remove(id) && registry::revoke(id)); } /// What the user granted is kept in the plug-in store with the module: the next session installs @@ -2403,6 +3033,7 @@ fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() { /// until it is granted on its own. #[test] fn granted_permissions_are_kept_and_folders_skip_the_rest() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let folder = crate::tests_links::Folder::new("plugin-store-grants"); let id = "test.engine.permissions.stored"; let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); @@ -2484,6 +3115,41 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() { run(&mut granted, "plugin.remove", json!({"id": id})); } +/// The registry installs a module that lists permissions only under a grant the process holds, so +/// a start and a `plugin.reload` record the store's grant for the module they load. A module in the +/// folder that nobody granted is reported and skipped, and records nothing. +#[test] +fn stored_and_reload_grants_still_install() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let store = crate::tests_links::Folder::new("plugin-store-grants-reload"); + let id = "test.engine.permissions.reload"; + let lone = "test.engine.permissions.reload.lone"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]})); + let forget = || { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + }; + forget(); + let mut next = session(); + next.attach_plugin_store(store.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again from the store"); + assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm))); + forget(); + let dir = crate::tests_links::Folder::new("plugin-folder-grants-reload"); + std::fs::write(dir.0.join("granted.wasm"), &wasm).unwrap(); + std::fs::write(dir.0.join("lone.wasm"), asking(lone, r#"["doc.read"]"#, &json!({"objects": []}))).unwrap(); + let r = run(&mut next, "plugin.reload", json!({"path": dir.0.display().to_string()})); + assert_eq!(r["loaded"], json!([id]), "{r}"); + assert!(vectorcraft_plugins::registry::granted(id).is_some(), "the store's grant is the process's too"); + let why = r["failed"][0]["error"].as_str().unwrap(); + assert!(why.contains("needs approval") && r["failed"][0]["file"].as_str().unwrap().ends_with("lone.wasm"), "{r}"); + assert!(vectorcraft_plugins::registry::get(lone).is_none() && vectorcraft_plugins::registry::granted(lone).is_none()); + run(&mut next, "plugin.remove", json!({"id": id})); +} + /// A grant covers the module it was given to: another module under the id, listing the same /// permissions, isn't installed from the store at the next start, a folder load reports it as /// needing approval, and `plugin.install` asks for `grant` again, even with `replace: true`. It @@ -2491,6 +3157,7 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() { /// covers no module. #[test] fn a_grant_covers_only_the_module_it_was_given_to() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let folder = crate::tests_links::Folder::new("plugin-store-grant-hash"); let id = "test.engine.granthash"; let mut s = session(); @@ -3231,6 +3898,40 @@ fn removing_an_id_that_is_not_installed_deletes_its_storage() { assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "nothing left to remove"); } +/// The `plugin.*` commands that the tests running every command with `{}` run +/// ([`crate::runs_with_empty_params`]) leave the cache of an installed plug-in as it is, so +/// those tests can run beside the ones here that check a cache. Each command runs with `{}` in a +/// document with two rectangles, one or both selected, as `every_command_survives_empty_params` +/// runs it. +#[test] +fn plugin_commands_run_with_empty_params_keep_other_plugins_caches() { + let folder = crate::tests_links::Folder::new("plugin-storage-empty-params"); + let id = "test.engine.storageemptyparams"; + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + install_storing(&mut s, id, WRITES); + run(&mut s, "plugin.run", json!({"id": id, "ids": []})); + assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3)); + let mut ran = vec![]; + for all in [false, true] { + for c in crate::cmd::command_specs().iter().filter(|c| c.id.starts_with("plugin.") && crate::runs_with_empty_params(c.id)) { + let mut other = session(); + let a = rect(&mut other, 10.0, "#ff0000"); + rect(&mut other, 40.0, "#0000ff"); + if all { + run(&mut other, "select.all", json!({})); + } else { + run(&mut other, "select.set", json!({"ids": [a.0]})); + } + let _ = other.execute(c.id, &json!({})); + ran.push(c.id); + assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3), "after {}", c.id); + } + } + assert!(ran.contains(&"plugin.list"), "{ran:?}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// The settings file and the cache are checked: a file that doesn't read is moved aside and the /// settings start empty; a write past a cap fails and changes nothing; cache entries whose names /// differ only in case are two files; a removed plug-in's storage takes no more writes. @@ -3620,3 +4321,60 @@ fn a_filter_that_calls_commands_is_given_the_edit_in_progress() { assert_eq!(x, json!(17.0), "undoing the filter brings back the moved rectangle"); run(&mut s, "plugin.remove", json!({"id": id})); } + +/// Installs a filter `id` that calls commands and hands back what it is given, with `commands` (a +/// JSON list of command specs) in its manifest. +fn install_echo_calling(s: &mut Session, id: &str, commands: &str) { + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"],"commands":{commands}}}"# + ); + let wasm = wat::parse_str(tpl::module(&manifest, tpl::ECHO, "", 1)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + +/// With Real-time Drawing off, a 50 × 50 rectangle at (10, 10) whose move by 7 pt is still being +/// dragged: the tool has stored the move, which the document does not hold yet. +fn deferred_move(s: &mut Session) -> NodeId { + let r = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + run(s, "prefs.set", json!({"key": "realTimeDrawing", "value": false})); + let move_by = vectorcraft_tools::Action::Preview("object.move".into(), json!({"dx": 7, "dy": 0})); + s.apply_actions(vec![vectorcraft_tools::Action::Begin("Move".into()), move_by]).unwrap(); + assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 10.0, "the move is not applied while it is dragged"); + r +} + +/// The rectangle a run named `label` during [`deferred_move`] left: moved, with the interaction +/// ended and the move an undo step of its own before the run's. +fn assert_moved_once(s: &Session, r: NodeId, label: &str) { + assert!(!s.in_interaction()); + assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, [label, "Move"]); +} + +/// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies +/// the dragged move first and gives the filter the moved rectangle, which it hands back as it was. +#[test] +fn a_filter_that_calls_commands_is_given_a_deferred_move() { + let id = "test.engine.callsdeferred"; + let mut s = session(); + install_echo_calling(&mut s, id, "[]"); + let r = deferred_move(&mut s); + run(&mut s, "plugin.run", json!({"id": id})); + assert_moved_once(&s, r, &format!("Test {id}")); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in command that calls commands, run with Real-time Drawing off during a drag, is given +/// the moved rectangle as `plugin.run` is. +#[test] +fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() { + let id = "test.engine.callsdeferredcmd"; + let mut s = session(); + install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#); + let r = deferred_move(&mut s); + run(&mut s, &format!("plugin.{id}.same"), json!({})); + assert_moved_once(&s, r, "Same"); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 8e3c043e4e..14669fd357 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1990,9 +1990,12 @@ fn real_time_drawing_off_still_shows_a_dragged_guide() { set_pref(&mut s, "realTimeDrawing", json!(false)); s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 200.0), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 200.0), v).unwrap(); - assert_eq!(s.doc().unwrap().doc.guides[0].pos, 150.0, "the guide moves while dragged"); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 150.0, "the guide moves while dragged"); s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 200.0), v).unwrap(); - assert_eq!((s.doc().unwrap().doc.guides[0].pos, s.doc().unwrap().history.undo.last().map(|e| e.label.as_str())), (150.0, Some("Move Guide"))); + assert_eq!( + (s.doc().unwrap().doc.ruler_guides()[0].pos, s.doc().unwrap().history.undo.last().map(|e| e.label.as_str())), + (150.0, Some("Move Guide")) + ); } /// With Real-time Drawing off, a 9-slice guide of the edited symbol moved with the Selection tool @@ -2044,6 +2047,42 @@ fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() { assert_eq!(paths(&s), 1, "the deferred rectangle is committed"); } +/// With Real-time Drawing off, Undo during a drag keeps the dragged move as its own step and takes +/// back only that: the rectangle drawn before stays, and Redo brings the move back. +#[test] +fn undo_during_a_deferred_drag_takes_back_only_the_drag() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + set_pref(&mut s, "realTimeDrawing", json!(false)); + let x = |s: &Session| s.doc().unwrap().doc.node(r).and_then(vectorcraft_doc::Node::geometric_bounds).map(|b| b.x0); + let move_by = vectorcraft_tools::Action::Preview("object.move".into(), json!({"dx": 7, "dy": 0})); + s.apply_actions(vec![vectorcraft_tools::Action::Begin("Move".into()), move_by]).unwrap(); + assert_eq!(x(&s), Some(10.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.in_interaction()); + assert_eq!(x(&s), Some(10.0), "the rectangle stays"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(x(&s), Some(17.0), "Redo brings the move back"); +} + +/// Undo during a drag whose stored preview fails cancels the drag, as its release would, and then +/// takes back the step before it. +#[test] +fn undo_during_a_deferred_drag_that_fails_cancels_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + set_pref(&mut s, "realTimeDrawing", json!(false)); + let bad = vectorcraft_tools::Action::Preview("no.such.command".into(), json!({})); + s.apply_actions(vec![vectorcraft_tools::Action::Begin("Bad".into()), bad]).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.in_interaction()); + let d = s.doc().unwrap(); + assert_eq!(d.doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum::(), 0, "the rectangle is undone"); + assert!(d.history.undo.iter().all(|e| e.label != "Bad")); +} + /// Repeated overlay redraws with Real-time Drawing off reuse the cached deferred feedback. #[test] fn deferred_preview_overlays_are_cached_across_redraws() { diff --git a/crates/engine/src/tests/prefs_roots.rs b/crates/engine/src/tests/prefs_roots.rs new file mode 100644 index 0000000000..b9818949f1 --- /dev/null +++ b/crates/engine/src/tests/prefs_roots.rs @@ -0,0 +1,107 @@ +//! The preferences commands under automation roots: a confined request sees a folder preference and +//! an export preset's folder only inside its read roots. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::cmd::fileio::ScreenExportPreset; +use crate::file_access::{AutomationRoots, confine}; +use crate::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn text(p: &Path) -> String { + p.to_string_lossy().to_string() +} + +/// A fresh scratch folder for one test, with the folders `in` and `out`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-prefs-roots-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for sub in ["in", "out"] { + std::fs::create_dir_all(dir.join(sub)).unwrap(); + } + dir +} + +/// The folder preferences that name the folder outside the read root. +const OUTSIDE: [&str; 3] = ["pluginsFolder", "scratchPrimary", "templatesFolder"]; + +/// A session whose folder preferences name `inside` (fonts, and the Data Recovery folder with +/// spaces around it) and `outside` (the [`OUTSIDE`] ones, the Templates folder with spaces around +/// it), with a scratch disk choice and an export preset kept with each folder. +fn session(inside: &str, outside: &str) -> Session { + let mut s = Session::new(); + s.prefs.fonts_folder = inside.to_string(); + s.prefs.recovery_folder = format!(" {inside} "); + s.prefs.plugins_folder = outside.to_string(); + s.prefs.scratch_primary = outside.to_string(); + s.prefs.scratch_secondary = "None".to_string(); + s.prefs.templates_folder = format!(" {outside} "); + for (name, folder) in [("Inside", inside), ("Outside", outside)] { + let settings = json!({"formats": [{"format": "svg"}], "folder": folder}); + s.prefs.screen_export_presets.push(ScreenExportPreset { name: name.into(), settings: settings.as_object().cloned().unwrap_or_default() }); + } + s +} + +/// Does a string anywhere in `v` hold `path`? +fn holds(v: &Value, path: &str) -> bool { + v.to_string().contains(&path.replace('\\', "\\\\")) +} + +#[test] +fn prefs_commands_leave_out_folders_outside_the_read_root() { + let base = folder("get"); + let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out"))); + let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap(); + let mut s = session(&inside, &outside); + + let all = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({}))); + let prefs = &all["prefs"]; + assert_eq!(prefs["fontsFolder"], json!(inside), "a folder inside the root is shown"); + assert_eq!(prefs["recoveryFolder"], json!(format!(" {inside} ")), "checked without the spaces, shown as kept"); + assert_eq!(prefs["scratchSecondary"], json!("None"), "a scratch disk choice is shown"); + for key in OUTSIDE { + assert_eq!(prefs[key], Value::Null, "{key}: {all}"); + } + let presets = prefs["screenExportPresets"].as_array().unwrap(); + assert_eq!(presets[0]["settings"]["folder"], json!(inside)); + assert_eq!(presets[1]["name"], json!("Outside"), "the preset stays"); + assert!(presets[1]["settings"].get("folder").is_none(), "{all}"); + assert!(!holds(&all, &outside), "{all}"); + + for key in OUTSIDE { + let one = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": key}))); + assert_eq!(one, Value::Null, "{key}"); + } + assert_eq!(confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": "fontsFolder"}))), json!(inside)); + + let list = confine(roots.as_ref(), || run(&mut s, "prefs.list", json!({}))); + assert!(!holds(&list, &outside), "{list}"); + let row = |key: &str| list.as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap(); + assert_eq!(row("fontsFolder")["value"], json!(inside)); + assert_eq!(row("pluginsFolder")["value"], Value::Null); + assert_eq!(row("pluginsFolder")["kind"], json!("text"), "the row stays"); + + // A request that sets another preference, or resets a category without folders. + let set = confine(roots.as_ref(), || run(&mut s, "prefs.set", json!({"values": {"keyboardIncrement": 2, "pluginsFolder": outside}}))); + assert_eq!(set, json!({"keyboardIncrement": 2.0, "pluginsFolder": null}), "a folder kept as it was is left out too"); + let reset = confine(roots.as_ref(), || run(&mut s, "prefs.reset", json!({"category": "General"}))); + assert!(!holds(&reset, &outside), "{reset}"); + assert_eq!(reset["prefs"]["fontsFolder"], json!(inside)); + + // Unconfined and with only a write root. + let all = run(&mut s, "prefs.get", json!({})); + assert_eq!(all["prefs"]["pluginsFolder"], json!(outside), "unconfined, the folder is shown"); + assert_eq!(all["prefs"]["screenExportPresets"][1]["settings"]["folder"], json!(outside)); + let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap(); + let all = confine(write_only.as_ref(), || run(&mut s, "prefs.get", json!({}))); + assert_eq!(all["prefs"]["fontsFolder"], Value::Null, "without a read root no folder is shown"); + assert_eq!(all["prefs"]["recoveryFolder"], Value::Null); + assert_eq!(s.prefs.plugins_folder, outside, "the preferences are unchanged"); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index 9fe2d846ce..8248f12a48 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -483,6 +483,777 @@ fn the_folder_store_reads_no_linked_entries() { let _ = std::fs::remove_dir_all(&base); } +/// A file where a folder of the store's path should be: the error names that file, not the area +/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery +/// save. +#[cfg(unix)] +#[test] +fn folder_errors_name_a_file_in_the_way() { + let base = std::env::temp_dir().join(format!("vc-recovery-file-in-way-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let file = base.join("file"); + std::fs::write(&file, b"").unwrap(); + let folder = file.join("recovery"); + let store = FolderStore::new(&folder); + let mut s = Session::new(); + s.prefs.recovery_folder = folder.to_string_lossy().to_string(); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let errors = [ + ("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err()), + ("lock", store.lock("1-2").err()), + ("read", store.read("1-1/Untitled-1-1.vectorcraft").err()), + ("list", store.list().err()), + ("remove", store.remove("1-1/Untitled-1-1.vectorcraft").err()), + ("save", s.execute("file.recovery.save", &json!({})).err().map(|e| e.to_string())), + ]; + let _ = std::fs::remove_dir_all(&base); + let named = format!("{} is not a folder: ", file.display()); + let wrong: Vec<_> = errors.iter().filter(|(_, e)| !e.as_deref().is_some_and(|e| e.contains(&named))).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); +} + +/// A removal that finds the copy missing because a file is on the way to it (how Windows reports a +/// file in the way) names that file. A copy that is just not there still counts as removed. +#[test] +fn a_removal_reported_missing_names_a_file_in_the_way() { + let base = std::env::temp_dir().join(format!("vc-recovery-remove-in-way-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let file = base.join("file"); + std::fs::write(&file, b"").unwrap(); + let missing = || std::io::Error::from(std::io::ErrorKind::NotFound); + let behind = FolderStore::removed(&file.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing())); + let gone = FolderStore::removed(&base.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing())); + let _ = std::fs::remove_dir_all(&base); + let named = format!("{} is not a folder: ", file.display()); + assert!(behind.as_ref().is_err_and(|e| e.starts_with(&named)), "{behind:?}"); + assert_eq!(gone, Ok(())); +} + +/// A folder of the store's path that is missing and can't be made: a write or a lock names it as +/// the folder it couldn't make, and a read names it as missing. An area folder that can't be made +/// in a store folder that is there is named the same way. +#[cfg(unix)] +#[test] +fn folder_errors_name_a_missing_folder_that_cannot_be_made() { + use std::os::unix::fs::PermissionsExt as _; + let base = std::env::temp_dir().join(format!("vc-recovery-missing-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let closed = base.join("closed"); + std::fs::create_dir_all(&closed).unwrap(); + std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o500)).unwrap(); + let gone = closed.join("gone"); + let store = FolderStore::new(gone.join("recovery")); + let unmade = format!("couldn't make {}: ", gone.display()); + let area = FolderStore::new(&closed).write("1-1/Untitled-1-1.vectorcraft", b"copy").err(); + let errors = [ + ("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err(), unmade.clone()), + ("lock", store.lock("1-2").err(), unmade), + ("read", store.read("1-1/Untitled-1-1.vectorcraft").err(), format!("{} is missing", gone.display())), + ("area", area, format!("couldn't make {}: ", closed.join("1-1").display())), + ]; + std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o700)).unwrap(); + let _ = std::fs::remove_dir_all(&base); + // An account that can write anywhere (root) makes the folders, so the test has nothing to check. + if errors[0].1.is_none() { + return; + } + let wrong: Vec<_> = errors.iter().filter(|(_, e, named)| !e.as_deref().is_some_and(|e| e.starts_with(named.as_str()))).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); +} + +/// When every folder on the way is there, an error names the folder it happened on. +#[cfg(unix)] +#[test] +fn folder_errors_name_the_folder_when_every_folder_is_there() { + use std::os::unix::fs::PermissionsExt as _; + let base = std::env::temp_dir().join(format!("vc-recovery-unreadable-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let unreadable = base.join("unreadable"); + std::fs::create_dir_all(&unreadable).unwrap(); + std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o300)).unwrap(); + let listed = FolderStore::new(&unreadable).list(); + std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o700)).unwrap(); + let _ = std::fs::remove_dir_all(&base); + // An account that can read any folder (root) lists it, so the test has nothing to check. + let Err(err) = listed else { return }; + assert!(err.starts_with(&format!("{}: ", unreadable.display())), "{err}"); +} + +/// A store in memory that notes each removal of an area (its lock file and folder, then its empty +/// folder) and whether the area was still held then. +#[derive(Default)] +struct Tidying { + inner: MemoryStore, + removals: std::sync::Mutex>, +} + +impl Tidying { + fn note(&self, what: &'static str, area: &str) { + let held = matches!(self.inner.lock(area), Ok(cmd::recovery::Lock::Busy)); + self.removals.lock().unwrap().push((what, held)); + } +} + +impl RecoveryStore for Tidying { + fn list(&self) -> std::result::Result, String> { + self.inner.list() + } + fn read(&self, name: &str) -> std::result::Result, String> { + self.inner.read(name) + } + fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { + self.inner.write(name, bytes) + } + fn remove(&self, name: &str) -> std::result::Result<(), String> { + self.inner.remove(name) + } + fn location(&self) -> String { + self.inner.location() + } + fn lock(&self, area: &str) -> std::result::Result { + self.inner.lock(area) + } + fn remove_area(&self, area: &str) { + self.note("area", area); + } + fn remove_empty_area(&self, area: &str) { + self.note("empty folder", area); + } + fn now(&self) -> Option { + self.inner.now() + } +} + +/// An app tidying an area away (a crashed app's, or its own when it quits) removes it while it +/// still holds it, so another app taking a new area of that name can't lock it in between. Once it +/// let the area go, it removes the folder again if that is empty. +#[test] +fn areas_are_removed_while_still_held() { + let store = Arc::new(Tidying::default()); + let app = || { + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + s + }; + let mut a = app(); + a.execute("file.recovery.save", &json!({})).unwrap(); + drop(a); + let mut b = app(); + assert_eq!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().len(), 1); + b.execute("file.recovery.save", &json!({})).unwrap(); + b.execute("file.close", &json!({})).unwrap(); + cmd::recovery::forget_all(&mut b); + let tidy = [("area", true), ("empty folder", false)]; + assert_eq!(*store.removals.lock().unwrap(), [tidy, tidy].concat(), "discard's tidy, then quitting"); +} + +/// Another app tidied an empty area away between this app making it and locking it: the area is +/// busy, not held and not an error. +#[test] +fn an_area_tidied_away_before_it_is_locked_is_busy() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-tidied-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + drop(store.lock("5-1").unwrap()); + let area = base.join("5-1"); + let path = area.join(".lock"); + let open = |create: bool| std::fs::OpenOptions::new().read(true).write(true).create(create).truncate(false).open(&path).unwrap(); + // The lock file was opened, then removed before it was locked. + let opened = open(false); + std::fs::remove_file(&path).unwrap(); + assert!(matches!(FolderStore::take(opened, &path), Ok(Lock::Busy))); + // The folder went before it was checked or its lock file opened. + std::fs::remove_dir(&area).unwrap(); + assert!(matches!(FolderStore::lock_area(&area), Ok(Lock::Busy))); + // A lock file made again under the same name is not the one opened, also where it keeps the + // removed one's creation time (NTFS does within 15 seconds). + #[cfg(any(unix, windows))] + { + std::fs::create_dir_all(&area).unwrap(); + let opened = open(true); + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(FolderStore::take(opened, &path), Ok(Lock::Busy))); + assert!(matches!(FolderStore::take(open(false), &path), Ok(Lock::Held(_)))); + } + let _ = std::fs::remove_dir_all(&base); +} + +/// Opening an area's lock file failed. When the folder went after it was checked, or the lock file +/// is there but can't be opened (a removed lock file that another app still has open, on file +/// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an +/// error. +#[test] +fn a_lock_file_that_is_gone_or_cannot_be_opened_is_busy() { + use cmd::recovery::Lock; + use std::io::ErrorKind::{NotFound, PermissionDenied}; + let base = std::env::temp_dir().join(format!("vc-recovery-unopened-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let path = base.join(".lock"); + let failed = |kind: std::io::ErrorKind| FolderStore::open_failed(kind.into(), &path); + assert!(matches!(failed(NotFound), Ok(Lock::Busy))); + assert!(failed(PermissionDenied).is_err()); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(failed(PermissionDenied), Ok(Lock::Busy))); + #[cfg(unix)] + if !rustix::process::geteuid().is_root() { + use std::os::unix::fs::PermissionsExt as _; + let mode = |p: &std::path::Path, m: u32| std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap(); + // A lock file that is there but can't be opened. + let area = base.join("5-1"); + std::fs::create_dir(&area).unwrap(); + std::fs::write(area.join(".lock"), b"").unwrap(); + mode(&area.join(".lock"), 0o400); + assert!(matches!(FolderStore::lock_area(&area), Ok(Lock::Busy))); + // A folder in which no lock file can be made. + let area = base.join("5-2"); + std::fs::create_dir(&area).unwrap(); + mode(&area, 0o500); + let r = FolderStore::lock_area(&area); + mode(&area, 0o700); + assert!(r.is_err()); + } + let _ = std::fs::remove_dir_all(&base); +} + +/// A folder store in which another app tidies the first area away as soon as it is made. +struct TidiedFirst { + inner: FolderStore, + dir: std::path::PathBuf, + first: std::sync::atomic::AtomicBool, +} + +impl RecoveryStore for TidiedFirst { + fn list(&self) -> std::result::Result, String> { + self.inner.list() + } + fn read(&self, name: &str) -> std::result::Result, String> { + self.inner.read(name) + } + fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { + self.inner.write(name, bytes) + } + fn remove(&self, name: &str) -> std::result::Result<(), String> { + self.inner.remove(name) + } + fn location(&self) -> String { + self.inner.location() + } + fn areas(&self) -> std::result::Result, String> { + self.inner.areas() + } + fn lock(&self, area: &str) -> std::result::Result { + if !self.first.swap(false, std::sync::atomic::Ordering::SeqCst) { + return self.inner.lock(area); + } + let dir = self.dir.join(area); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::remove_dir(&dir).unwrap(); + FolderStore::lock_area(&dir) + } + fn remove_area(&self, area: &str) { + self.inner.remove_area(area); + } +} + +#[test] +fn a_recovery_save_takes_the_next_area_when_the_first_is_tidied_away() { + let dir = std::env::temp_dir().join(format!("vc-recovery-next-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = Arc::new(TidiedFirst { inner: FolderStore::new(&dir), dir: dir.clone(), first: true.into() }); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let r = s.execute("file.recovery.save", &json!({})).unwrap(); + let area = s.recovery.own_area().unwrap().to_string(); + assert!(area.ends_with("-2"), "{area}"); + assert_eq!(r["saved"][0]["file"], format!("{area}/Untitled-1-1").as_str(), "{r}"); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A session keeping its copies in folder `dir`, with one modified document whose copy is written. +fn saved_in(dir: &std::path::Path) -> (Session, String) { + let mut s = Session::new(); + s.prefs.recovery_folder = dir.to_string_lossy().to_string(); + s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + s.execute("file.recovery.save", &json!({})).unwrap(); + let area = s.recovery.own_area().unwrap().to_string(); + (s, area) +} + +/// A new app over folder `dir`, with nothing open. +#[cfg(unix)] +fn other_app(dir: &std::path::Path) -> Session { + let mut s = Session::new(); + s.prefs.recovery_folder = dir.to_string_lossy().to_string(); + s +} + +/// The area's lock file was removed while its app runs: the next recovery save locks the area +/// again, so another app neither offers nor discards its copy. +#[cfg(unix)] +#[test] +fn a_recovery_save_locks_the_area_again_when_its_lock_file_was_removed() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-relock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(a.recovery.own_area(), Some(area.as_str())); + let mut b = other_app(&dir); + assert!(offered(&mut b).is_empty()); + assert!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().is_empty()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy))); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The whole area was removed while its app runs: the next recovery save makes it again, locked, +/// with the copy written again. +#[cfg(unix)] +#[test] +fn a_recovery_save_makes_the_area_again_when_it_was_removed() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-remade-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_dir_all(dir.join(&area)).unwrap(); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(r["saved"][0]["file"], format!("{area}/Untitled-1-1").as_str(), "{r}"); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy))); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another app locked the area after its lock file was removed: the next heartbeat takes a new +/// area, and the document is to be copied again there. Its copy in the old area stays until then. +#[cfg(unix)] +#[test] +fn an_area_another_app_locked_meanwhile_is_left_for_a_new_one() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-moved-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let store = FolderStore::new(&dir); + let Ok(Lock::Held(other)) = store.lock(&area) else { panic!("the other app locks the area") }; + let uid = a.doc().unwrap().uid; + assert_eq!(cmd::recovery::heartbeat(&mut a), [uid]); + let mine = a.recovery.own_area().unwrap().to_string(); + assert_ne!(mine, area); + assert!(a.doc().unwrap().recovery.is_none()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file(), "kept until the new copy is written"); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}"); + assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists(), "the copy left there goes"); + assert!(matches!(store.lock(&mine), Ok(Lock::Busy))); + drop(other); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy written in the background into the area the session left meanwhile is not the +/// document's copy: it stays only until the document is copied again in the new area. +#[cfg(unix)] +#[test] +fn a_copy_written_into_an_area_left_meanwhile_goes_once_copied_again() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-inflight-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let store: Arc = Arc::new(FolderStore::new(&dir)); + let (jobs, _) = cmd::recovery::jobs(&mut a, &store).unwrap(); + assert_eq!(jobs.len(), 1); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = store.lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + for j in jobs { + j.write().unwrap(); + j.finish(&mut a); + } + assert!(a.doc().unwrap().recovery.is_none()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + let uid = a.doc().unwrap().uid; + assert_eq!(cmd::recovery::heartbeat(&mut a), [uid], "the next heartbeat has it copied again"); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(r["saved"].as_array().unwrap().len(), 1, "{r}"); + assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists()); + assert!(cmd::recovery::heartbeat(&mut a).is_empty()); + drop(other); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another app locked the area meanwhile and the document is unchanged since its copy: the next +/// recovery save still writes the copy, in the new area. +#[cfg(unix)] +#[test] +fn a_recovery_save_copies_unchanged_documents_into_the_new_area() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-unchanged-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + let mine = a.recovery.own_area().unwrap().to_string(); + assert_ne!(mine, area); + assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}"); + assert!(dir.join(&mine).join("Untitled-1-1.vectorcraft").is_file()); + assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists()); + drop(other); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy left in an area the session had to leave goes at once when its document is saved, +/// reverted or closed, and every one goes when the app quits with nothing unsaved. +#[cfg(unix)] +#[test] +fn copies_left_behind_go_when_their_document_is_saved_reverted_or_closed() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-leftgo-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("recovery"); + let path = base.join("doc.vectorcraft").to_string_lossy().to_string(); + let left = |area: &str| std::fs::read_dir(dir.join(area)).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "vectorcraft")); + for how in ["save", "revert", "close", "quit"] { + let (mut a, _) = saved_in(&dir); + a.execute("document.save", &json!({"path": path})).unwrap(); + a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + a.execute("file.recovery.save", &json!({})).unwrap(); + let area = a.recovery.own_area().unwrap().to_string(); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + assert!(left(&area), "{how}"); + match how { + "save" => a.execute("document.save", &json!({"path": path})).map(drop).unwrap(), + "revert" => a.execute("file.revert", &json!({})).map(drop).unwrap(), + "close" => a.execute("file.close", &json!({})).map(drop).unwrap(), + _ => cmd::recovery::forget_all(&mut a), + } + assert!(!left(&area), "{how}"); + drop(other); + drop(a); + } + let _ = std::fs::remove_dir_all(&base); +} + +/// The lock file was removed: the next heartbeat locks the area again, before any recovery save. +#[cfg(unix)] +#[test] +fn a_heartbeat_locks_the_area_again_when_its_lock_file_was_removed() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-beatlock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + assert!(cmd::recovery::heartbeat(&mut a).is_empty(), "the copy is still there"); + assert_eq!(a.recovery.own_area(), Some(area.as_str())); + assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy))); + assert!(offered(&mut other_app(&dir)).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The lock file was removed and can't be made again (the area folder can't be written to now): +/// the session takes a new area and writes its copy there. +#[cfg(unix)] +#[test] +fn an_area_whose_lock_file_cannot_be_made_again_is_left_for_a_new_one() { + use std::os::unix::fs::PermissionsExt as _; + + use cmd::recovery::Lock; + // Permissions don't stop the superuser. + if rustix::process::geteuid().is_root() { + return; + } + let dir = std::env::temp_dir().join(format!("vc-recovery-readonly-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o500)).unwrap(); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + let mine = a.recovery.own_area().unwrap().to_string(); + assert_ne!(mine, area); + assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}"); + assert!(matches!(FolderStore::new(&dir).lock(&mine), Ok(Lock::Busy))); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o700)).unwrap(); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy left behind that can't be removed when its document is saved (its area can't be written +/// to now) stays the session's own: it isn't offered here, and a later heartbeat removes it. +#[cfg(unix)] +#[test] +fn a_copy_left_behind_that_cannot_be_removed_yet_stays_the_sessions_own() { + use std::os::unix::fs::PermissionsExt as _; + + use cmd::recovery::Lock; + // Permissions don't stop the superuser. + if rustix::process::geteuid().is_root() { + return; + } + let base = std::env::temp_dir().join(format!("vc-recovery-leftstuck-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("recovery"); + let path = base.join("doc.vectorcraft").to_string_lossy().to_string(); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o500)).unwrap(); + a.execute("document.save", &json!({"path": path})).unwrap(); + std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o700)).unwrap(); + let copy = dir.join(&area).join("Untitled-1-1.vectorcraft"); + assert!(copy.is_file()); + drop(other); + assert!(offered(&mut a).is_empty()); + cmd::recovery::heartbeat(&mut a); + assert!(!copy.exists()); + drop(a); + let _ = std::fs::remove_dir_all(&base); +} + +/// A copy left in an area the session had to leave is still the session's own after the app that +/// locked that area is gone: the session neither offers nor discards it. +#[cfg(unix)] +#[test] +fn a_copy_left_behind_is_not_offered_by_its_own_app() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-leftmine-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (mut a, area) = saved_in(&dir); + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(&mut a); + drop(other); + assert!(offered(&mut a).is_empty()); + let r = a.execute("file.recovery.discard", &json!({})).unwrap(); + assert!(r["discarded"].as_array().unwrap().is_empty(), "{r}"); + assert!(a.execute("file.recovery.discard", &json!({"file": format!("{area}/Untitled-1-1")})).is_err()); + assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copy left in an area the session had to leave is not another app's to offer, restore or +/// discard while the session runs, even after the app that locked that area let it go: an entry in +/// the session's new area says it keeps it. Once the copy is written again in the new area, the +/// entry goes; after a crash before that, the copy is offered. +#[cfg(unix)] +#[test] +fn a_copy_left_behind_is_not_offered_by_another_app_while_its_app_runs() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-leftother-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let left_behind = |area: &str| dir.join(area).join("Untitled-1-1.vectorcraft"); + let leave = |a: &mut Session, area: &str| { + std::fs::remove_file(dir.join(area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(area) else { panic!("the other app locks the area") }; + cmd::recovery::heartbeat(a); + drop(other); + a.recovery.own_area().unwrap().to_string() + }; + let (mut a, area) = saved_in(&dir); + let mine = leave(&mut a, &area); + assert_ne!(mine, area); + assert!(dir.join(&mine).join(format!("keeps-{area}")).is_file()); + // Removed meanwhile: the next heartbeat writes it again. + std::fs::remove_file(dir.join(&mine).join(format!("keeps-{area}"))).unwrap(); + cmd::recovery::heartbeat(&mut a); + assert!(dir.join(&mine).join(format!("keeps-{area}")).is_file()); + let mut b = other_app(&dir); + assert!(offered(&mut b).is_empty()); + assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 0); + assert!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().is_empty()); + assert!(b.execute("file.recovery.discard", &json!({"file": format!("{area}/Untitled-1-1")})).is_err()); + assert!(left_behind(&area).is_file()); + // Written again in the new area: the copy left behind and the entry go. + a.execute("file.recovery.save", &json!({})).unwrap(); + assert!(!left_behind(&area).exists()); + assert!(!dir.join(&mine).join(format!("keeps-{area}")).exists()); + assert!(offered(&mut b).is_empty()); + drop(a); + let _ = std::fs::remove_dir_all(&dir); + // A crash before the copy is written again: the copy left behind is offered. + let (mut a, area) = saved_in(&dir); + leave(&mut a, &area); + drop(a); + assert_eq!(offered(&mut other_app(&dir)).len(), 1); + assert!(left_behind(&area).is_file()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A store in memory whose areas named `foreign-…` can't be locked by this account (as another +/// account's folder in a shared recovery folder). +#[derive(Default)] +struct ForeignAreas(MemoryStore); + +impl RecoveryStore for ForeignAreas { + fn list(&self) -> std::result::Result, String> { + self.0.list() + } + fn read(&self, name: &str) -> std::result::Result, String> { + self.0.read(name) + } + fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { + self.0.write(name, bytes) + } + fn remove(&self, name: &str) -> std::result::Result<(), String> { + self.0.remove(name) + } + fn location(&self) -> String { + self.0.location() + } + fn lock(&self, area: &str) -> std::result::Result { + if area.starts_with("foreign-") { + return Err(format!("{area}: belongs to another account")); + } + self.0.lock(area) + } + fn now(&self) -> Option { + self.0.now() + } +} + +/// An entry `/keeps-` in an area this account can't lock keeps nothing: a crashed +/// app's copies in the left area are still offered. +#[test] +fn a_keeps_entry_in_an_area_that_cannot_be_locked_keeps_nothing() { + let store = Arc::new(ForeignAreas::default()); + let app = || { + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s + }; + let mut a = app(); + a.execute("file.new", &json!({"width": 50, "height": 50})).unwrap(); + a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + a.execute("file.recovery.save", &json!({})).unwrap(); + let area = a.recovery.own_area().unwrap().to_string(); + drop(a); + store.write(&format!("foreign-1/keeps-{area}"), b"").unwrap(); + let mut b = app(); + assert_eq!(offered(&mut b).len(), 1); + assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 1); +} + +/// An entry `/keeps-` in a running app's area keeps a crashed app's copies in the +/// left area until that app is gone too. +#[test] +fn a_keeps_entry_in_a_running_apps_area_keeps_the_copies() { + let store = Arc::new(MemoryStore::default()); + let mut a = session_in(&store); + a.execute("file.recovery.save", &json!({})).unwrap(); + let area = a.recovery.own_area().unwrap().to_string(); + drop(a); + let mut c = session_in(&store); + c.execute("file.recovery.save", &json!({})).unwrap(); + let keeper = c.recovery.own_area().unwrap().to_string(); + store.write(&format!("{keeper}/keeps-{area}"), b"").unwrap(); + let mut b = relaunch(&store); + assert!(offered(&mut b).is_empty()); + assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 0); + drop(c); + assert_eq!(offered(&mut b).len(), 2); +} + +/// An entry `/keeps-` in a folder whose lock file can't be opened keeps nothing. +#[cfg(unix)] +#[test] +fn a_keeps_entry_in_a_folder_whose_lock_cannot_be_checked_keeps_nothing() { + let dir = std::env::temp_dir().join(format!("vc-recovery-keepsunlocked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (a, area) = saved_in(&dir); + drop(a); + std::fs::create_dir_all(dir.join("keeper").join(".lock")).unwrap(); + std::fs::write(dir.join("keeper").join(format!("keeps-{area}")), b"").unwrap(); + assert_eq!(offered(&mut other_app(&dir)).len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A complex document (Data Recovery off for those) gets no new copy after the session left its +/// area: it keeps the copy it left there, and the heartbeat asks for it only once. +#[cfg(unix)] +#[test] +fn a_complex_documents_copy_left_behind_is_asked_for_once() { + use cmd::recovery::Lock; + let dir = std::env::temp_dir().join(format!("vc-recovery-leftcomplex-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut a = other_app(&dir); + let mut d = vectorcraft_doc::Document::new(1000.0, 1000.0); + let layer = d.layers[0].id; + for i in 0..cmd::recovery::COMPLEX_OBJECTS { + let id = d.alloc_id(); + let r = vectorcraft_geom::Rect::new((i % 200) as f64, (i / 200) as f64, (i % 200) as f64 + 1.0, (i / 200) as f64 + 1.0); + let n = vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art()); + d.insert(Some(layer), i, n).unwrap(); + } + a.add_document(d, None); + a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + let copy = r["saved"][0]["file"].as_str().unwrap().to_string(); + let area = a.recovery.own_area().unwrap().to_string(); + a.prefs.recovery_off_for_complex = true; + std::fs::remove_file(dir.join(&area).join(".lock")).unwrap(); + let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") }; + let uid = a.doc().unwrap().uid; + assert_eq!(cmd::recovery::heartbeat(&mut a), [uid]); + let r = a.execute("file.recovery.save", &json!({})).unwrap(); + assert!(r["saved"].as_array().unwrap().is_empty(), "{r}"); + assert!(cmd::recovery::heartbeat(&mut a).is_empty(), "asked for once"); + assert!(dir.join(format!("{copy}.vectorcraft")).is_file(), "its copy stays"); + drop(other); + drop(a); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The preference named another folder while a copy was written in the background: the copy goes +/// from the folder it was written to, and the document keeps its copy in the new folder. +#[test] +fn a_copy_finished_after_the_folder_changed_goes_from_its_own_folder() { + let base = std::env::temp_dir().join(format!("vc-recovery-refolder-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (old, new) = (base.join("old"), base.join("new")); + let (mut a, area) = saved_in(&old); + a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let store: Arc = Arc::new(FolderStore::new(&old)); + let (jobs, _) = cmd::recovery::jobs(&mut a, &store).unwrap(); + a.prefs.recovery_folder = new.to_string_lossy().to_string(); + a.execute("file.recovery.save", &json!({})).unwrap(); + let mine = a.doc().unwrap().recovery.as_ref().unwrap().file.clone(); + for j in jobs { + j.write().unwrap(); + j.finish(&mut a); + } + assert!(!old.join(&area).join("Untitled-1-1.vectorcraft").exists()); + assert_eq!(a.doc().unwrap().recovery.as_ref().unwrap().file, mine); + assert!(new.join(format!("{mine}.vectorcraft")).is_file()); + drop(a); + let _ = std::fs::remove_dir_all(&base); +} + #[test] fn saving_reverting_or_closing_removes_the_copy() { let dir = std::env::temp_dir().join(format!("vc-recovery-save-{}", std::process::id())); diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index 68b8b57abc..9932055652 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -40,6 +40,50 @@ fn objects(s: &Session) -> usize { s.doc().unwrap().doc.node_count() } +/// A client confined by automation roots: a save without a path writes the document's own file, and +/// when that file is outside the read roots the reply leaves out its `path` and names the files +/// written beside it by their file names. A reply without a path leaves out a suggested `folder` +/// outside them. A path inside the read roots, and one the client gives, stay whole. +#[test] +fn a_confined_save_leaves_out_paths_outside_the_read_root() { + use crate::file_access::{AutomationRoots, confine}; + + let d = dir("roots"); + let (inside, outside) = (d.join("in"), d.join("out")); + for f in [&inside, &outside] { + std::fs::create_dir_all(f).unwrap(); + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let own = path(&outside, "doc.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + let person = s.execute("document.save", &json!({"separateArtboards": true})).unwrap(); + let files: Vec = person["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!((files.len(), files[0].as_str()), (3, own.as_str()), "{person}"); + + let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap(); + let run = |s: &mut Session, roots: &Option>, id: &str, p: Value| { + confine(roots.as_ref(), || s.execute(id, &p)).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + }; + let hidden = outside.to_string_lossy().into_owned(); + let r = run(&mut s, &write_only, "document.save", json!({})); + assert!(r.get("path").is_none() && r["bytes"].as_u64().is_some_and(|n| n > 0), "{r}"); + assert!(!r.to_string().contains(&hidden), "{r}"); + let r = run(&mut s, &write_only, "document.save", json!({"separateArtboards": true})); + let names: Vec = files.iter().map(|f| json!(std::path::Path::new(f).file_name().unwrap().to_string_lossy())).collect(); + assert_eq!((r.get("path"), r["files"].as_array()), (None, Some(&names)), "{r}"); + // Inside the read roots, or given by the client: whole. + assert_eq!(run(&mut s, &both, "document.save", json!({}))["path"], json!(own)); + assert_eq!(run(&mut s, &write_only, "document.save", json!({"path": own}))["path"], json!(own)); + // A save without a path known suggests the document's folder. + let r = run(&mut s, &write_only, "file.saveCopy", json!({})); + assert!(r.get("folder").is_none() && r["name"] == "doc copy.vectorcraft" && r.get("dataBase64").is_some(), "{r}"); + assert_eq!(run(&mut s, &both, "file.saveCopy", json!({}))["folder"], json!(hidden)); + let _ = std::fs::remove_dir_all(d); +} + #[test] fn an_svg_path_writes_svg_and_save_writes_it_back() { let d = dir("svg"); @@ -425,8 +469,16 @@ fn transparency_grid_round_trips_without_dirtying() { let _ = std::fs::remove_dir_all(d); } +/// The `%%BoundingBox` of an EPS file's PostScript. +fn bounding_box(eps: &[u8]) -> [i64; 4] { + let ps = std::str::from_utf8(vectorcraft_eps::sections(eps).unwrap().0).unwrap(); + let line = ps.lines().find_map(|l| l.strip_prefix("%%BoundingBox:")).expect("a bounding box"); + let v: Vec = line.split_whitespace().map(|n| n.parse().unwrap()).collect(); + [v[0], v[1], v[2], v[3]] +} + #[test] -fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() { +fn opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page() { let d = dir("eps-original-format"); let eps_path = path(&d, "Artwork.eps"); // Original, contributor-authored PostScript: the artwork occupies only part of the page. @@ -440,11 +492,16 @@ fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() { assert_eq!((board.width(), board.height()), (200.0, 100.0)); rect(&mut s); let edited_layers = s.doc().unwrap().doc.layers.clone(); - let r = s.execute("document.save", &json!({"options": {"previewFormat": "none", "thumbnails": false}})).unwrap(); + // Without Use Artboards the bounding box fits the art, as Export draws it; the editing data + // keeps the page. + let quiet = json!({"previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"options": quiet})).unwrap(); assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(eps_path.as_str()), Some("eps"))); let bytes = std::fs::read(&eps_path).unwrap(); assert!(bytes.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0")); - assert!(std::str::from_utf8(vectorcraft_eps::sections(&bytes).unwrap().0).unwrap().contains("%%BoundingBox: 0 0 200 100")); + let exported = b64(&s.execute("document.export", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap()); + assert_eq!(bounding_box(&bytes), bounding_box(&exported)); + assert_ne!(bounding_box(&bytes), [0, 0, 200, 100], "the art does not fill the page"); let editing = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); assert_eq!(editing.artboards[0].rect, board); assert_eq!(editing.layers, edited_layers); @@ -453,26 +510,101 @@ fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() { assert_eq!(opened["restored"], true); assert_eq!(s.doc().unwrap().doc.layers, edited_layers); assert_eq!(s.doc().unwrap().doc.artboards[0].rect, board); + // Use Artboards keeps the opened file's page. + rect(&mut s); + s.execute("document.save", &json!({"options": {"useArtboards": true, "previewFormat": "none", "thumbnails": false}})).unwrap(); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str())); + assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]); + // Save remembers it. rect(&mut s); s.execute("document.save", &json!({})).unwrap(); - assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str())); + assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]); std::fs::remove_dir_all(d).unwrap(); } #[test] -fn eps_save_keeps_all_editing_artboards_while_printing_one_page() { +fn eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": -50, "y": 20, "width": 300, "height": 40})).unwrap(); + let quiet = json!({"previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"format": "eps", "options": quiet})).unwrap(); + let [x0, y0, x1, y1] = bounding_box(&b64(&r)); + assert!(x0 <= -50 && x1 >= 250 && y0 >= 0 && y1 <= 100, "{:?}", [x0, y0, x1, y1]); + for (use_artboards, expected) in [(false, [x0, y0, x1, y1]), (true, [0, 0, 200, 100])] { + let options = json!({"useArtboards": use_artboards, "previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap(); + assert_eq!(bounding_box(&b64(&r)), expected, "useArtboards: {use_artboards}"); + } +} + +#[test] +fn eps_save_keeps_all_editing_artboards_in_the_file_of_one_page() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); rect(&mut s); let r = s.execute("document.save", &json!({"format": "eps", "artboard": 1, "previewFormat": "none", "thumbnails": false})).unwrap(); let bytes = b64(&r); + assert!(r.get("files").is_none(), "{r}"); + let board = s.doc().unwrap().doc.artboards[1].rect; + let [x0, y0, x1, y1] = bounding_box(&bytes); + assert_eq!(((x1 - x0) as f64, (y1 - y0) as f64), (board.width(), board.height())); let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); assert_eq!(native.artboards.len(), 2); assert_eq!(native.layers, s.doc().unwrap().doc.layers); - assert!(s.execute("document.save", &json!({"format": "eps", "range": "all"})).is_err(), "EPS is one printed page"); - for options in [json!({"useArtboards": false}), json!({"selectedOnly": true})] { - assert!(s.execute("document.save", &json!({"format": "eps", "options": options})).is_err(), "cropping is Export's job"); + assert!(s.execute("document.save", &json!({"format": "eps", "options": {"selectedOnly": true}})).is_err(), "selected-only is Export's job"); +} + +#[test] +fn eps_save_with_use_artboards_and_a_named_artboard_reports_it_as_the_range() { + let d = dir("eps-named-artboard"); + let eps_path = path(&d, "Art.eps"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let options = json!({"useArtboards": true, "artboard": 1, "previewFormat": "none", "thumbnails": false}); + s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap(); + let o = s.execute("file.formatOptions", &json!({})).unwrap(); + assert_eq!(o["options"]["useArtboards"]["value"], true); + assert_eq!(o["options"]["range"]["value"], "2", "the saved artboard, not All"); + std::fs::remove_dir_all(d).unwrap(); +} + +#[test] +fn eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard() { + let d = dir("eps-artboards"); + let eps_path = path(&d, "Art.eps"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut s); + let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false}); + let r = s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap(); + let files: Vec = r["files"].as_array().expect("files").iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + assert_eq!(files[0], eps_path, "the file the document becomes comes first"); + assert!(files[1..].iter().all(|f| f.starts_with(&path(&d, "Art_")) && f.ends_with(".eps")), "{files:?}"); + // The central file: the visible art and the whole document. + let central = std::fs::read(&eps_path).unwrap(); + let exported = b64(&s.execute("document.export", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap()); + assert_eq!(bounding_box(¢ral), bounding_box(&exported)); + assert_eq!(vectorcraft_format::load(&vectorcraft_eps::native(¢ral).unwrap()).unwrap().artboards.len(), 2); + // Each artboard's file: its artboard as the page, holding that artboard. + let boards = s.doc().unwrap().doc.artboards.clone(); + for (f, board) in files[1..].iter().zip(&boards) { + let bytes = std::fs::read(f).unwrap(); + let [x0, y0, x1, y1] = bounding_box(&bytes); + assert_eq!(((x1 - x0) as f64, (y1 - y0) as f64), (board.rect.width(), board.rect.height()), "{f}"); + let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap(); + assert_eq!(native.artboards.iter().map(|a| a.rect).collect::>(), [board.rect], "{f}"); } + let st = s.doc().unwrap(); + assert_eq!((st.path.as_deref(), st.is_dirty()), (Some(eps_path.as_str()), false)); + // With no visible art the central file is still written, on the first artboard. + s.execute("select.all", &json!({})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + std::fs::remove_file(&eps_path).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]); + std::fs::remove_dir_all(d).unwrap(); } #[test] @@ -550,7 +682,7 @@ fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data() s.execute("file.new", &json!({"width": 4000, "height": 4000})).unwrap(); rect(&mut s); // Explicit colour preview remains a colour preview; Save bounds its resolution, not the art. - let r = s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap(); + let r = s.execute("document.save", &json!({"format": "eps", "useArtboards": true, "previewFormat": "tiffColor"})).unwrap(); let bytes = b64(&r); let (ps, tiff) = vectorcraft_eps::sections(&bytes).unwrap(); let tiff = tiff.unwrap(); @@ -579,7 +711,7 @@ fn units_and_ruler_guides_survive_save_and_reopen() { s.execute("file.close", &json!({})).unwrap(); s.execute("document.open", &json!({"path": p})).unwrap(); let doc = &s.doc().unwrap().doc; - let guides: Vec<_> = doc.guides.iter().map(|g| (g.vertical, g.pos)).collect(); + let guides: Vec<_> = doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect(); assert_eq!((doc.units, guides), (vectorcraft_doc::Unit::Millimeters, vec![(true, 50.0), (false, 30.0)]), "{ext}"); } let _ = std::fs::remove_dir_all(d); diff --git a/crates/engine/src/tests/script_console.rs b/crates/engine/src/tests/script_console.rs index 985e5b810e..27f53cef07 100644 --- a/crates/engine/src/tests/script_console.rs +++ b/crates/engine/src/tests/script_console.rs @@ -137,7 +137,10 @@ fn the_result_and_the_report_agree_and_count_each_kind_of_host_call() { try { vc.run('no.such', {}); } catch (e) {} var d = vc.document; var c = vc.commands; vc.log({a: 1}); vc.log('two\\nlines'); $.writeln('w');"; let r = run(&mut s, source).unwrap(); assert_eq!(&r, s.script_report().unwrap()); - assert_eq!(r["hostCallCounts"], json!({"vcRun": 3, "documentReads": 1, "commandListReads": 1, "vcLog": 2, "consoleWrites": 1})); + assert_eq!( + r["hostCallCounts"], + json!({"vcRun": 3, "documentReads": 1, "commandListReads": 1, "vcLog": 2, "consoleWrites": 1, "fileCalls": 0, "fileExecutes": 0}) + ); assert_eq!(r["timingAvailable"], true); assert!(r["runTimeMs"].is_u64()); let slow = r["slowestCommands"].as_array().unwrap(); diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index 7572ca52f0..f955a6fdb3 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -217,6 +217,26 @@ fn dialog_loop_stops_or_exhausts() { assert_eq!(art(&s), before); } +#[test] +fn a_run_waiting_at_a_dialog_stops_at_the_next_slice_once_its_work_is_canceled() { + let mut s = one_doc(); + let before = art(&s); + let token = crate::cancel::CancelToken::new(); + s.script_frames = true; + let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); alert('x'); vc.log('answered');"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true); + assert!(crate::cancel::scope(&token, None, || s.script_pump()).is_none()); + assert!(s.script_dialog().is_some()); + token.cancel(); + let ended = crate::cancel::scope(&token, None, || s.script_pump()); + assert!(ended.expect("the run goes on waiting for an answer").is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(s.script_dialog(), None); + assert_eq!(art(&s), before); +} + #[test] fn dialog_text_limits_and_controls() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index d5b9624500..57ff9b15cd 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -5,6 +5,7 @@ use std::time::Duration; use serde_json::{Value, json}; +use crate::cancel::{self, CancelToken}; use crate::script::{TEST_ELAPSED, TEST_NO_CLOCK}; use crate::*; @@ -204,6 +205,36 @@ fn a_sleeping_run_stops_when_asked() { TEST_ELAPSED.set(None); } +#[test] +fn a_sleeping_run_stops_at_the_next_slice_once_its_work_is_canceled() { + for (asleep_until, when) in + [(None, "before its first slice"), (Some(Duration::ZERO), "while it sleeps"), (Some(Duration::from_secs(1)), "at its wake time")] + { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let before = (format!("{:?}", s.documents()[0].doc.layers), s.documents()[0].history.undo.len()); + s.script_frames = true; + TEST_ELAPSED.set(Some(Duration::ZERO)); + let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 5, height: 5}); $.sleep(1000); vc.log('woke'); \ + vc.run('shape.rectangle', {x: 9, y: 0, width: 5, height: 5});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + let token = CancelToken::new(); + if let Some(at) = asleep_until { + assert!(cancel::scope(&token, None, || s.script_pump()).is_none(), "{when}"); + assert_eq!(s.script_sleep_left(), Some(Duration::from_secs(1)), "{when}"); + TEST_ELAPSED.set(Some(at)); + } + token.cancel(); + let ended = cancel::scope(&token, None, || s.script_pump()); + TEST_ELAPSED.set(None); + assert!(ended.unwrap_or_else(|| panic!("{when}: the run goes on waiting")).is_err(), "{when}"); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{when}: {report}"); + assert!(!s.script_running(), "{when}"); + assert_eq!((format!("{:?}", s.documents()[0].doc.layers), s.documents()[0].history.undo.len()), before, "{when}"); + } +} + #[test] fn sleep_takes_milliseconds_from_0_to_1000() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_engines.rs b/crates/engine/src/tests/script_engines.rs new file mode 100644 index 0000000000..3171657b32 --- /dev/null +++ b/crates/engine/src/tests/script_engines.rs @@ -0,0 +1,519 @@ +//! `#targetengine`: named engines whose globals last between the runs that name them, their names +//! and places, their limits, `script.engines` and `script.engine.drop`. + +use std::path::PathBuf; +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::script::{PANIC_IN_SLICE, TEST_ENGINE_HEAP, TEST_KEPT_MAP_BYTES, engines_on_this_thread, releases_kept_for}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn log(s: &mut Session, source: &str) -> Value { + run(s, source).unwrap()["log"].clone() +} + +/// A session with one document holding one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn objects(s: &Session) -> usize { + s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn names(s: &mut Session) -> Vec { + let r = s.execute("script.engines", &json!({})).unwrap(); + r["engines"].as_array().unwrap().iter().map(|e| e["name"].as_str().unwrap().to_string()).collect() +} + +const RECT: &str = "{x: 100, y: 0, width: 5, height: 5}"; + +#[test] +fn a_named_engine_keeps_its_globals_and_functions_between_runs() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "#targetengine \"session\"\nvar n = 41;\nfunction f() { return n + 1; }\nvc.log($.engineName);"), json!(["session"])); + assert_eq!(log(&mut s, "//@targetengine session\nvc.log(f()); n = 1;"), json!([42])); + assert_eq!(log(&mut s, "#targetengine 'session'\nvc.log(n);"), json!([1]), "single quotes name the same engine"); + assert_eq!(log(&mut s, "#targetengine Session\nvc.log(typeof n);"), json!(["undefined"]), "names are matched as written"); + assert_eq!(log(&mut s, "#targetengine other\nvc.log(typeof f);"), json!(["undefined"])); + assert_eq!(log(&mut s, "vc.log(typeof n, $.engineName);\nvc.log($.engineName);"), json!(["undefined", "VectorCraft"])); + // `main` is new for each run, as a script without the line is. + log(&mut s, "#targetengine main\nvar m = 1;"); + assert_eq!(log(&mut s, "#targetengine main\nvc.log(typeof m, $.engineName);\nvc.log($.engineName);"), json!(["undefined", "main"])); + assert_eq!(names(&mut s), ["session", "Session", "other"]); + assert_eq!(log(&mut s, "#targetengine \"Ünï cödé 1\"\nvc.log($.engineName);"), json!(["Ünï cödé 1"])); + let r = s.execute("script.run", &json!({"source": "#targetengine session\n$.engineName = 'x'; vc.log($.engineName);"})).unwrap(); + assert_eq!(r["log"], json!(["session"]), "$.engineName is read-only"); +} + +#[test] +fn engine_names_and_places_are_checked_before_anything_runs() { + let mut s = Session::new(); + let long = "a".repeat(65); + let control = "#targetengine \"a\u{1}b\""; + let cases: Vec<(String, &str, u64)> = vec![ + ("#targetengine".into(), "#targetengine needs a name", 1), + ("#targetengine \"\"".into(), "#targetengine needs a name", 1), + ("#targetengine a b".into(), "#targetengine needs a name of letters, digits and _", 1), + ("#targetengine 9a".into(), "#targetengine needs a name of letters, digits and _", 1), + ("#targetengine \"a\" \"b\"".into(), "#targetengine takes one name", 1), + (format!("#targetengine \"{long}\""), "#targetengine needs a name of at most 64 bytes", 1), + (format!("#targetengine {long}"), "#targetengine needs a name of at most 64 bytes", 1), + (control.into(), "#targetengine needs a name without control characters", 1), + ("#targetengine a\n//@targetengine a".into(), "the script has more than one //@targetengine line", 2), + ("var x;\n#targetengine a".into(), "#targetengine must come before the script's code and #include lines", 2), + ("/* a */ 1;\n#targetengine a".into(), "#targetengine must come before the script's code and #include lines", 2), + ]; + for (source, message, line) in &cases { + let e = run(&mut s, &format!("{source}\nvc.log(1);")).unwrap_err().to_string(); + assert!(e.contains(message), "{source}: {e}"); + assert_eq!(s.script_report().unwrap()["line"], *line, "{source}"); + assert_eq!(s.script_report().unwrap()["log"], json!([]), "{source}"); + } + assert!(names(&mut s).is_empty(), "no failed line made an engine"); + let ok = format!( + "// a comment\n/* and\n another */\n#target vectorcraft\n#script \"Named\"\n #targetengine \"{}\"\nvc.log($.engineName.length);", + "b".repeat(64) + ); + assert_eq!(log(&mut s, &ok), json!([64])); + // A script that does not start: an engine it would make is not kept. + assert!(run(&mut s, "#targetengine broken\nvar = 1;").is_err()); + assert_eq!(names(&mut s), ["b".repeat(64)]); +} + +#[test] +fn only_the_script_itself_names_its_engine() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + std::fs::write(base.join("lib.jsxinc"), "#targetengine lib\nvar a = 1;").unwrap(); + let main = base.join("main.jsx"); + let mut s = Session::new(); + for text in ["#include \"lib.jsxinc\"\n", "$.evalFile('lib.jsxinc');\n"] { + std::fs::write(&main, text).unwrap(); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("#targetengine may only be in the script itself, not in a file it runs"), "{text}: {e}"); + assert!(s.script_report().unwrap()["file"].as_str().unwrap().ends_with("lib.jsxinc"), "{text}"); + } + std::fs::write(base.join("ok.jsxinc"), "var a = 1;").unwrap(); + std::fs::write(&main, "#include \"ok.jsxinc\"\n#targetengine e\n").unwrap(); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("#targetengine must come before the script's code and #include lines"), "{e}"); + assert_eq!(s.script_report().unwrap()["line"], 2); + // An error in a file $.evalFile runs is at that file's place in a kept engine's later runs too. + std::fs::write(base.join("bad.jsxinc"), "var b;\nthrow new Error('here');").unwrap(); + std::fs::write(&main, "#targetengine e\n$.evalFile('ok.jsxinc');").unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + std::fs::write(&main, "#targetengine e\n$.evalFile('bad.jsxinc');").unwrap(); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err()); + let report = s.script_report().unwrap().clone(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("bad.jsxinc")), "{report}"); + assert_eq!(report["line"], 2, "{report}"); + assert_eq!(names(&mut s), ["e"]); + let _ = std::fs::remove_dir_all(base); + // An error in a function an earlier run defined is at that run's line; a script given as text + // is named by its run's name. + run(&mut s, "#targetengine e\n\n\n\nfunction bad() { throw new Error('kept'); }").unwrap(); + let e = run(&mut s, "#targetengine e\nbad();").unwrap_err().to_string(); + let report = s.script_report().unwrap().clone(); + assert_eq!((report["name"].as_str(), report["file"].as_str(), report["line"].as_u64()), (Some("t.js"), Some("t.js"), Some(5)), "{report}"); + let column = report["column"].as_u64().unwrap(); + assert_eq!(error_lines(&report), [format!("t.js: t.js:5:{column}: Error: kept")]); + assert!(e.contains(&format!("line 5, column {column} of t.js")), "{e}"); +} + +/// The console error lines of a run's report. +fn error_lines(report: &Value) -> Vec { + let lines = report["console"]["lines"].as_array().unwrap(); + lines.iter().filter_map(Value::as_str).filter(|l| l.contains("Error: ")).map(str::to_string).collect() +} + +/// The file, line and column of the last run's error. +fn place(s: &Session) -> (Option, u64, u64) { + let r = s.script_report().unwrap(); + (r["file"].as_str().map(str::to_string), r["line"].as_u64().unwrap(), r["column"].as_u64().unwrap()) +} + +/// An error in code an earlier run of a named engine compiled is at the place of that code: in that +/// run's script, a file it included or a file `$.evalFile` gave, while the report and the console +/// line keep the calling run's name. +#[test] +fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-places-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + std::fs::write(base.join("inc.jsxinc"), "\nfunction fromInclude() { throw new Error('inc'); }").unwrap(); + std::fs::write(base.join("ev.jsxinc"), "\n\n\nfunction fromEval() { throw new Error('ev'); }").unwrap(); + let def = base.join("def.jsx"); + let text = "#targetengine e\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');\nfunction fromMain() {\n throw new Error('main');\n}\n\ + function spin() {\n while (true) {}\n}\nfunction badEval() {\n eval('var = 1');\n}"; + std::fs::write(&def, text).unwrap(); + let mut s = Session::new(); + s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap(); + let call = |s: &mut Session, code: &str| { + let e = s.execute("script.run", &json!({"source": format!("#targetengine e\n\n{code}"), "name": "caller.js"})); + assert!(e.is_err(), "{code}"); + }; + let shown = def.to_string_lossy().to_string(); + let ends = |p: &(Option, u64, u64), file: &str, line: u64| p.0.as_deref().is_some_and(|f| f.ends_with(file)) && p.1 == line && p.2 > 0; + call(&mut s, "fromMain();"); + let p = place(&s); + assert!(ends(&p, "def.jsx", 5), "{p:?}"); + let report = s.script_report().unwrap().clone(); + assert_eq!(report["name"], "caller.js"); + assert_eq!(error_lines(&report), [format!("caller.js: {}:5:{}: Error: main", p.0.as_deref().unwrap(), p.2)]); + call(&mut s, "fromInclude();"); + assert!(ends(&place(&s), "inc.jsxinc", 2), "{:?}", place(&s)); + call(&mut s, "fromEval();"); + assert!(ends(&place(&s), "ev.jsxinc", 4), "{:?}", place(&s)); + call(&mut s, "badEval();"); + assert!(ends(&place(&s), "def.jsx", 11), "a syntax error eval raises is at its call: {:?}", place(&s)); + let e = s.execute("script.run", &json!({"source": "#targetengine e\nspin();", "name": "caller.js", "maxFuel": 100_000})); + assert!(e.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "limit"); + assert!(ends(&place(&s), "def.jsx", 8), "the fuel ran out in spin: {:?}", place(&s)); + // A caught error thrown again is where that throw is, in the calling run. + call(&mut s, "try { fromMain(); } catch (x) {\n throw x;\n}"); + assert_eq!(place(&s), (None, 4, 3)); + // A run that fails before it starts compiles nothing, and the kept places stay. + assert!(run(&mut s, "#targetengine e\n#include \"missing.jsxinc\"").is_err()); + call(&mut s, "fromMain();"); + assert!(ends(&place(&s), "def.jsx", 5), "{:?}", place(&s)); + assert!(place(&s).0.is_some_and(|f| f == shown)); + // A dropped engine takes its places with it: the new one has its own. + s.execute("script.engine.drop", &json!({"name": "e"})).unwrap(); + run(&mut s, "#targetengine e\nfunction fromMain() { throw new Error('new'); }").unwrap(); + call(&mut s, "fromMain();"); + assert_eq!(place(&s).0.as_deref(), Some("t.js")); + assert_eq!(place(&s).1, 2); + // The name stands for the earlier script as that run's report gave it, not as console lines + // show it. + s.execute("script.run", &json!({"source": "#targetengine e\nfunction named() { throw 1; }", "name": "a\u{1}b.js"})).unwrap(); + call(&mut s, "named();"); + assert_eq!(place(&s).0.as_deref(), Some("a\u{1}b.js")); + let _ = std::fs::remove_dir_all(base); +} + +/// A named engine keeps the places of its earlier runs' code within its budget, the oldest going +/// first, and the code still runs once its place is gone. +#[test] +fn an_engine_keeps_the_newest_places_within_its_budget() { + let mut s = Session::new(); + run(&mut s, "#targetengine e\nfunction a() { throw new Error('a'); }").unwrap(); + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300))); + run(&mut s, "#targetengine e\n\nfunction b() { throw new Error('b'); }").unwrap(); + for _ in 0..20 { + run(&mut s, "#targetengine e\nvar x = 1;").unwrap(); + } + run(&mut s, "#targetengine e\n\n\nfunction c() { throw new Error('c'); }").unwrap(); + // Each run's own map takes the room of the one before, so c is called first. + assert!(run(&mut s, "#targetengine e\nc();").is_err()); + let c_place = place(&s); + let a = run(&mut s, "#targetengine e\na();").map(drop); + let a_place = place(&s); + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1))); + run(&mut s, "#targetengine e\n\n\n\nfunction d() { throw new Error('d'); }").unwrap(); + assert!(run(&mut s, "#targetengine e\nd();").is_err()); + let d_place = place(&s); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + assert!(a.is_err()); + assert_eq!((a_place.0, a_place.1, a_place.2), (None, 0, 0), "a's place went to make room"); + assert_eq!((c_place.0.as_deref(), c_place.1), (Some("t.js"), 4)); + assert_eq!((d_place.0, d_place.1, d_place.2), (None, 0, 0), "a map larger than the budget is not kept"); +} + +/// A `$.evalFile` an earlier run kept reads files the way the run that calls it does: relative to +/// that run's script, and as `$.evalFile` does in a run given as text. +#[test] +fn a_kept_eval_file_reads_in_the_calling_run_scope() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for dir in ["a", "b"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + std::fs::write(base.join(dir).join("lib.jsxinc"), format!("'{dir}'")).unwrap(); + } + let mut s = Session::new(); + let a = base.join("a").join("main.jsx"); + std::fs::write(&a, "#targetengine e\nvar ev = $.evalFile;\nvc.log(ev('lib.jsxinc'));").unwrap(); + assert_eq!(s.execute("script.run", &json!({"path": a.to_string_lossy()})).unwrap()["log"], json!(["a"])); + let b = base.join("b").join("main.jsx"); + std::fs::write(&b, "#targetengine e\nvc.log(ev('lib.jsxinc'));").unwrap(); + assert_eq!(s.execute("script.run", &json!({"path": b.to_string_lossy()})).unwrap()["log"], json!(["b"]), "the kept function reads beside b"); + let kept = run(&mut s, "#targetengine e\nvc.log(ev('lib.jsxinc'));").map_err(|e| e.to_string()); + let direct = run(&mut s, "vc.log($.evalFile('lib.jsxinc'));").map_err(|e| e.to_string()); + let _ = std::fs::remove_dir_all(base); + assert!(direct.is_err(), "{direct:?}"); + assert_eq!(kept.unwrap_err().split(": ").last(), direct.unwrap_err().split(": ").last(), "a run given as text reads no file beside a"); +} + +/// `File` and `Folder` objects an earlier run kept read in the folder of the run that calls them, +/// `Folder.current` starts at each run's script, and a file an earlier run left open is not open: +/// it takes the encoding it is given, as a closed file does. +#[test] +fn kept_file_objects_read_in_the_calling_run_folder() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for dir in ["a", "b"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + std::fs::write(base.join(dir).join("data.txt"), dir.to_uppercase()).unwrap(); + } + let mut s = Session::new(); + let a = base.join("a").join("main.jsx"); + std::fs::write(&a, "#targetengine e\nvar keep = new File('data.txt');\nkeep.open('r');\nvc.log([Folder.current.name, keep.read(1)]);").unwrap(); + assert_eq!(s.execute("script.run", &json!({"path": a.to_string_lossy()})).unwrap()["log"], json!([["a", "A"]])); + let b = base.join("b").join("main.jsx"); + let text = "#targetengine e\nvar g = new File('data.txt');\ng.open('r');\nvc.log([Folder.current.name, g.read(), keep.read(), keep.error, keep.exists]);\n\ + var before = keep.encoding;\nkeep.encoding = 'BINARY';\nkeep.open('r');\nvc.log([before, keep.encoding]);"; + std::fs::write(&b, text).unwrap(); + let log = s.execute("script.run", &json!({"path": b.to_string_lossy()})).unwrap()["log"].clone(); + let _ = std::fs::remove_dir_all(base); + assert_eq!(log, json!([["b", "B", "", "Script file is not open", false], ["UTF-8", "BINARY"]])); +} + +#[test] +fn a_failed_or_stopped_run_keeps_the_globals_it_set_and_puts_the_documents_back() { + let mut s = one_doc(); + let undo = s.documents()[0].history.undo.len(); + let e = run(&mut s, &format!("#targetengine e\nvar n = 1;\nvc.run('shape.rectangle', {RECT});\nthrow new Error('boom');")); + assert!(e.is_err()); + assert_eq!((objects(&s), s.documents()[0].history.undo.len()), (1, undo), "the documents went back"); + assert_eq!(log(&mut s, "#targetengine e\nvc.log(n);"), json!([1])); + // A stop. + s.script_frames = true; + assert_eq!(run(&mut s, &format!("#targetengine e\nn = 10;\nvc.run('shape.rectangle', {RECT});\nwhile (true) {{}}")).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(s.script_pump().unwrap().is_err()); + s.script_frames = false; + assert_eq!(objects(&s), 1); + // An error in another engine leaves this one as it was. + assert!(run(&mut s, "#targetengine f\nvar n = 99;\nthrow 1;").is_err()); + assert_eq!(log(&mut s, "#targetengine e\nvc.log(n);"), json!([10])); + // A run that ends well is one undo step. + run(&mut s, &format!("#targetengine e\nvc.run('shape.rectangle', {RECT});")).unwrap(); + assert_eq!((objects(&s), s.documents()[0].history.undo.len()), (2, undo + 1)); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); +} + +/// A run stopped at a dialog, or left paused, ends where it was: the engine keeps its globals and +/// the next run starts afresh. +#[test] +fn a_run_stopped_at_a_dialog_or_left_paused_ends_where_it_was() { + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "#targetengine e\nvar n = 20;\nfunction f() { var big = new Array(4000001).join('x'); alert('x'); n = big.length; }\nf();").unwrap(); + for _ in 0..1_000 { + if s.script_dialog().is_some() { + break; + } + assert!(s.script_pump().is_none()); + } + assert!(s.script_dialog().is_some()); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + let heap = s.execute("script.engines", &json!({})).unwrap()["engines"][0]["heapBytes"].as_u64().unwrap(); + assert!(heap < 4 << 20, "the stopped run's frames, and the string they held, are gone: {heap} bytes"); + run(&mut s, "#targetengine e\nn += 1;\nwhile (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert!(s.script_abandon()); + s.script_frames = false; + for _ in 0..3 { + assert_eq!(log(&mut s, "#targetengine e\nvc.log(n);"), json!([21])); + } +} + +#[test] +fn a_kept_host_function_acts_for_the_run_that_calls_it() { + let mut s = one_doc(); + run(&mut s, "#targetengine e\nvar oldRun = vc.run, oldVc = vc, oldWrite = $.writeln, oldAlert = alert;").unwrap(); + // The functions an earlier run kept work in this run's transaction, which goes back. + let e = run(&mut s, &format!("#targetengine e\noldRun('shape.rectangle', {RECT});\noldVc.log('kept');\nthrow new Error('x');")); + assert!(e.is_err()); + assert_eq!(objects(&s), 1, "the kept vc.run's change went back with the run"); + assert_eq!(s.script_report().unwrap()["log"], json!(["kept"])); + let r = s + .execute( + "script.run", + &json!({"source": format!("#targetengine e\noldRun('shape.rectangle', {RECT});\noldWrite('out');\noldAlert('hi');"), "answers": [{"kind": "alert", "value": "ok"}]}), + ) + .unwrap(); + assert_eq!((objects(&s), r["dialogCount"].as_u64()), (2, Some(1))); + assert!(r["console"]["lines"].as_array().unwrap().iter().any(|l| l == "out"), "{r}"); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); + let r = s + .execute( + "script.run", + &json!({"source": "#targetengine e\nvc.log([oldVc.args.n, vc === oldVc, Object.isFrozen(vc.args)]);", "args": {"n": 2}}), + ) + .unwrap(); + assert_eq!(r["log"], json!([[2, true, true]]), "a kept vc gives the calling run's args, frozen"); +} + +/// The values a run sets on `$` in a named engine end with that run, as in a run without one, and +/// a `$` an earlier run kept gives the values of the run that reads it. +#[test] +fn the_values_of_the_dollar_object_belong_to_each_run_of_a_named_engine() { + let mut s = Session::new(); + let read = "vc.log([$.getenv('OS'), $.getenv('LANG'), $.localize, $.flags, $.locale]);"; + let fresh = log(&mut s, read); + let set = "$.setenv('OS', 'set_here');\n$.setenv('LANG', 'set_here');\n$.localize = true;\n$.locale = 'fr_FR';"; + run(&mut s, &format!("#targetengine e\nvar d = $;\n{set}\n{read}")).unwrap(); + assert_eq!(log(&mut s, &format!("#targetengine e\n{read}")), fresh); + let os = fresh[0][0].clone(); + assert_eq!(log(&mut s, "#targetengine e\nvc.log([d === $, d.engineName, d.getenv('OS'), d.localize]);"), json!([[true, "e", os, false]])); + assert_eq!(log(&mut s, "#targetengine e\nd.setenv('OS', 'again');\nvc.log(d.getenv('OS'));"), json!(["again"])); + assert_eq!(log(&mut s, &format!("#targetengine e\n{read}")), fresh); +} + +#[test] +fn an_engine_does_not_keep_a_closed_document() { + let mut s = one_doc(); + let name = s.documents()[0].title(); + run(&mut s, "#targetengine e\nvar snap = vc.document;\nvar read = function () { return vc.document; };").unwrap(); + let weak = Arc::downgrade(&s.documents()[0].doc); + s.execute("file.close", &json!({})).unwrap(); + assert!(weak.upgrade().is_none(), "nothing holds the closed document"); + assert_eq!(log(&mut s, "#targetengine e\nvc.log(read());\nvc.log(snap.name);"), json!([null, name])); +} + +#[test] +fn a_session_keeps_eight_engines_and_drops_them_on_request() { + let mut s = Session::new(); + for i in 0..8 { + run(&mut s, &format!("#targetengine e{i}\nvar v = {i};")).unwrap(); + } + let e = run(&mut s, "#targetengine e8\nvc.log(1);").unwrap_err().to_string(); + assert!(e.contains("a session keeps at most 8 script engines"), "{e}"); + assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_report().unwrap()["log"].clone()), (Some("limit"), json!([]))); + assert_eq!(log(&mut s, "#targetengine e3\nvc.log(v);"), json!([3]), "the eight still run"); + let list = s.execute("script.engines", &json!({})).unwrap(); + assert_eq!((list["limit"].as_u64(), list["heapLimit"].as_u64()), (Some(8), Some(64 << 20))); + for (i, e) in list["engines"].as_array().unwrap().iter().enumerate() { + assert_eq!(e["name"], format!("e{i}")); + assert_eq!(e["running"], false); + assert!(e["heapBytes"].as_u64().unwrap() > 0, "{e}"); + } + assert_eq!(s.execute("script.engine.drop", &json!({"name": "e2"})).unwrap(), json!({"dropped": true, "name": "e2"})); + assert_eq!(names(&mut s), ["e0", "e1", "e3", "e4", "e5", "e6", "e7"]); + run(&mut s, "#targetengine e8\nvar v = 8;").unwrap(); + assert!(run(&mut s, "#targetengine e2\n1").unwrap_err().to_string().contains("at most 8")); + s.execute("script.engine.drop", &json!({"name": "e8"})).unwrap(); + assert_eq!(log(&mut s, "#targetengine e2\nvc.log(typeof v);"), json!(["undefined"]), "a dropped engine comes back new"); + for (params, message) in [ + (json!({"name": "main"}), "the main script engine is new for each run"), + (json!({"name": "nope"}), "there is no script engine named \"nope\""), + (json!({}), "`name` must be the name of a script engine"), + (json!({"name": 3}), "`name` must be the name of a script engine"), + ] { + let e = s.execute("script.engine.drop", ¶ms).unwrap_err().to_string(); + assert!(e.contains(message), "{params}: {e}"); + } + // The running script's engine cannot be dropped; another one can. + s.script_frames = true; + assert_eq!(run(&mut s, "#targetengine e0\nwhile (true) {}").unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(matches!(s.execute("script.engine.drop", &json!({"name": "e0"})), Err(EngineError::Busy))); + let list = s.execute("script.engines", &json!({})).unwrap(); + assert_eq!(list["engines"][0]["running"], true); + s.execute("script.engine.drop", &json!({"name": "e1"})).unwrap(); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + assert_eq!(names(&mut s), ["e0", "e3", "e4", "e5", "e6", "e7", "e2"]); + // A script cannot drop or list engines itself. + s.script_frames = false; + let e = run(&mut s, "vc.run('script.engine.drop', {name: 'e0'});").unwrap_err().to_string(); + assert!(e.contains("a script cannot run `script.engine.drop`"), "{e}"); +} + +#[test] +fn a_named_engine_has_its_own_heap_limit_and_stays_usable() { + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let big = run(&mut s, "#targetengine big\nvar marker = 'set', keep = [];\nfor (var i = 0; i < 10000000; i++) keep.push('item ' + i);"); + // The next run starts on the nearly full heap even with large `args`, and can free memory. + let big_args = json!({"big": "x".repeat(1 << 19)}); + let free = json!({"source": "#targetengine big\nkeep = null;\nvc.log(marker);", "name": "t.js", "args": big_args}); + let kept = s.execute("script.run", &free).unwrap()["log"].clone(); + let after = s.execute("script.engines", &json!({})).unwrap(); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert!(big.unwrap_err().to_string().contains("Heap")); + assert_eq!(kept, json!(["set"]), "the globals set before the limit stay, and the engine still runs"); + assert!(after["engines"][0]["heapBytes"].as_u64().unwrap() < 8 << 20, "{after}"); + // A run without #targetengine keeps the larger heap of one run. + assert_eq!(log(&mut s, "var keep = [];\nfor (var i = 0; i < 300000; i++) keep.push('item ' + i);\nvc.log(keep.length);"), json!([300000])); +} + +/// The engines stay on the thread that made them: a session used on another thread starts there +/// with none, and the engines it left, or that a session dropped elsewhere held, are dropped on +/// their own thread when it next uses its engines. +#[test] +fn a_session_moved_to_another_thread_starts_with_no_engines_and_lets_the_old_ones_go() { + let mut s = Session::new(); + run(&mut s, "#targetengine e\nvar kept = 1;").unwrap(); + assert_eq!(engines_on_this_thread(), 1); + let (mut s, there, listed, thread) = std::thread::spawn(move || { + let there = log(&mut s, "#targetengine e\nvc.log(typeof kept);"); + let listed = names(&mut s); + (s, there, listed, std::thread::current().id()) + }) + .join() + .unwrap(); + assert_eq!((there, listed), (json!(["undefined"]), vec!["e".to_string()])); + assert!(!releases_kept_for(thread), "a thread that ended keeps no list of engines to let go"); + // Back here, the first engine has been let go: the run gets a new one. + assert_eq!(log(&mut s, "#targetengine e\nvc.log(typeof kept);"), json!(["undefined"])); + assert_eq!(engines_on_this_thread(), 1); + assert!(!releases_kept_for(thread), "letting go of the ended thread's engines adds nothing for it"); + std::thread::spawn(move || drop(s)).join().unwrap(); + let mut other = Session::new(); + assert!(names(&mut other).is_empty()); + assert_eq!(engines_on_this_thread(), 0, "the engine of the session dropped on another thread is dropped here"); +} + +#[test] +fn an_internal_error_drops_the_engine() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "#targetengine p\nvar a = 1;\nvc.log(a);"), json!([1])); + assert_eq!(log(&mut s, "#targetengine p\nvc.log(a);"), json!([1])); + s.script_frames = true; + run(&mut s, "#targetengine p\nwhile (true) {}").unwrap(); + PANIC_IN_SLICE.with(|p| p.set(true)); + let r = s.script_pump().unwrap(); + PANIC_IN_SLICE.with(|p| p.set(false)); + assert!(r.is_err()); + assert!(names(&mut s).is_empty()); + s.script_frames = false; + assert_eq!(log(&mut s, "#targetengine p\nvc.log(typeof a);"), json!(["undefined"])); +} + +/// A run whose job is gone took its engine's realm with it: the engine is dropped, so the next run +/// that names it starts it new and other engines stay. +#[test] +fn a_run_whose_job_is_gone_drops_its_engine() { + for abandon in [true, false] { + let mut s = Session::new(); + run(&mut s, "#targetengine kept\nvar k = 1;").unwrap(); + run(&mut s, "#targetengine lost\nvar a = 1;").unwrap(); + s.script_frames = true; + run(&mut s, "#targetengine lost\nwhile (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert!(crate::script::forget_job(&s)); + if abandon { + assert!(s.script_abandon()); + } else { + assert!(s.script_pump().unwrap().is_err()); + } + s.script_frames = false; + assert_eq!(names(&mut s), ["kept"], "abandon: {abandon}"); + assert_eq!(log(&mut s, "#targetengine lost\nvc.log(typeof a);"), json!(["undefined"]), "abandon: {abandon}"); + assert_eq!(log(&mut s, "#targetengine kept\nvc.log(k);"), json!([1]), "abandon: {abandon}"); + } +} diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 0c9ab45b20..e5acc536cc 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -192,7 +192,7 @@ fn script_target_other_app_does_not_route() { assert_eq!(r["log"], json!([1])); for (source, message) in [ ("#target\nvc.log(1);", "#target needs a value"), - ("#targetengine \"session\"", "unsupported script directive: #targetengine"), + ("#targetengine \"session\"", "#targetengine must come before the script's code and #include lines"), ("#engine \"main\"", "unsupported script directive: #engine"), ("#strict maybe", "#strict takes on or off"), ("#frobnicate 1", "unknown script directive: #frobnicate"), @@ -563,3 +563,19 @@ fn script_eval_file_error_caught_and_thrown_again_is_at_the_new_throw() { } let _ = std::fs::remove_dir_all(base); } + +#[test] +fn script_error_that_passes_through_a_finally_block_is_at_its_throw() { + let base = folder("finally"); + let main = base.join("main/main.jsx"); + let mut s = Session::new(); + for text in ["try {\n throw new Error('x');\n} finally {\n var z=1;\n}", "try {\n null();\n} finally {\n var z=1;\n}"] { + write(&main, text); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "{text}"); + let report = s.script_report().unwrap().clone(); + let (l, c, f, error) = place(&report); + assert_eq!((report["kind"].as_str(), l, c, f), (Some("thrown"), 2, 3, None), "{text}\n{report}"); + assert!(error.contains("main.jsx:2:3: "), "{error}"); + } + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs new file mode 100644 index 0000000000..d8c5d1d2e4 --- /dev/null +++ b/crates/engine/src/tests/script_io.rs @@ -0,0 +1,482 @@ +//! `File` and `Folder` in a script: their classes and names, reading inside the script's own folder, +//! the paths refused before anything is looked up, the read limits, and the parts that write, which +//! are not available. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::file_access::{AutomationRoots, confine, script_probes}; +use crate::*; + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + base +} + +fn write(path: &Path, bytes: &[u8]) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// Runs `main/main.jsx` in `base`, with the text `text`. +fn run(base: &Path, text: &str) -> Value { + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap() +} + +/// The values the run of `text` logged. +fn logged(base: &Path, text: &str) -> Value { + run(base, text)["log"].clone() +} + +#[test] +fn file_constructor_identity_and_folder_path() { + let base = folder("identity"); + write(&base.join("main/data.txt"), b"x"); + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + let log = logged( + &base, + "var a = new File('data.txt'), b = new File('data.txt');\n\ + vc.log([a === b, a instanceof File, a instanceof Folder, File('sub') instanceof Folder, new File('sub') instanceof File,\n\ + Folder('data.txt') instanceof File, new Folder('data.txt') instanceof Folder, File('nope') instanceof File,\n\ + a.parent instanceof Folder, a.name, a.parent.fsName === Folder.current.fsName, String(a) === a.absoluteURI,\n\ + a.exists, new File('nope').exists, a.length, a.created instanceof Date, Folder('sub').exists, new File().exists]);", + ); + assert_eq!(log, json!([[false, true, false, true, true, true, true, true, true, "data.txt", true, true, true, false, 1, true, true, false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `exists` is true only when the path names an entry of the object's own kind. +#[test] +fn script_file_exists_checks_the_kind() { + let base = folder("kind"); + write(&base.join("main/data.txt"), b"x"); + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + let log = + logged(&base, "vc.log([new File('sub').exists, new Folder('data.txt').exists, new File('data.txt').exists, new Folder('sub').exists]);"); + assert_eq!(log, json!([[false, false, true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A property a script puts on `Object.prototype` is not read as part of what the app returns. +#[test] +fn script_file_ignores_inherited_result_fields() { + let base = folder("inherited"); + write(&base.join("main/data.txt"), b"data"); + let log = logged( + &base, + "Object.prototype.error = 'inherited'; Object.prototype.exists = true;\n\ + var f = new File('data.txt'); var opened = f.open('r');\n\ + vc.log([f.exists, new File('nope').exists, opened, f.error, f.read()]);", + ); + assert_eq!(log, json!([[true, false, true, "", "data"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `File.encode`, `File.decode`, `File.isEncodingAvailable` and the `Folder` locations are counted as +/// calls to the app. +#[test] +fn script_file_class_functions_are_counted() { + let source = "File.encode('x'); File.decode('y'); Folder.isEncodingAvailable('UTF-8'); Folder.temp;"; + let r = Session::new().execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["hostCallCounts"]["fileCalls"], 4, "{r}"); +} + +#[test] +fn file_names_are_uri_encoded_and_current_relative() { + let base = folder("names"); + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + let log = logged( + &base, + "var f = new File('caf%C3%A9 x.txt');\n\ + var sep = File.fs === 'Windows' ? '\\\\' : '/';\n\ + vc.log([f.name, f.displayName, f.relativeURI, f.fsName === Folder.current.fsName + sep + 'caf\\u00e9 x.txt',\n\ + File.encode('\\u00e9 /'), File.decode('%C3%A9'), new File('sub/../sub/./y.txt').relativeURI,\n\ + new File('~/z').fsName === new Folder('~').fsName + sep + 'z', new File('a/b').path === new Folder('a').absoluteURI]);\n\ + Folder.current = new Folder('sub');\n\ + vc.log([new File('w').parent.name, new File('w').relativeURI, new File('../w').getRelativeURI(Folder.current.parent)]);\n\ + var l = new File('literal%2520name.txt'); Folder.current = new Folder('p%2541');\n\ + vc.log([l.displayName, l.name, l.absoluteURI.slice(-20), l.fsName === new File(l).fsName, Folder.current.displayName, new File('x').parent.displayName]);", + ); + assert_eq!( + log, + json!([ + ["caf%C3%A9%20x.txt", "caf\u{e9} x.txt", "caf%C3%A9%20x.txt", true, "%C3%A9%20/", "\u{e9}", "sub/y.txt", true, true], + ["sub", "w", "w"], + ["literal%20name.txt", "literal%2520name.txt", "literal%2520name.txt", true, "p%41", "p%41"] + ]) + ); + if cfg!(windows) { + let log = logged(&base, "vc.log([new File('/c/a b/x.txt').fsName, new File('C:/a/x.txt').absoluteURI, new File('d:\\\\q').fsName]);"); + assert_eq!(log, json!([["C:\\a b\\x.txt", "/c/a/x.txt", "D:\\q"]])); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_without_scope_cannot_probe_home() { + let base = folder("home"); + let source = "var f = File('~/.ssh/id_test'); var g = new Folder('~');\n\ + vc.log([f instanceof File, f.exists, f.open('r'), f.error, g.getFiles(), g.error, f.modified, f.length]);"; + let denied = json!([[true, false, false, "Script file access denied", null, "Script file access denied", null, 0]]); + let before = script_probes(); + let r = Session::new().execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["log"], denied, "a script given as text reads nothing"); + assert_eq!(script_probes(), before, "nothing was looked up"); + // A script run from a file is held to its folder. + let before = script_probes(); + assert_eq!(logged(&base, source), denied); + assert_eq!(script_probes(), before, "the home folder lies outside the script's folder by its names alone"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_unc_rejected_before_lookup() { + let base = folder("unc"); + let before = script_probes(); + let log = logged( + &base, + "var out = [];\n\ + var paths = ['\\\\\\\\host\\\\s\\\\x.txt', '//host/s/x.txt', '\\\\\\\\?\\\\C:\\\\x.txt', '\\\\\\\\.\\\\pipe\\\\x'];\n\ + for (var i = 0; i < paths.length; i++) { var f = new File(paths[i]); out.push(f.exists, f.open('r'), new Folder(paths[i]).getFiles()); }\n\ + vc.log(out);", + ); + assert_eq!(log, json!([[false, false, null, false, false, null, false, false, null, false, false, null]])); + if cfg!(windows) { + assert_eq!(script_probes(), before, "no network or device path was looked up"); + } else { + // Outside Windows the backslash forms are relative file names in the script's folder, and + // `//host/s/x.txt` is an absolute path outside it. + let before = script_probes(); + let log = logged(&base, "var f = new File('//host/s/x.txt'); vc.log([f.exists, f.open('r'), new Folder('//host/s/x.txt').getFiles()]);"); + assert_eq!(log, json!([[false, false, null]])); + assert_eq!(script_probes(), before, "a path outside the script's folder was not looked up"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_link_escape_refused() { + let base = folder("links"); + write(&base.join("outside/secret.txt"), b"secret"); + write(&base.join("main/own.txt"), b"own"); + std::fs::create_dir_all(base.join("main/inner")).unwrap(); + // A folder link: a symbolic link, or on Windows a junction, which needs no privilege. + let link_folder = |target: &Path, link: &Path| { + #[cfg(unix)] + std::os::unix::fs::symlink(target, link).unwrap(); + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().unwrap(); + assert!(made.status.success(), "mklink /J: {}", String::from_utf8_lossy(&made.stderr)); + } + }; + link_folder(&base.join("outside"), &base.join("main").join("away")); + link_folder(&base.join("main").join("inner"), &base.join("main").join("near")); + let log = logged( + &base, + "var away = new Folder('away'); var s = new File('away/secret.txt');\n\ + vc.log([away.exists, away.getFiles(), away.error, away.resolve(), s.exists, s.open('r'), s.error,\n\ + Folder.current.getFiles().map(function (f) { return f.name; }), new Folder('near').alias, new Folder('near').resolve().name]);", + ); + assert_eq!(log, json!([[false, null, DENIED, null, false, false, DENIED, ["inner", "main.jsx", "near", "own.txt"], true, "inner"]])); + // A missing file behind the link is refused like an existing one, so nothing tells them apart. + let log = logged(&base, "var n = new File('away/nope.txt'); vc.log([n.exists, n.open('r'), n.error]);"); + assert_eq!(log, json!([[false, false, DENIED]])); + // A folder link to an outside folder that does not exist is refused the same way, so a script + // cannot tell whether the folder it leads to exists. + link_folder(&base.join("gone"), &base.join("main").join("dangling")); + let log = logged( + &base, + "var d = new File('dangling/nope.txt'); var e = new File('dangling/a/b.txt');\n\ + vc.log([d.exists, d.open('r'), d.error, e.open('r'), e.error]);", + ); + assert_eq!(log, json!([[false, false, DENIED, false, DENIED]])); + let dangling = base.join("main").join("dangling"); + std::fs::remove_dir(&dangling).or_else(|_| std::fs::remove_file(&dangling)).unwrap(); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_file(target, link).is_ok(); + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + // Windows needs Developer Mode or elevation to make a link to a file. + if !made(&base.join("outside/secret.txt"), &base.join("main/leak.txt")) { + eprintln!("skipped: links to files can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + assert!(made(&base.join("main/own.txt"), &base.join("main/alias.txt"))); + let log = logged( + &base, + "var leak = new File('leak.txt');\n\ + vc.log([leak.exists, leak.open('r'), leak.error, leak.resolve(), new File('away/secret.txt').exists, new Folder('away').getFiles(),\n\ + Folder.current.getFiles().map(function (f) { return f.name; }), new File('alias.txt').alias, new File('alias.txt').resolve().name]);", + ); + assert_eq!(log, json!([[false, false, DENIED, null, false, null, ["alias.txt", "inner", "main.jsx", "near", "own.txt"], true, "own.txt"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A path whose names differ from the script's folder only in case is that folder where case does +/// not matter, and outside it where case matters, whether or not the file is there. +#[test] +fn script_file_case_variant_folder() { + let base = folder("case"); + write(&base.join("main/own.txt"), b"own"); + let upper = base.join("MAIN"); + let source = |name: &str| { + let p = format!("{:?}", upper.join(name).to_string_lossy()); + format!("var f = new File({p}); vc.log([f.exists, f.open('r'), f.error]);") + }; + if upper.exists() { + // Case does not matter here: `MAIN` is the script's folder. + assert_eq!(logged(&base, &source("own.txt")), json!([[true, true, ""]])); + assert_eq!(logged(&base, &source("nope.txt")), json!([[false, false, "Script file does not exist"]])); + } else { + let denied = json!([[false, false, DENIED]]); + assert_eq!(logged(&base, &source("nope.txt")), denied, "MAIN does not exist"); + write(&upper.join("secret.txt"), b"secret"); + assert_eq!(logged(&base, &source("secret.txt")), denied); + assert_eq!(logged(&base, &source("nope.txt")), denied, "MAIN exists beside main"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_oversize_refused_before_read() { + let base = folder("oversize"); + let big = std::fs::File::create(base.join("main/big.bin")).unwrap(); + big.set_len(9 << 20).unwrap(); + drop(big); + write(&base.join("main/small.txt"), b"ok"); + let r = + run(&base, "var f = new File('big.bin'); var s = new File('small.txt'); vc.log([f.length, f.open('r'), f.error, s.open('r'), s.read()]);"); + assert_eq!(r["log"], json!([[9437184, false, "Script file exceeds 8 MiB", true, "ok"]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_files_read_at_most_32_mib_in_a_run() { + let base = folder("total"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 5; i++) { f.open('r'); vc.log(i); }"); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})); + assert!(e.is_err(), "the fifth open passes 32 MiB"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([0, 1, 2, 3])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_files_have_at_most_256_open() { + let base = folder("open"); + write(&base.join("main/empty.txt"), b""); + let log = logged( + &base, + "var all = [], fails = 0, error = '';\n\ + for (var i = 0; i < 300; i++) { var f = new File('empty.txt'); if (f.open('r')) all.push(f); else { fails++; error = f.error; } }\n\ + var closed = all[0].close(); var again = new File('empty.txt');\n\ + vc.log([all.length, fails, error, closed, again.open('r'), all[1].open('r'), new File('empty.txt').open('r')]);", + ); + assert_eq!(log, json!([[256, 44, "Script has 256 files open", true, true, true, false]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_folder_getfiles_stays_inside_scope() { + let base = folder("list"); + for name in ["a.jsx", "b.txt", "C.JSX"] { + write(&base.join("main").join(name), b""); + } + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + write(&base.join("outside.jsx"), b""); + let log = logged( + &base, + "var d = Folder.current; var names = function (l) { var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; };\n\ + vc.log(names(d.getFiles('*.jsx')));\n\ + vc.log(names(d.getFiles(function (f) { return f instanceof Folder; })));\n\ + var up = d.parent; vc.log([names(d.getFiles('?.txt')), d.getFiles().length, up.getFiles(), up.error]);\n\ + try { d.getFiles(function () { throw new Error('stop'); }); } catch (e) { vc.log(e.message); }\n\ + vc.log([new Folder('nope').getFiles(), d.getFiles('*.jsx')[0] instanceof File]);", + ); + assert_eq!(log, json!([["C.JSX", "a.jsx", "main.jsx"], ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); + let many = base.join("main/many"); + for i in 0..=crate::script::files::MAX_ENTRIES { + write(&many.join(format!("{i:04}.txt")), b""); + } + let log = logged(&base, "var m = new Folder('many'); vc.log([m.getFiles(), m.error, m.getFiles('0001.*').length]);"); + assert_eq!(log, json!([[null, "Script folder has more than 2,048 entries", 1]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_bom_and_line_read() { + let base = folder("lines"); + write(&base.join("main/lines.txt"), b"\xEF\xBB\xBFone\r\ntwo\n\rthree\rfour\nfin"); + write(&base.join("main/e.txt"), "\u{e9}t\u{e9}".as_bytes()); + let log = logged( + &base, + "var f = new File('lines.txt'); var out = [f.eof, f.open('r'), f.encoding, f.tell()];\n\ + var lines = []; while (!f.eof) lines.push(f.readln()); out.push(lines, f.tell());\n\ + out.push(f.seek(3), f.read(3), f.seek(-3, 2), f.read(), f.seek(1, 1), f.seek(100), f.seek(-1), f.tell());\n\ + f.seek(6); out.push(f.readch(), f.readch(), f.tell(), f.close(), f.read(), f.error, f.eof);\n\ + var e = new File('e.txt'); e.open(); out.push(e.read(1), e.tell(), e.read(5), e.tell());\n\ + vc.log(out);", + ); + assert_eq!( + log, + json!([[ + true, + true, + "UTF-8", + 3, + ["one", "two", "three", "four", "fin"], + 27, + true, + "one", + true, + "fin", + false, + false, + false, + 27, + "\n", + "t", + 9, + true, + "", + "Script file is not open", + true, + "\u{e9}", + 2, + "t\u{e9}", + 5 + ]]) + ); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_encoding_binary_ascii() { + let base = folder("encodings"); + write(&base.join("main/bytes.bin"), &[0xE8, 0x41]); + write(&base.join("main/euro.txt"), &[0x80]); + let log = logged( + &base, + "var b = new File('bytes.bin'); b.encoding = 'BINARY'; b.open('r'); var t = b.read();\n\ + var a = new File('bytes.bin'); a.encoding = 'ASCII'; a.open('r');\n\ + var out = [t.charCodeAt(0), t.charAt(1), b.encoding, a.read(), a.error, a.tell()];\n\ + a.encoding = 'binary'; out.push(a.encoding, a.read().length);\n\ + var c = new File('euro.txt'); c.open('r'); out.push(c.encoding, c.read().charCodeAt(0));\n\ + var k = new File('bytes.bin'); k.encoding = 'KLINGON'; out.push(k.open('r'), k.error);\n\ + out.push(File.isEncodingAvailable('utf-8'), Folder.isEncodingAvailable('BINARY'), File.isEncodingAvailable('KLINGON'));\n\ + vc.log(out);\n\ + var m = new File('bytes.bin'); m.encoding = 'BINARY'; m.open('r'); m.encoding = 'KLINGON'; vc.log([m.error, m.encoding, m.read().length]);\n\ + var r = new File('bytes.bin'); r.open('r'); r.encoding = 'ASCII'; r.close(); vc.log([r.encoding, r.open('r'), r.read(), r.error]);", + ); + let undecodable = "Script file cannot be decoded"; + assert_eq!(log[0], json!([232, "A", "BINARY", "", undecodable, 0, "BINARY", 2, "CP1252", 0x20AC, false, undecodable, true, true, false])); + assert_eq!(log[1], json!([undecodable, "BINARY", 2]), "a name that is not an encoding leaves the open file's encoding"); + assert_eq!(log[2], json!(["ASCII", true, "", undecodable]), "an encoding set while open is kept after close"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_file_writes_dialogs_and_execute_are_not_available() { + let base = folder("writes"); + write(&base.join("main/keep.txt"), b"keep"); + let r = run( + &base, + "var f = new File('keep.txt'); var n = new File('new.txt');\n\ + var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.write('x'), f.remove(), f.copy('c.txt'), f.rename('r.txt')];\n\ + out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ + f.hidden = true; out.push(f.error, f.hidden); f.error = ''; out.push(f.error);\n\ + vc.log(out);", + ); + assert_eq!( + r["log"], + json!([[ + false, + "Script file writing is not available", + false, + false, + false, + "Script file open mode must be r, w, e or a", + false, + false, + false, + false, + false, + null, + "Script file dialogs are not available", + null, + null, + false, + "Script files cannot be opened in another application", + "Script file writing is not available", + false, + "" + ]]) + ); + assert_eq!(r["hostCallCounts"]["fileExecutes"], 1); + assert!(r["hostCallCounts"]["fileCalls"].as_u64().unwrap() > 0); + assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); + assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A run with automation roots in force reads inside its folder and the read roots, and a run given +/// as text reads nothing even where the roots allow it. +#[test] +fn script_files_read_inside_the_automation_read_roots() { + let base = folder("roots"); + write(&base.join("main/data.txt"), b"data"); + let source = "var f = new File('data.txt'); vc.log([f.exists, f.open('r'), f.error, f.read()]);"; + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + assert_eq!(confine(roots.as_ref(), || logged(&base, source)), json!([[true, true, "", "data"]])); + let text = format!("var f = new File({:?}); vc.log([f.exists, f.error]);", base.join("main/data.txt").to_string_lossy()); + let r = confine(roots.as_ref(), || Session::new().execute("script.run", &json!({"source": text})).unwrap()); + assert_eq!(r["log"], json!([[false, "Script file access denied"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A path longer than 32,767 characters is refused before it is split into names. +#[test] +fn script_file_path_length_is_bounded() { + let base = folder("longpath"); + let log = logged( + &base, + "var s = 'a/'; while (s.length < 40000) s += s;\n\ + var out = []; try { new File(s); } catch (e) { out.push(e.name, e.message); }\n\ + try { new Folder('x').getRelativeURI(s); } catch (e) { out.push(e.name); }\n\ + out.push(new File(s.slice(0, 30000)).exists); vc.log(out);", + ); + assert_eq!(log, json!([["RangeError", "Script file path exceeds 32,767 characters", "RangeError", false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// An error `File` or `Folder` throws is reported at the script's line that called it. +#[test] +fn script_file_errors_are_at_the_calling_line() { + let base = folder("errors"); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, b"\n\n\nnew File('x').read(-1);"); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("RangeError: File.read: the count must be a finite number"), "{report}"); + assert_eq!(report["line"].as_u64(), Some(4), "{report}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 8294aa638a..417798a862 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -166,7 +166,7 @@ fn an_error_names_the_script_its_place_and_kind() { let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); - assert!(run(&mut s, "#targetengine x\n1").unwrap_err().to_string().contains("unsupported script directive: #targetengine")); + assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); assert_eq!(s.script_report().unwrap()["line"], 1); } @@ -845,6 +845,30 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() { assert_eq!(state(&s), before); } +#[test] +fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { + TEST_GROWTH.with(|g| g.set(Some(20))); + let mut s = two_docs(); + let before = state(&s); + s.script_frames = true; + run(&mut s, "for (var i = 0; i < 25; i++) vc.run('shape.rectangle', {x:i,y:1,width:1,height:1});").unwrap(); + let token = crate::cancel::CancelToken::new(); + for _ in 0..1_000 { + if s.script_waiting() { + break; + } + assert!(crate::cancel::scope(&token, None, || s.script_pump()).is_none()); + } + assert!(s.script_waiting()); + token.cancel(); + let ended = crate::cancel::scope(&token, None, || s.script_pump()); + TEST_GROWTH.with(|g| g.set(None)); + assert!(ended.expect("the run goes on waiting for Continue").is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert!(!s.script_running()); + assert_eq!(state(&s), before); +} + #[test] fn a_file_saved_before_a_failure_stays_written_and_is_named() { let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id())); diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs new file mode 100644 index 0000000000..d2160fba34 --- /dev/null +++ b/crates/engine/src/tests/select_effects.rs @@ -0,0 +1,393 @@ +//! Clicks, hovers and marquees with the selection tools leave out the area that raster effects +//! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the +//! effect, or nothing. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s +} + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// A rectangle filled with `color`. +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64, color: &str) -> NodeId { + let id = id_of(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))); + run(s, "select.set", json!({"ids": [id.0]})); + run(s, "paint.setFill", json!({"color": color})); + id +} + +/// A drop shadow on the whole of `id`, `dx` to the right, with no blur. +fn shadow(s: &mut Session, id: NodeId, dx: f64) { + run(s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [id.0], "params": {"x": dx, "y": 0, "blur": 0}, "item": null})); +} + +fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] { + let doc = s.doc().unwrap().doc.clone(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(x, y) +} + +fn press(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64), mods: Mods) -> Vec { + let v = ViewInfo::default(); + s.select_tool(tool, v).unwrap(); + for (k, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + if k == PointerKind::Drag && from == to { + continue; + } + s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), v).unwrap(); + } + s.active().unwrap().selection.objects.clone() +} + +/// Click with the Selection tool at (x, y) on a 100% view: what is selected afterwards. +fn click(s: &mut Session, x: f64, y: f64) -> Vec { + press(s, "selection", (x, y), (x, y), Mods::default()) +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +const WHITE: [u8; 4] = [255; 4]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; + +/// Blue B at x 100 to 160, red A over its left edge's side at x 20 to 80, and A's shadow +/// 40 pt to the right, from x 60 to 120: over the canvas from 80 to 100 and over B from 100 to 120. +fn shadow_over_b(s: &mut Session) -> (NodeId, NodeId) { + let b = rect(s, 100.0, 20.0, 60.0, 60.0, "#0000ff"); + let a = rect(s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + shadow(s, a, 40.0); + (a, b) +} + +#[test] +fn a_click_on_a_drop_shadow_selects_the_object_under_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + // The shadow paints over B and over the canvas. + assert_ne!(pixel(&s, 110, 50), BLUE); + assert_ne!(pixel(&s, 90, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 110.0, 50.0), [b]); + assert_eq!(click(&mut s, 50.0, 50.0), [a]); +} + +#[test] +fn a_click_on_a_drop_shadow_over_the_canvas_selects_nothing_and_clears_the_selection() { + let mut s = session(); + let (a, _) = shadow_over_b(&mut s); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(click(&mut s, 90.0, 50.0).is_empty()); +} + +#[test] +fn a_click_on_an_outer_glow_or_a_gaussian_blur_outside_the_path_selects_what_is_under_it() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "stylize.outerGlow", "ids": [a.0], "params": {"blur": 20, "mode": "normal"}, "item": null})); + assert_ne!(pixel(&s, 88, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 88.0, 50.0).is_empty()); + // A red square whose blur reaches over the canvas and over the left edge of a blue one. + let mut s = session(); + let b = rect(&mut s, 92.0, 20.0, 60.0, 60.0, "#0000ff"); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "blur.gaussian", "ids": [a.0], "params": {"radius": 20}, "item": null})); + assert_ne!(pixel(&s, 98, 50), BLUE); + assert_ne!(pixel(&s, 87, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 98.0, 50.0), [b]); + // (With B deselected, so that the press does not take its bounding box handle.) + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 87.0, 50.0).is_empty()); +} + +/// The first point of `area` (x0, y0, x1, y1) that the canvas paints, scanning rows. +fn painted_in(s: &Session, (x0, y0, x1, y1): (u32, u32, u32, u32)) -> Option<(f64, f64)> { + let doc = s.doc().unwrap().doc.clone(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let img = vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts); + (y0..y1) + .flat_map(|y| (x0..x1).map(move |x| (x, y))) + .find(|&(x, y)| img.pixel(x, y) != WHITE) + .map(|(x, y)| (f64::from(x) + 0.5, f64::from(y) + 0.5)) +} + +#[test] +fn a_click_on_the_drop_shadow_of_a_group_or_of_point_type_selects_neither() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 30.0, 30.0, "#ff0000"); + let b = rect(&mut s, 60.0, 20.0, 30.0, 30.0, "#ff0000"); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + shadow(&mut s, g, 80.0); + // The group's shadow lies from x 100 to 170. + assert_ne!(pixel(&s, 110, 35), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 110.0, 35.0).is_empty()); + assert_eq!(click(&mut s, 35.0, 35.0), [g]); + // Type 40 pt high at y 150 with its shadow 90 pt to the right. + let t = id_of(&run(&mut s, "text.create", json!({"x": 20, "y": 150, "text": "HH", "size": 40}))); + shadow(&mut s, t, 90.0); + let right = bounds(&s, t).x1; + assert!(right < 100.0, "{right}"); + let at = painted_in(&s, (right.ceil() as u32 + 10, 110, 199, 160)).expect("the type's shadow paints"); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, at.0, at.1).is_empty(), "{at:?}"); +} + +#[test] +fn a_click_on_the_drop_shadow_of_a_symbols_art_does_not_select_the_instance() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + shadow(&mut s, a, 40.0); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let inst = id_of(&run(&mut s, "symbol.new", json!({"name": "Shadowed"}))); + assert_ne!(pixel(&s, 100, 50), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 100.0, 50.0).is_empty()); + assert_eq!(click(&mut s, 50.0, 50.0), [inst]); +} + +#[test] +fn a_click_on_the_drop_shadow_of_an_image_outside_its_frame_does_not_select_it() { + let mut s = session(); + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + // The frame lies from x 50 to 80 and the shadow from 90 to 120. + shadow(&mut s, im, 40.0); + assert_ne!(pixel(&s, 105, 65), WHITE); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 105.0, 65.0).is_empty()); + assert_eq!(click(&mut s, 65.0, 65.0), [im]); +} + +#[test] +fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + // Shift-click on the shadow over B adds B and keeps A. + run(&mut s, "select.set", json!({"ids": [a.0]})); + let shift = Mods { shift: true, ..Mods::default() }; + let mut sel = press(&mut s, "selection", (110.0, 50.0), (110.0, 50.0), shift); + sel.sort_by_key(|n| n.0); + let mut both = vec![a, b]; + both.sort_by_key(|n| n.0); + assert_eq!(sel, both); + // Direct Selection takes B through the shadow, and nothing over the canvas. + run(&mut s, "select.none", json!({})); + let sel = press(&mut s, "directSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()); + assert!(sel.contains(&b) && !sel.contains(&a), "{sel:?}"); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "directSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty()); + // With A selected, the pointer over its shadow is the plain arrow, and over A the move pointer. + run(&mut s, "select.set", json!({"ids": [a.0]})); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move); + assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow); + assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow); +} + +#[test] +fn a_drag_from_the_drop_shadow_of_a_selected_object_does_not_move_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let before = bounds(&s, a); + // From the shadow over the canvas: a marquee that touches nothing. + assert!(press(&mut s, "selection", (92.0, 50.0), (96.0, 60.0), Mods::default()).is_empty()); + assert_eq!(bounds(&s, a), before); + // From the shadow over B: B moves, A stays. + run(&mut s, "select.set", json!({"ids": [a.0]})); + let b_before = bounds(&s, b); + assert_eq!(press(&mut s, "selection", (110.0, 50.0), (110.0, 60.0), Mods::default()), [b]); + assert_eq!(bounds(&s, a), before); + assert!((bounds(&s, b).y0 - b_before.y0 - 10.0).abs() < 1e-6, "{:?}", bounds(&s, b)); +} + +#[test] +fn a_marquee_that_touches_only_a_drop_shadow_does_not_select_its_object() { + let mut s = session(); + let (_, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "selection", (85.0, 40.0), (95.0, 60.0), Mods::default()).is_empty()); + // From above B, over B and the shadow: B only. + assert_eq!(press(&mut s, "selection", (105.0, 5.0), (115.0, 30.0), Mods::default()), [b]); +} + +/// The selection after a drag with `tool` from `from` to `to`. +fn marquee(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)) -> vectorcraft_doc::Selection { + press(s, tool, from, to, Mods::default()); + s.doc().unwrap().selection.clone() +} + +/// The point of anchor `(si, ai)` of path `id`. +fn anchor_point(s: &Session, id: NodeId, (si, ai): vectorcraft_doc::AnchorRef) -> Point { + let path = s.doc().unwrap().doc.node(id).and_then(|n| n.path_data()).unwrap(); + path.anchors().find(|(s, i, _)| (*s, *i) == (si, ai)).map(|(.., a)| a.p).unwrap() +} + +/// The anchors a marquee or a click picked on `id`, as points. +fn picked_points(s: &Session, id: NodeId) -> Vec { + let refs: Vec<_> = s.doc().unwrap().selection.partial(id).into_iter().flatten().copied().collect(); + refs.into_iter().map(|r| anchor_point(s, id, r)).collect() +} + +/// The anchors the tool marks as hovered. +fn anchor_marks(s: &mut Session) -> Vec { + s.overlays(ViewInfo::default()) + .into_iter() + .filter_map(|o| if let vectorcraft_tools::Overlay::Anchor { p, .. } = o { Some(p) } else { None }) + .collect() +} + +fn hover(s: &mut Session, x: f64, y: f64) -> Cursor { + let v = ViewInfo::default(); + s.pointer(&PointerEvent::new(PointerKind::Move, x, y), v).unwrap(); + s.cursor(Point::new(x, y), Mods::default(), v) +} + +#[test] +fn a_direct_selection_marquee_leaves_out_a_drop_shadow() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + let (a_before, b_before) = (bounds(&s, a), bounds(&s, b)); + assert_ne!(pixel(&s, 90, 50), WHITE); + run(&mut s, "select.none", json!({})); + // Over the shadow alone: no object, no anchor, no segment. + let sel = marquee(&mut s, "directSelection", (85.0, 40.0), (95.0, 60.0)); + assert!(sel.objects.is_empty() && sel.anchors.is_empty() && sel.segments.is_empty(), "{sel:?}"); + // Over the shadow and B's upper left corner: that anchor of B, and nothing of A. + let sel = marquee(&mut s, "directSelection", (90.0, 5.0), (105.0, 30.0)); + assert_eq!(sel.objects, [b]); + assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); + // Across B's top edge under the shadow, with neither of its anchors inside: that segment. + run(&mut s, "select.none", json!({})); + assert_ne!(pixel(&s, 112, 25), BLUE); + let sel = marquee(&mut s, "directSelection", (110.0, 5.0), (115.0, 30.0)); + assert_eq!(sel.objects, [b]); + assert!(sel.segments.contains_key(&b) && !sel.segments.contains_key(&a), "{sel:?}"); + assert_eq!((bounds(&s, a), bounds(&s, b)), (a_before, b_before)); +} + +#[test] +fn direct_selection_hover_leaves_out_a_drop_shadow_and_marks_the_anchor_under_it() { + let mut s = session(); + let (_, b) = shadow_over_b(&mut s); + // B's upper left corner lies under the shadow. + assert_ne!(pixel(&s, 101, 21), BLUE); + run(&mut s, "select.none", json!({})); + s.select_tool("directSelection", ViewInfo::default()).unwrap(); + for (x, y) in [(90.0, 50.0), (110.0, 50.0)] { + assert_eq!(hover(&mut s, x, y), Cursor::ArrowHollow, "({x}, {y})"); + assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})"); + } + assert_eq!(hover(&mut s, 101.0, 21.0), Cursor::DirectAnchor); + assert_eq!(anchor_marks(&mut s), [Point::new(100.0, 20.0)]); + // A press there picks that anchor of B. + assert_eq!(press(&mut s, "directSelection", (101.0, 21.0), (101.0, 21.0), Mods::default()), [b]); + assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); +} + +#[test] +fn a_group_selection_click_on_a_drop_shadow_selects_the_object_under_it() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]); + assert!(press(&mut s, "groupSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty()); + assert_eq!(press(&mut s, "groupSelection", (50.0, 50.0), (50.0, 50.0), Mods::default()), [a]); +} + +#[test] +fn group_selection_clicks_on_a_drop_shadow_climb_the_groups_of_the_object_under_it() { + let mut s = session(); + // B and C in one group, A and D in another above it, and A's shadow over B. + let b = rect(&mut s, 100.0, 20.0, 60.0, 60.0, "#0000ff"); + let c = rect(&mut s, 170.0, 20.0, 20.0, 20.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + let gb = id_of(&run(&mut s, "object.group", json!({}))); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000"); + let d = rect(&mut s, 20.0, 120.0, 20.0, 20.0, "#ff0000"); + run(&mut s, "select.set", json!({"ids": [a.0, d.0]})); + let ga = id_of(&run(&mut s, "object.group", json!({}))); + shadow(&mut s, a, 40.0); + assert_ne!(pixel(&s, 110, 50), BLUE); + assert_ne!(pixel(&s, 90, 50), WHITE); + run(&mut s, "select.none", json!({})); + let click = |s: &mut Session, x, y| { + let mut sel = press(s, "groupSelection", (x, y), (x, y), Mods::default()); + sel.sort_by_key(|n| n.0); + sel + }; + assert_eq!(click(&mut s, 110.0, 50.0), [b]); + let mut both = vec![b, gb]; + both.sort_by_key(|n| n.0); + assert_eq!(click(&mut s, 110.0, 50.0), both); + // With A selected, a click on its shadow over the canvas does not add A's group. + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(click(&mut s, 90.0, 50.0).is_empty()); + // On A itself the second click adds it. + assert_eq!(click(&mut s, 50.0, 50.0), [a]); + let mut both = vec![a, ga]; + both.sort_by_key(|n| n.0); + assert_eq!(click(&mut s, 50.0, 50.0), both); +} + +#[test] +fn a_group_selection_marquee_leaves_out_a_drop_shadow() { + let mut s = session(); + let (a, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0)); + assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}"); + // Over the shadow and B's upper left corner: that anchor of B. + let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0)); + assert_eq!(sel.objects, [b]); + assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]); + // With E, a marquee around B that crosses A's shadow selects B whole, and not A. + run(&mut s, "select.none", json!({})); + let v = ViewInfo::default(); + s.select_tool("groupSelection", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 95.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 50.0), v).unwrap(); + s.tool_key(vectorcraft_tools::ToolKey::Letter('e'), Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 165.0, 90.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 165.0, 90.0), v).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.objects, [b]); + assert!(sel.partial(b).is_none() && sel.partial(a).is_none(), "{sel:?}"); +} + +#[test] +fn group_selection_hover_over_a_drop_shadow_marks_nothing() { + let mut s = session(); + let (_, b) = shadow_over_b(&mut s); + run(&mut s, "select.none", json!({})); + s.select_tool("groupSelection", ViewInfo::default()).unwrap(); + for (x, y) in [(90.0, 50.0), (110.0, 50.0), (101.0, 21.0)] { + assert_eq!(hover(&mut s, x, y), Cursor::GroupSelection, "({x}, {y})"); + assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})"); + } + assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]); +} diff --git a/crates/engine/src/tests/slices.rs b/crates/engine/src/tests/slices.rs index 87d0088d97..79b2cbe662 100644 --- a/crates/engine/src/tests/slices.rs +++ b/crates/engine/src/tests/slices.rs @@ -93,7 +93,7 @@ fn too_many_guide_pieces_are_refused() { let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); for i in 1..3000 { for vertical in [true, false] { - doc.guides.push(vectorcraft_doc::Guide::new(vertical, f64::from(i) * 0.1)); + doc.add_ruler_guide(&vectorcraft_doc::Guide::new(vertical, f64::from(i) * 0.1)); } } assert!(s.execute("object.slice.fromGuides", &json!({})).unwrap_err().to_string().contains("more than")); @@ -440,9 +440,9 @@ fn a_canceled_undo_scope_leaves_locked_or_hidden_slices_deselected() { /// Select slice `id` and the first ruler guide together, through [`Session::select`]. fn pick_slice_and_guide(s: &mut Session, id: u64) { - s.select(|_, sel| { + s.select(|d, sel| { sel.slices = vec![NodeId(id)]; - sel.guides = vec![0]; + sel.guides = d.ruler_guides().first().and_then(|g| g.id).into_iter().collect(); }) .unwrap(); } diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 5124fb4502..fd8f2c7e24 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -44,6 +44,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -64,6 +65,10 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"})); let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); + let textures = run(&mut s, "graphicStyle.library", json!({"library": "textures"})); + let texture_names: Vec<&str> = textures["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + let expected = ["Fine Grain", "Canvas Weave", "Burlap Sack", "Cracked Glaze", "Mosaic Floor", "Quilted Squares", "Leaded Glass", "Damp Paper"]; + assert_eq!(texture_names, expected); let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]})); assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow"))); @@ -82,6 +87,87 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() { + let mut s = session(); + let list = run(&mut s, "graphicStyle.libraries", json!({})); + let libs = list["libraries"].as_array().unwrap(); + let at = libs.iter().position(|l| l["id"] == "painted-sketched").expect("listed"); + assert_eq!((libs[at]["name"].as_str(), libs[at]["count"].as_u64()), (Some("Painted and Sketched"), Some(7))); + assert_eq!(libs[at - 1]["id"], "textures"); + let g = run(&mut s, "graphicStyle.library", json!({"library": "Painted and Sketched"})); + let listed: Vec<(&str, &str, Vec<&str>)> = + g["styles"].as_array().unwrap().iter().map(|x| (x["name"].as_str().unwrap(), x["fill"].as_str().unwrap(), names(&x["effects"]))).collect(); + let want = [ + ("Washed Blue", "#8ab9c9", "artistic.watercolor"), + ("Bristle Ochre", "#c4975a", "artistic.dryBrush"), + ("Pastel Heather", "#a78ca5", "artistic.roughPastels"), + ("Charcoal Shade", "#666666", "sketch.charcoal"), + ("Ink Contour", "#d9e2df", "brushStrokes.inkOutlines"), + ("Wet Ink", "#637b85", "brushStrokes.sumiE"), + ("Fine Pen", "#d8d4c6", "sketch.graphicPen"), + ]; + assert_eq!(listed, want.iter().map(|&(n, f, e)| (n, f, vec![e])).collect::>()); + // Every setting of each effect is given, with the catalog's key and kind of value. + let (_, lib) = cmd::stylelib::library(&s, "painted-sketched").unwrap(); + for st in &lib.styles { + let e = &st.appearance.effects[0]; + let defaults = vectorcraft_render::effects::effect_info(&e.id).unwrap().defaults; + let (set, all) = (e.params.as_object().unwrap(), defaults.as_object().unwrap()); + let keys = |m: &serde_json::Map| m.keys().cloned().collect::>(); + assert_eq!(keys(set), keys(all), "{}", st.name); + for (k, v) in set { + let kind = |v: &Value| (v.is_number(), v.is_string(), v.is_boolean()); + assert_eq!(kind(v), kind(&all[k]), "{} / {k}", st.name); + } + } + let strokes: Vec<(&str, f64)> = + lib.styles.iter().filter(|g| g.appearance.stroke_paint() != Paint::None).map(|g| (g.name.as_str(), g.appearance.stroke_width())).collect(); + assert_eq!(strokes, [("Bristle Ochre", 1.0), ("Ink Contour", 1.0)]); + + // Each one adds and applies to a rectangle in one undo step. + let mut ids = vec![]; + for (i, (name, fill, effect)) in want.iter().enumerate() { + let id = rect(&mut s, 10.0 + 25.0 * i as f64, 20.0, 20.0, 30.0); + let before = undo_len(&s); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": name, "apply": true, "ids": [id.0]})); + assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![*name], Some(*name))); + assert_eq!(undo_len(&s), before + 1, "{name}"); + let node = doc(&s).node(id).unwrap(); + assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex(fill).unwrap()), "{name}"); + assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), [*effect]); + assert_eq!(node.appearance.effects[0].params, lib.style(name).unwrap().appearance.effects[0].params, "{name}"); + ids.push((id, *name)); + } + // Adding one again reuses it: no new style, no undo step. + let before = (undo_len(&s), doc(&s).graphic_styles.len()); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink"})); + assert_eq!((names(&r["added"]), names(&r["existing"])), (vec![], vec!["Wet Ink"])); + assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before); + // An unknown style or library changes nothing. + assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-sketched", "names": ["Wet Ink", "Nope"]})).is_err()); + assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-and-sketched", "name": "Wet Ink"})).is_err()); + assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before); + + // Saved and opened again, the styles keep their effects and the rectangles stay linked to them. + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + run(&mut s, "document.open", json!({"name": "painted.vectorcraft", "dataBase64": b64})); + for (id, name) in &ids { + let d = doc(&s); + let style = d.graphic_style(name).unwrap(); + assert!(style.same_look(lib.style(name).unwrap()), "{name}"); + let node = d.node(*id).unwrap(); + assert_eq!((node.extras().graphic_style, &node.appearance.effects), (Some(style.id), &style.appearance.effects), "{name}"); + } + + // With nothing selected, `apply` only adds; empty `names` adds the whole library in order. + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Fine Pen", "apply": true})); + assert!(r.get("applied").is_none() && doc(&s).graphic_style("Fine Pen").is_some()); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "names": []})); + assert_eq!((names(&r["added"]), names(&r["existing"])), (want[..6].iter().map(|w| w.0).collect::>(), vec!["Fine Pen"])); +} + #[test] fn add_dedupes_names_as_one_undo_step() { let mut s = session(); @@ -167,6 +253,53 @@ fn add_with_null_ids_applies_to_selection() { assert_eq!(doc(&s).node(id).unwrap().extras().graphic_style, Some(style.id)); } +#[test] +fn textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open() { + let mut s = session(); + let (_, lib) = cmd::stylelib::library(&s, "textures").unwrap(); + let mut ids = vec![]; + for (i, g) in lib.styles.iter().enumerate() { + let id = rect(&mut s, (i % 4) as f64 * 50.0, (i / 4) as f64 * 50.0, 40.0, 40.0); + let before = undo_len(&s); + let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "textures", "name": g.name, "apply": true, "ids": [id.0]})); + assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![g.name.as_str()], Some(g.name.as_str()))); + assert_eq!(undo_len(&s), before + 1, "{}: added and applied as one step", g.name); + ids.push(id); + } + let effects = |s: &Session| -> Vec> { + ids.iter().map(|id| doc(s).node(*id).unwrap().appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect()).collect() + }; + let applied = effects(&s); + let effect_ids: Vec> = applied.iter().map(|fx| fx.iter().map(|(id, _)| id.as_str()).collect()).collect(); + assert_eq!( + effect_ids, + [ + ["texture.grain"], + ["texture.texturizer"], + ["texture.texturizer"], + ["texture.craquelure"], + ["texture.mosaicTiles"], + ["texture.patchwork"], + ["texture.stainedGlass"], + ["sketch.waterPaper"], + ] + ); + assert_eq!(applied[1][0].1["texture"], "canvas"); + assert_eq!(applied[3][0].1["crackSpacing"], 12.0); + for (fx, g) in applied.iter().zip(&lib.styles) { + let want: Vec<(String, Value)> = g.appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect(); + assert_eq!(fx, &want, "{} applies the library's params", g.name); + } + let b64 = run(&mut s, "document.serialize", json!({"format": "vectorcraft"}))["dataBase64"].as_str().unwrap().to_string(); + run(&mut s, "document.open", json!({"name": "textures.vectorcraft", "dataBase64": b64})); + assert_eq!(effects(&s), applied, "the params survive a save and open"); + for g in &lib.styles { + let saved = doc(&s).graphic_style(&g.name).unwrap(); + assert!(saved.same_look(g), "{} keeps its look", g.name); + assert!(ids.iter().any(|id| doc(&s).node(*id).unwrap().extras().graphic_style == Some(saved.id)), "{} stays linked", g.name); + } +} + /// A document with pattern `name` (a dot) and its swatch. fn add_pattern(s: &mut Session, name: &str, radius: f64) { s.edit("Pattern", |d, _| { diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 3ffb2ed615..6f77b58971 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{GraphicStyle, Knockout, Node}; +use vectorcraft_doc::{GraphicStyle, Knockout, Node, Shared}; use crate::*; @@ -202,6 +202,77 @@ fn redefine_leaves_unlinked_and_edited_objects_alone() { assert!(s.execute("graphicStyle.redefine", &json!({"id": c.0})).is_err()); } +/// Applying a style to several objects gives them one shared copy of its appearance; editing one +/// object gives that one its own, and the saved file is the same as with a copy for each. +#[test] +fn applying_a_style_shares_one_appearance() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "appearance.clear", json!({})); + run(&mut s, "paint.setFill", json!({"color": "#00ff00"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "effect.apply", json!({"effect": "distort.roughen"})); + run(&mut s, "graphicStyle.new", json!({"name": "Rough"})); + let rough = style(&s, "Rough"); + let ids = [rect(&mut s, 100.0), rect(&mut s, 200.0), rect(&mut s, 300.0)]; + let [b, c, d] = ids; + run(&mut s, "graphicStyle.apply", json!({"name": "Rough", "ids": [b.0, c.0, d.0]})); + let shared = |s: &Session, x: NodeId, y: NodeId| Shared::ptr_eq(&node(s, x).appearance, &node(s, y).appearance); + assert!(shared(&s, b, c) && shared(&s, c, d), "one appearance for every object"); + for id in ids { + assert_eq!(node(&s, id).appearance, rough.appearance); + assert_eq!(node(&s, id).extras().graphic_style, Some(rough.id)); + } + // The saved file is the same as one where each object has its own copy. + let doc = s.doc().unwrap().doc.clone(); + let mut copies = (*doc).clone(); + for id in ids { + let n = copies.node_mut(id).unwrap(); + n.appearance = Shared::new((*n.appearance).clone()); + } + assert!(!Shared::ptr_eq(&copies.node(b).unwrap().appearance, &copies.node(c).unwrap().appearance)); + for pretty in [false, true] { + assert_eq!(vectorcraft_format::save(&doc, pretty), vectorcraft_format::save(&copies, pretty)); + } + + // Editing one object leaves the others and the style as they were. + set_fill(&mut s, b, "#ff0000"); + assert!(!shared(&s, b, c) && shared(&s, c, d)); + assert_eq!(fill(&s, b), Paint::solid(Color::from_hex("#ff0000").unwrap())); + assert_eq!(node(&s, c).appearance, rough.appearance); + assert_eq!(style(&s, "Rough"), rough); + assert_eq!(linked(&mut s, "Rough"), vec![a.0, c.0, d.0]); + + // Undo and redo restore the values, still shared. + run(&mut s, "edit.undo", json!({})); + assert!(shared(&s, b, c) && node(&s, b).appearance == rough.appearance); + run(&mut s, "edit.undo", json!({})); + for id in ids { + assert_ne!(node(&s, id).appearance, rough.appearance); + assert_eq!(node(&s, id).extras().graphic_style, None); + } + run(&mut s, "edit.redo", json!({})); + assert!(shared(&s, b, c) && shared(&s, c, d) && node(&s, d).appearance == rough.appearance); +} + +/// Redefine Graphic Style gives the objects still linked one shared copy of the new appearance. +#[test] +fn redefine_shares_one_appearance() { + let mut s = session(); + let (a, b, c) = linked_three(&mut s); + let d = rect(&mut s, 300.0); + run(&mut s, "graphicStyle.apply", json!({"name": "S"})); + set_fill(&mut s, d, "#00ff00"); + set_fill(&mut s, a, "#0000ff"); + run(&mut s, "graphicStyle.redefine", json!({"name": "S", "id": a.0})); + let (nb, nc) = (node(&s, b), node(&s, c)); + assert!(Shared::ptr_eq(&nb.appearance, &nc.appearance)); + assert_eq!(nb.appearance, style(&s, "S").appearance); + // The edited object keeps its own look. + assert_eq!(fill(&s, d), Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance)); +} + #[test] fn deleting_a_style_unlinks_and_renaming_keeps_links() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index cbf595d6d8..af059e5e33 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -355,6 +355,35 @@ fn new_color_group_from_artwork_lists_each_color_once_with_free_names() { assert_eq!(*doc(&s), before); } +/// New Color Group takes the named solid swatches in the order given. A name listed twice takes +/// the next swatch of that name, found ungrouped first and then in each colour group, and the +/// lists the swatches leave keep their order. Gradients and names no swatch has take nothing. +#[test] +fn new_color_group_takes_named_swatches_in_order_from_every_list() { + let mut s = session(); + let twin = vectorcraft_color::Swatch { name: "Red".into(), paint: Paint::solid(Color::rgb(0.5, 0.0, 0.0)), global: false, spot: false }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) + .swatch_groups + .iter_mut() + .find(|g| g.name == "Brights") + .unwrap() + .swatches + .push(twin.clone()); + let red = doc(&s).swatch("Red").cloned().unwrap(); + let mut ungrouped = names(&s, None); + let mut brights = names(&s, Some("Brights")); + let r = run(&mut s, "swatch.newGroup", json!({"name": "Mine", "swatches": ["Red", "Orange", "Sunset", "Red", "Missing", "Bright Red"]})); + assert_eq!(r["swatches"], json!(["Red", "Orange", "Red", "Bright Red"])); + let group = &doc(&s).swatch_groups.iter().find(|g| g.name == "Mine").unwrap().swatches; + assert_eq!(group[0], red); + assert_eq!(group[2], twin); + ungrouped.retain(|n| n != "Red" && n != "Orange"); + brights.retain(|n| n != "Red" && n != "Bright Red"); + assert_eq!(names(&s, None), ungrouped); + assert_eq!(names(&s, Some("Brights")), brights); + assert!(doc(&s).swatch("Sunset").is_some()); +} + #[test] fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 3ecb5e68e1..695a2962a5 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -638,6 +638,77 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi assert_eq!(doc(&s).swatch("Red").unwrap().paint.color().map(|c| c.to_hex()), Some("#00ff00".into())); } +#[test] +fn organic_fades_add_with_their_method_midpoints_and_opacities_in_rgb_and_cmyk() { + let lib = vectorcraft_color::libraries::builtin_library("organic-fades").unwrap(); + for mode in ["rgb", "cmyk"] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100, "colorMode": mode})); + let list = run(&mut s, "swatch.library.list", json!({})); + let row = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "organic-fades").unwrap().clone(); + assert_eq!( + (row["name"].as_str(), row["category"].as_str(), row["count"].as_u64()), + (Some("Organic Fades"), Some("gradients"), Some(lib.len() as u64)) + ); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let r = run(&mut s, "swatch.library.add", json!({"library": "organic-fades", "names": ["Petal", "Dew"], "apply": "fill"})); + assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Petal", "Dew"]), json!("Petal")), "{mode}"); + for name in ["Petal", "Dew"] { + // The swatch comes as the library has it: stops (colors as given, opacities, midpoints) and method. + let Paint::Gradient(added) = &doc(&s).swatch(name).unwrap().paint else { panic!("{name} is a gradient") }; + let Paint::Gradient(want) = &lib.swatch(name).unwrap().paint else { panic!("{name} is a gradient") }; + assert_eq!(added.gradient, want.gradient, "{mode} {name}"); + assert_eq!(added.gradient.method, vectorcraft_color::GradientMethod::Perceptual); + assert!(added.gradient.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{mode} {name}: the stops stay RGB"); + assert!(added.gradient.stops.iter().any(|st| st.opacity < 1.0 && (st.midpoint - 0.5).abs() > 0.02), "{mode} {name}"); + } + // The fill takes the fade's method, opacities and midpoints. + let fill = doc(&s).node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().appearance.fill_paint(); + let (Paint::Gradient(fill), Paint::Gradient(want)) = (fill, &lib.swatch("Petal").unwrap().paint) else { panic!("a gradient fill") }; + assert_eq!(fill.gradient.method, want.gradient.method, "{mode}"); + let shape = |g: &vectorcraft_color::Gradient| g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect::>(); + assert_eq!(shape(&fill.gradient), shape(&want.gradient), "{mode}"); + } +} + +#[test] +fn holographic_glows_add_whole_in_rgb_and_cmyk_as_one_undo_step() { + let lib = vectorcraft_color::libraries::builtin_library("holographic").unwrap(); + let Paint::Gradient(want) = &lib.swatch("Mint Halo").unwrap().paint else { panic!("Mint Halo is a gradient") }; + for mode in ["rgb", "cmyk"] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100, "colorMode": mode})); + let list = run(&mut s, "swatch.library.list", json!({})); + let row = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "holographic").unwrap().clone(); + assert_eq!((row["name"].as_str(), row["category"].as_str(), row["count"].as_u64()), (Some("Holographic"), Some("gradients"), Some(14))); + let got = run(&mut s, "swatch.library.get", json!({"library": "holographic"})); + assert!(got.to_string().contains("Mint Halo"), "{mode}: get lists Mint Halo"); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let node = vectorcraft_doc::NodeId(id.as_u64().unwrap()); + let before = undo_len(&s); + let r = run(&mut s, "swatch.library.add", json!({"library": "holographic", "names": ["Mint Halo"], "apply": "fill"})); + assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Mint Halo"]), json!("Mint Halo")), "{mode}"); + assert_eq!(undo_len(&s), before + 1, "{mode}: added and applied as one step"); + // The swatch comes as the library has it: kind, stops (RGB colors, opacities, midpoints) and method. + let Paint::Gradient(added) = &doc(&s).swatch("Mint Halo").unwrap().paint else { panic!("{mode}: a gradient swatch") }; + assert_eq!(added.gradient, want.gradient, "{mode}"); + assert!(added.gradient.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{mode}: the stops stay RGB"); + assert_eq!(added.gradient.stops.last().map(|st| st.opacity), Some(0.0), "{mode}: clear at the edge"); + let Paint::Gradient(fill) = doc(&s).node(node).unwrap().appearance.fill_paint() else { panic!("{mode}: a gradient fill") }; + assert_eq!((fill.gradient.kind, fill.gradient.method), (want.gradient.kind, want.gradient.method), "{mode}"); + assert_eq!(fill.gradient.stops, want.gradient.stops, "{mode}"); + run(&mut s, "edit.undo", json!({})); + assert!(doc(&s).swatch("Mint Halo").is_none(), "{mode}: undo removes the add"); + assert!(!matches!(doc(&s).node(node).unwrap().appearance.fill_paint(), Paint::Gradient(_)), "{mode}: and the fill"); + // A document swatch already named Mint Halo stays; the glow comes in under a number. + run(&mut s, "swatch.new", json!({"name": "Mint Halo", "color": "#123456"})); + let r = run(&mut s, "swatch.library.add", json!({"library": "holographic", "names": ["Mint Halo"]})); + assert_eq!(r["added"], json!(["Mint Halo 2"]), "{mode}"); + assert!(doc(&s).swatch("Mint Halo").unwrap().paint.color().is_some(), "{mode}: the document's swatch is kept"); + assert!(matches!(&doc(&s).swatch("Mint Halo 2").unwrap().paint, Paint::Gradient(g) if g.gradient == want.gradient)); + } +} + #[test] fn pattern_libraries_bring_their_patterns_and_add_each_once() { let mut s = session(); @@ -765,6 +836,39 @@ 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)); } +/// Grit Textures is listed after Geometric Patterns. One of its patterns comes in with its swatch +/// once, as one undo step that also takes both away, and both stay after a save and reopen. +#[test] +fn a_grit_texture_adds_once_undoes_and_saves() { + let mut s = session(); + let list = run(&mut s, "swatch.library.list", json!({})); + let ids: Vec<&str> = + list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect(); + assert_eq!(ids, ["geometric-patterns", "grit-textures"]); + let got = run(&mut s, "swatch.library.get", json!({"library": "Grit Textures"})); + let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Fine Grain", "Coarse Grit", "Sand", "Speckle", "Stipple", "Scratches", "Sparse Flecks", "Dense Flecks"]); + let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count()); + let empty = counts(doc(&s)); + let undo = undo_len(&s); + let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]})); + assert_eq!(r["added"], json!(["Stipple"])); + assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1)); + let def = doc(&s).pattern("Stipple").expect("the pattern comes with its swatch").clone(); + assert!(def.art.len() >= 144, "{} marks", def.art.len()); + assert!(matches!(doc(&s).swatch("Stipple").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Stipple")); + let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]})); + assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Stipple"]))); + assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(counts(doc(&s)), empty); + assert!(doc(&s).pattern("Stipple").is_none() && doc(&s).swatch("Stipple").is_none()); + run(&mut s, "edit.redo", json!({})); + let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap(); + assert_eq!(back.pattern("Stipple"), Some(&def)); + assert_eq!(back.swatch("Stipple").map(|w| &w.paint), doc(&s).swatch("Stipple").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] diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index febc220296..54591c4658 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() { let mut s = Session::new(); let list = run(&mut s, "symbol.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert_eq!(libs.len(), 4, "{libs:?}"); + assert_eq!(libs.len(), 5, "{libs:?}"); assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn"))); assert_eq!( (libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()), @@ -98,6 +98,10 @@ fn the_builtin_library_is_original_art_generated_in_code() { (libs[3]["id"].as_str(), libs[3]["name"].as_str(), libs[3]["category"].as_str()), (Some("inventory-icons"), Some("Inventory Icons"), Some("builtIn")) ); + assert_eq!( + (libs[4]["id"].as_str(), libs[4]["name"].as_str(), libs[4]["category"].as_str()), + (Some("skill-icons"), Some("Skill Icons"), Some("builtIn")) + ); let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"})); let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]); @@ -159,6 +163,32 @@ fn inventory_icons_symbols_add_without_nine_slice() { )); } +#[test] +fn skill_icons_symbols_add_without_nine_slice() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "skill-icons"})); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Attack", "Defend", "Heal", "Buff", "Ult"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "skill-icons", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}), + ); + assert_eq!(r["added"], json!([name])); + placed.push(r["placed"].as_u64().unwrap()); + } + let d = doc(&s); + for name in &names { + assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides"); + } + assert!(matches!( + d.node(NodeId(placed[0])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Attack" + )); +} + #[test] fn map_markers_symbols_add_without_nine_slice() { let mut s = session(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index f49a88c80b..abb39c0d96 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -475,6 +475,7 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() { ("text.setFormat", json!({"ids": [id.0], "hyphenate": "false"}), "hyphenate"), ("text.setFormat", json!({"ids": [id.0], "hyphenateCapitalized": 0}), "hyphenateCapitalized"), ("text.setFormat", json!({"ids": [id.0], "romanHangingPunctuation": "true"}), "romanHangingPunctuation"), + ("text.setFormat", json!({"ids": [id.0], "koreanLineBreakAnywhere": 1}), "koreanLineBreakAnywhere"), ("text.getRange", json!({"id": id.0, "effective": "true"}), "effective"), ("type.opticalMarginAlignment", json!({"on": "true"}), "on"), ("type.systemLayout", json!({"on": "true"}), "on"), @@ -1016,7 +1017,7 @@ fn dropped_type_press_restores_the_original_text_and_selection() { let a = at(&s, first); click(&mut s, a.x + 0.1, a.y); assert!(s.tool_wants_text()); - s.select(|_, selection| selection.guides.push(0)).unwrap(); + s.select(|d, selection| selection.guides.extend(d.ruler_guides().first().and_then(|g| g.id))).unwrap(); let before = s.doc().unwrap().selection.clone(); let b = at(&s, second); s.pointer(&PointerEvent::new(PointerKind::Down, b.x + 0.1, b.y), v).unwrap(); @@ -2467,6 +2468,124 @@ fn convert_area_point_keeps_text_in_place_for_every_alignment() { } } +/// Each line's first glyph in the document, and the line count. +fn line_starts_doc(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.iter().map(|l| t.xf * lay.glyphs[l.glyph_start].origin).collect() +} + +/// Tracked type converted between point and area type stays where it is, however it is aligned, +/// as often as it goes round: an aligned line leaves the tracking after its last character out +/// of its width, and the frame Convert To Area Type makes ends where the lines are aligned, with +/// room for that tracking (line breaking counts it). Lines area type wraps at a space or after a +/// hyphen keep their place as the paragraphs Convert To Point Type makes of them (words without a +/// kerning pair across the wrap, which a new paragraph doesn't keep). +#[test] +fn converting_tracked_type_between_point_and_area_keeps_it_in_place() { + for j in ["left", "center", "right"] { + for tracking in [200.0, 1000.0, -100.0] { + let mut s = session(); + let id = + NodeId(s.execute("text.create", &json!({"x": 50, "y": 100, "text": "Wave\nWaves", "size": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": tracking})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap(); + let before = line_starts_doc(&obj(&s, id)); + assert_eq!(before.len(), 2); + for round in 0..2 { + s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap(); + let area = line_starts_doc(&obj(&s, id)); + assert_eq!(area.len(), 2, "{j} {tracking}: no rewrap"); + for (a, b) in area.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "{j} {tracking}, round {round}, area: {before:?} → {area:?}"); + } + s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap(); + let point = line_starts_doc(&obj(&s, id)); + for (a, b) in point.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "{j} {tracking}, round {round}, point: {before:?} → {point:?}"); + } + } + } + // Area type wrapped at a space and after a hyphen, to point type. + for text in ["Wave Wave Wave", "Mode-Mode-Mode"] { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 50, "y": 100, "text": text, "size": 20, "area": {"width": 90, "height": 200}})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": 200})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap(); + let before = line_starts_doc(&obj(&s, id)); + assert!(before.len() > 1, "{text}: it wraps"); + s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap(); + let after = line_starts_doc(&obj(&s, id)); + assert_eq!(after.len(), before.len(), "{text}"); + for (a, b) in after.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "{j} {text}: {before:?} → {after:?}"); + } + } + } +} + +/// Horizontal and vertical type keep every line where it is when converted from point to area +/// type and back, and from area to point type and back, however the lines are aligned. Vertical +/// lines run down their columns, and each next column sits to the left of the one before it. +#[test] +fn converting_vertical_type_between_point_and_area_keeps_it_in_place() { + for vertical in [false, true] { + for j in ["left", "center", "right"] { + for text in ["Wave", "Wave\nWaves"] { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 300, "y": 40, "text": text, "size": 12, "vertical": vertical})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap(); + let before = line_starts_doc(&obj(&s, id)); + assert_eq!(before.len(), text.lines().count()); + if vertical && before.len() > 1 { + assert!(before[1].x < before[0].x, "{j}: the second column is to the left: {before:?}"); + } + for round in 0..2 { + s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap(); + let t = obj(&s, id); + assert!(matches!(t.kind, TextKind::Area { .. })); + let area = line_starts_doc(&t); + assert_eq!(area.len(), before.len(), "vertical {vertical}, {j}, {text:?}: no rewrap"); + for (a, b) in area.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, {text:?}, round {round}, area: {before:?} → {area:?}"); + } + s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap(); + let t = obj(&s, id); + assert!(matches!(t.kind, TextKind::Point)); + let point = line_starts_doc(&t); + for (a, b) in point.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, {text:?}, round {round}, point: {before:?} → {point:?}"); + } + } + } + // Area type to point type and back. + let mut s = session(); + let r = s + .execute( + "text.create", + &json!({"x": 300, "y": 40, "text": "Wave\nWaves", "size": 12, "vertical": vertical, "area": {"width": 120, "height": 120}}), + ) + .unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setStyle", &json!({"ids": [id.0], "justify": j})).unwrap(); + let before = line_starts_doc(&obj(&s, id)); + assert_eq!(before.len(), 2); + s.execute("type.convertToPointType", &json!({"ids": [id.0]})).unwrap(); + let point = line_starts_doc(&obj(&s, id)); + for (a, b) in point.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, from area, point: {before:?} → {point:?}"); + } + s.execute("type.convertToAreaType", &json!({"ids": [id.0]})).unwrap(); + let area = line_starts_doc(&obj(&s, id)); + assert_eq!(area.len(), 2); + for (a, b) in area.iter().zip(&before) { + assert!((*a - *b).hypot() < 0.01, "vertical {vertical}, {j}, from area, area again: {before:?} → {area:?}"); + } + } + } +} + #[test] fn convert_area_to_point_keeps_a_deeper_list_item_in_place() { let mut s = session(); diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs new file mode 100644 index 0000000000..a8961f3c46 --- /dev/null +++ b/crates/engine/src/tests/turn_direction.rs @@ -0,0 +1,125 @@ +//! Every angle or rotation a command takes says which way it turns (#6340): creation commands turn +//! clockwise and most edits counter-clockwise, so a client can't guess. + +use crate::cmd::params::{is_key, object_body, split_top}; +use crate::command_specs; + +/// Params that are angles but not a turn, with why. +const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), + ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), + ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), + ("addon.shapes.box3d", "angleY", "a tilt out of the page: the description says which side turns away"), + ("addon.shapes.configure", "angleX", "a tilt out of the page: the description says which side turns away"), + ("addon.shapes.configure", "angleY", "a tilt out of the page: the description says which side turns away"), + ("object.path.simplify", "cornerAngle", "the angle a corner's sides meet at"), + ("perspective.grid.define", "angle", "the viewing angle, 0 to 90°"), +]; + +/// A param name that is an angle or a turn. +fn is_turn(key: &str) -> bool { + let k = key.to_ascii_lowercase(); + k.ends_with("angle") || k.ends_with("angles") || k.starts_with("angle") || ["rotation", "rotate", "piestart", "pieend"].contains(&k.as_str()) +} + +/// The bodies of the `{…}` objects in `text` that are not inside another one. +fn objects_in(text: &str) -> Vec<&str> { + let mut out = vec![]; + let mut rest = text; + while let Some(i) = rest.find('{') { + let Ok((body, after)) = object_body(&rest[i..]) else { break }; + out.push(body); + rest = after; + } + out +} + +/// `(key, what the description says about it)` for each key the object `body` names, and for the +/// keys of the objects inside it. A key given without a note (`a?, b?: degrees`) shares the note of +/// the next key that has one. +fn keys_and_notes(body: &str, out: &mut Vec<(String, String)>) { + let mut items: Vec<(&str, String)> = vec![]; + for entry in split_top(body, ',').into_iter().map(str::trim).filter(|e| !e.is_empty() && !e.starts_with('…')) { + for (i, alternative) in split_top(entry, '|').into_iter().enumerate() { + let head = alternative.split([':', '=', '(']).next().unwrap_or_default(); + let note = alternative.get(head.len()..).unwrap_or_default(); + let name = head.trim().trim_end_matches('?').trim_end(); + let a_key = is_key(name) && (i == 0 || head.trim_end().ends_with('?') || note.starts_with(':')); + match items.last_mut() { + Some((_, last)) if !a_key => last.push_str(alternative), + _ if a_key => items.push((name, note.to_string())), + _ => {} + } + } + } + for (i, (key, note)) in items.iter().enumerate() { + let shared = items.get(i..).unwrap_or_default().iter().map(|(_, n)| n.trim()).find(|n| !n.is_empty()).unwrap_or_default(); + out.push((key.to_string(), shared.to_string())); + for inner in objects_in(note) { + keys_and_notes(inner, out); + } + } +} + +/// The turn params of description `doc` whose note doesn't say which way they turn. +fn undirected(doc: &str) -> Vec { + let mut found = vec![]; + let mut next = Some(doc); + // `{…} or {…}`: each object the command takes. + while let Some(text) = next { + let Ok((body, rest)) = object_body(text) else { break }; + keys_and_notes(body, &mut found); + next = rest.trim_start().strip_prefix("or ").or_else(|| rest.trim_start().strip_prefix("| ")).filter(|r| r.starts_with('{')); + } + found.into_iter().filter(|(k, note)| is_turn(k) && !note.to_ascii_lowercase().contains("clockwise")).map(|(k, _)| k).collect() +} + +#[test] +fn a_note_is_found_for_each_key() { + assert_eq!(undirected("{angle: deg (counter-clockwise), origin?}"), Vec::::new()); + assert_eq!(undirected("{x, rotation?: deg} → {rotation}"), ["rotation"]); + // A shared note, an alternative, a nested object, and the object after `or`. + assert_eq!(undirected("{inAngle?, outAngle?: degrees counter-clockwise, size?: pt}"), Vec::::new()); + assert_eq!(undirected("{startAngle?, endAngle?, center?: [x,y] | hSpacing? | angle?}"), ["startAngle", "endAngle", "angle"]); + assert_eq!(undirected("{gradient?: {kind?: linear|radial, angle?: deg}, id?}"), ["angle"]); + assert_eq!(undirected("{id} or {ids, rotate?: deg}"), ["rotate"]); + // Not a turn by its name, or a value rather than a key. + assert_eq!(undirected("{autoRotate: true, orientation?: portrait|landscape, mode?: rotation|scale}"), Vec::::new()); +} + +/// Each command param that is an angle or a rotation says in its description which way it turns +/// (clockwise or counter-clockwise), unless [`NOT_A_TURN`] says why it isn't a turn. +#[test] +fn every_turn_param_says_which_way_it_turns() { + let mut missing = vec![]; + for c in command_specs() { + for key in undirected(c.params) { + if !NOT_A_TURN.iter().any(|(id, k, _)| *id == c.id && *k == key) { + missing.push(format!("{}: {key}", c.id)); + } + } + } + assert!(missing.is_empty(), "{} params don't say whether they turn clockwise or counter-clockwise:\n{}", missing.len(), missing.join("\n")); + let stale: Vec<_> = NOT_A_TURN + .iter() + .filter(|(id, key, _)| !command_specs().iter().any(|c| c.id == *id && keys_named(c.params).iter().any(|k| k == key))) + .collect(); + assert!(stale.is_empty(), "NOT_A_TURN names params no command takes: {stale:?}"); +} + +fn keys_named(doc: &str) -> Vec { + let mut found = vec![]; + if let Ok((body, _)) = object_body(doc) { + keys_and_notes(body, &mut found); + } + found.into_iter().map(|(k, _)| k).collect() +} + +/// Turn notes the key walk above doesn't reach: a numeric reflection axis and the Scatter brush's +/// `rotation [a, b]` range, whose head isn't a plain key. +#[test] +fn turns_outside_plain_keys_say_which_way() { + let doc = |id: &str| command_specs().iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default(); + assert!(doc("object.reflect").contains("|deg (the mirror line, counter-clockwise from horizontal"), "object.reflect's numeric axis"); + assert!(doc("brush.options").contains("rotation [a, b] −180..180° (counter-clockwise)"), "the Scatter brush's rotation"); +} diff --git a/crates/engine/src/tests/warp_images.rs b/crates/engine/src/tests/warp_images.rs new file mode 100644 index 0000000000..47175fc866 --- /dev/null +++ b/crates/engine/src/tests/warp_images.rs @@ -0,0 +1,293 @@ +//! Effect › Warp on placed images: the pixels bend with the frame, in the canvas and in exports. + +use serde_json::{Value, json}; +use vectorcraft_doc::live::{WarpNet, WarpStyle, uses_net, warp_version}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +/// The box of the image [`quarters`] places. +const FRAME: Rect = Rect::new(100.0, 100.0, 180.0, 180.0); + +/// The color of the quarter of the image [`quarters`] places that holds (u, v) of its box: red top +/// left, green top right, blue bottom left, yellow bottom right. +fn quarter(u: f64, v: f64) -> [u8; 3] { + match (u < 0.5, v < 0.5) { + (true, true) => [255, 0, 0], + (false, true) => [0, 255, 0], + (true, false) => [0, 0, 255], + (false, false) => [255, 255, 0], + } +} + +/// A selected embedded 40×40 px image filling [`FRAME`], each quarter one color ([`quarter`]). +fn quarters(s: &mut Session) -> NodeId { + let img = image::RgbaImage::from_fn(40, 40, |x, y| { + let [r, g, b] = quarter(x as f64 / 40.0, y as f64 / 40.0); + image::Rgba([r, g, b, 255]) + }); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.edit("Place", |d, sel| { + d.images.insert("quarters".into(), vectorcraft_doc::ImageBlob::png(png)); + let id = d.alloc_id(); + let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0); + let im = vectorcraft_doc::ImageObject { + key: "quarters".into(), + width: 40, + height: 40, + xf, + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +/// Where an Arc warp bending `bend` % takes the point at (u, v) of [`FRAME`]. +fn arced(bend: f64, u: f64, v: f64) -> Point { + let net = WarpNet::new(WarpStyle::Arc, bend / 100.0, 0.0, 0.0, FRAME.width(), FRAME.height(), false); + FRAME.origin() + net.at(u, v).to_vec2() +} + +/// Points of the image's box: near each quarter's middle and on both sides of the line between +/// the top and bottom quarters, where a warp that moves the pixels up or down changes the color. +const SAMPLES: [(f64, f64); 10] = + [(0.2, 0.2), (0.8, 0.2), (0.2, 0.8), (0.8, 0.8), (0.4, 0.4), (0.6, 0.4), (0.4, 0.6), (0.6, 0.6), (0.3, 0.62), (0.7, 0.62)]; + +/// The document drawn over (0, 0)–(400, 400) at one pixel a point, on white. +fn drawn(s: &Session) -> vectorcraft_render::Rendered { + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 400.0, 400.0), 1.0, true) +} + +/// The sample points whose color in `img` at `at(u, v)` is not the image's color at (u, v). +fn wrong(img: &vectorcraft_render::Rendered, at: &dyn Fn(f64, f64) -> Point) -> Vec<(f64, f64, [u8; 4])> { + SAMPLES + .iter() + .filter_map(|&(u, v)| { + let p = at(u, v); + let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32); + let want = quarter(u, v); + let near = (0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40); + (!near).then_some((u, v, px)) + }) + .collect() +} + +/// `quarters` with Effect › Warp › Arc at 50 %: the warp the effect holds, checked to be the +/// Bézier patch [`arced`] follows. +fn arc_image(s: &mut Session) -> NodeId { + let id = quarters(s); + s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let e = &n.appearance.effects[0]; + assert!(warp_version(&e.params["version"]).is_some_and(uses_net), "{}", e.params); + id +} + +fn decoded(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap() +} + +#[test] +fn an_images_pixels_bend_with_effect_warp() { + let mut s = session(); + let id = arc_image(&mut s); + // The arc lifts the middle of the image: the line between the quarters rises there. + assert!(arced(50.0, 0.5, 0.6).y < FRAME.y0 + 0.5 * FRAME.height(), "{:?}", arced(50.0, 0.5, 0.6)); + let bent = drawn(&s); + assert_eq!(wrong(&bent, &|u, v| arced(50.0, u, v)), vec![], "each pixel is drawn where the warp takes it"); + // Drawn as pieces of the one image, each placed by the warp. + let d = &s.doc().unwrap().doc; + let art = vectorcraft_render::effects::reshape(Some(d), d.node(id).unwrap(), None).unwrap(); + let mut pieces = 0; + art.walk(&mut |c| pieces += matches!(c.kind, NodeKind::Image(_)) as usize); + assert!(pieces >= 100, "{pieces} pieces"); + // Removing the warp draws the image as it was, in one undo step. + let steps = s.doc().unwrap().history.undo.len(); + s.execute("effect.remove", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let plain = |u: f64, v: f64| Point::new(FRAME.x0 + u * FRAME.width(), FRAME.y0 + v * FRAME.height()); + assert_eq!(wrong(&drawn(&s), &plain), vec![]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![], "undo brings the bend back"); +} + +/// `out`, an export of [`arc_image`]'s document named `name`, opened again: it draws the image +/// bent. +fn opens_bent(name: &str, out: &Value) { + let mut back = session(); + back.execute("document.open", &json!({"name": name, "dataBase64": out["dataBase64"]})).unwrap(); + assert_eq!(wrong(&drawn(&back), &|u, v| arced(50.0, u, v)), vec![], "{name}"); +} + +#[test] +fn a_warped_image_keeps_its_bend_in_svg() { + let mut s = session(); + arc_image(&mut s); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let text = String::from_utf8(decoded(&svg)).unwrap(); + assert_eq!(text.matches("= 100, "{images} pieces"); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]); + s.execute("edit.undo", &json!({})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.len() == 1); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]); +} + +/// A selected embedded grayscale 40×40 px image filling [`FRAME`], black above white, colorized +/// red by its fill color: red above, nothing below. +fn red_on_clear(s: &mut Session) -> NodeId { + let img = image::GrayImage::from_fn(40, 40, |_, y| image::Luma([if y < 20 { 0 } else { 255 }])); + let mut png = vec![]; + image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let id = s + .edit("Place", |d, sel| { + d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png)); + let id = d.alloc_id(); + let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0); + let im = vectorcraft_doc::ImageObject { + key: "gray".into(), + width: 40, + height: 40, + xf, + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap(); + id +} + +#[test] +fn a_colorized_image_keeps_its_color_when_warped() { + let mut s = session(); + red_on_clear(&mut s); + s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap(); + let img = drawn(&s); + let (red, white) = ([255u8, 0, 0], [255u8, 255, 255]); + for (u, v, want) in [(0.5, 0.35, red), (0.2, 0.2, red), (0.5, 0.65, white), (0.8, 0.8, white)] { + let p = arced(50.0, u, v); + let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32); + assert!((0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40), "({u}, {v}) at {p:?}: {px:?}"); + } +} + +#[test] +fn a_warp_on_a_group_bends_the_image_in_it() { + let mut s = session(); + let im = quarters(&mut s); + // A group of the image and a line below it as wide as the image: the group's box is the image's. + let line = s.execute("shape.line", &json!({"x1": FRAME.x0, "y1": FRAME.y1, "x2": FRAME.x1, "y2": FRAME.y1})).unwrap(); + let line = NodeId(line["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [im.0, line.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap(); + assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]); +} diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 4c837c300f..6aa324aa90 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -221,9 +221,9 @@ fn new_width_point_adjust_adjoining_uses_sampled_widths() { let (mut s, id) = line_session(); let original = vec![(0.0, 9.0, 9.0), (0.25, 1.0, 0.0), (0.75, 3.0, 0.0), (1.0, 7.0, 7.0)]; s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": original})).unwrap(); - // At t=0.5 the old left side is where the profile's curve is there (#5714) and the right - // side is 0pt. Indexed editing of that sampled point is the existing convention: scale the - // nonzero side, add from zero. + // At t=0.5 the old left side is where the profile's curve is there and the right side is + // 0pt. Indexed editing of that sampled point is the existing convention: scale the nonzero + // side, add from zero. let sampled = vectorcraft_doc::WidthProfile { points: original }.at(0.5).0; let index = if indexed { Some(set(&mut s, json!({"id": id.0, "t": 0.5, "left": sampled * 5.0, "right": 0}))) } else { None }; set(&mut s, json!({"id": id.0, "index": index, "t": 0.5, "left": 20, "right": 5, "adjustAdjoining": true})); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index b096922e9a..e9aa3c5329 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -766,7 +766,7 @@ fn stroke_width(s: &Session, id: NodeId) -> f64 { } fn guide_positions(s: &Session) -> Vec { - s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect() + s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect() } /// Scale Artwork with Artboard (#602): `artboard.setProps {scaleArt}` takes the art fully inside the diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index b222f32107..9bc450f937 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -751,6 +751,27 @@ impl Session { self.apply_actions(acts).map(drop) } + /// The rulers' origin dragged out of their corner, whatever the tool, with the pointer at `p` in + /// document space (none off the canvas): where it goes, snapped as a drawn point is + /// ([`vectorcraft_tools::rulerguide::OriginDrag`]), the targets gathered on the drag's first + /// call. It changes nothing: the caller sets the origin where the button is released + /// (`document.setRulerOrigin`) and ends the drag ([`Session::end_ruler_origin_drag`]). + pub fn ruler_origin_drag(&mut self, p: Option, view: ViewInfo) -> Option { + let drag = match self.ruler_origin.take() { + Some(d) => Some(d), + None => self.with_tool_cx(view, |_, cx| Some(vectorcraft_tools::rulerguide::OriginDrag::new(cx))), + }; + let Some(mut drag) = drag else { return p }; + let at = self.with_tool_cx(view, |_, cx| drag.pointer(cx, p)); + self.ruler_origin = Some(drag); + at + } + + /// The drag of the rulers' origin ended, released or cancelled: its guides go. + pub fn end_ruler_origin_drag(&mut self) { + self.ruler_origin = None; + } + /// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the /// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event. pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result> { @@ -1112,6 +1133,9 @@ impl Session { v.extend(self.with_tool_cx(view, |_, cx| g.overlays(cx))); self.ruler_guide = Some(g); } + if let Some(d) = &self.ruler_origin { + v.extend(d.overlays()); + } let deferred_preview = self.unapplied_interaction_preview(); if let Some(d) = self.active() { let w = self.prefs.perspective_widget; diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 947cf559d0..b41eb112f4 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -674,6 +674,8 @@ fn structured_junk() { ("object.blend.options", json!({"spacing": "distance", "value": -1e308, "orientation": 5})), ("object.blend.options", json!({"ramp": 1e308, "colorShift": -1e308, "easingType": [1]})), ("object.blend.make", json!({"ids": [1, 2], "ramp": f64::NAN, "colorShift": [1]})), + ("object.blend.make", json!({"ids": [1, 2], "createSpine": ["never"], "easingType": "easeIn"})), + ("object.blend.createSpine", json!({"mode": 1e308})), ("object.blend.spine.moveAnchor", json!({"id": 2, "anchor": u64::MAX, "x": 1e308, "y": -1e308, "handle": "sideways"})), ("object.blend.spine.addAnchor", json!({"id": u64::MAX, "x": 0, "y": 0})), ("object.blend.spine.reshapeSegment", json!({"id": 2, "segment": u64::MAX, "t": f64::NAN, "dx": 1e308, "dy": -1e308})), @@ -807,6 +809,12 @@ fn structured_junk() { ("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"]})), + // Cutting Tools add-on: Stencil Bridges. + ("addon.cutting.bridges", json!({"width": 0.01, "count": 16, "direction": "shortest", "keepOriginal": true})), + ("addon.cutting.bridges", json!({"width": 1000, "count": 1, "direction": "horizontal", "keepOriginal": false})), + ("addon.cutting.bridges", json!({"width": "3 mm", "direction": "vertical"})), + ("addon.cutting.bridges", json!({"width": f64::MAX, "count": 1e308, "direction": ["vertical"], "keepOriginal": "no"})), + ("addon.cutting.bridges", json!({"width": -1, "count": -3, "direction": "diagonal", "keepOriginal": 1e308})), ("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/font_folder.rs b/crates/engine/tests/font_folder.rs index b58e79fc17..11d152fb4d 100644 --- a/crates/engine/tests/font_folder.rs +++ b/crates/engine/tests/font_folder.rs @@ -71,6 +71,13 @@ fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() { assert!(st.revision > revision && !st.is_dirty()); assert_eq!(s.execute("text.missingFonts", &json!({})).unwrap()["count"], 0); + // A caller whose read roots hold the file but not the Fonts folder: the file is kept, and the + // reply names the copy by its file name only, without the folder. + let downloads = vectorcraft_engine::file_access::AutomationRoots::new(&[&root.join("Downloads")], &[]).unwrap(); + let r = vectorcraft_engine::file_access::confine(downloads.as_ref(), || s.execute("text.addFontFiles", &json!({"files": [file]}))).unwrap(); + assert_eq!((&r["folder"], &r["kept"]), (&Value::Null, &json!([{"from": file, "to": "Findme 2.otf"}])), "{r}"); + assert!(!r.to_string().contains("App Fonts"), "{r}"); + // The same file again is kept, not copied a third time. let r = s.execute("text.addFontFiles", &json!({"files": [file]})).unwrap(); assert_eq!((r["copied"].clone(), r["kept"].clone()), (json!([]), json!([{"from": file, "to": fonts.join("Findme 2.otf")}])), "{r}"); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index f729ed394c..ac98db8e9c 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1,4 +1,4 @@ -//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF and DXF input, +//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF, DXF and HP-GL input, //! mutated raster images (Photoshop documents and JPEG XL images among them) placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`), flattener preset //! (`.vcflattener`) and export preset (`.vcexportpresets`) libraries, shortcut sets and action sets other apps save as text (`.kys`, `.aia`), and native files (compressed, damaged, saved for older versions), //! must load as an error or as a document that then renders and exports, without a panic; nor may @@ -1807,6 +1807,27 @@ proptest! { }); prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); } + + /// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden + /// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count. + /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.) + #[test] + fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::()), 0..12)) { + let (name, mut bytes) = raster_samples().swap_remove(which); + let len = bytes.len(); + for (at, b) in edits { + if let Some(x) = bytes.get_mut(at % len) { + *x = b; + } + } + bytes.truncate((cut % (len + 1)).max(8)); + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true}); + let _ = no_panic(s.execute("document.open", &p)); + }); + prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); + } } /// 1-bit TIFFs compressed with CCITT Group 3: modified Huffman (Compression 2) in three strips, T.4 @@ -2661,7 +2682,10 @@ fn arb_ps_token() -> impl Strategy { // Local VM restored: dictionary changes undone, saves restored twice. "/a 1 def save /a 2 def", "restore", "save dup restore", "1 dict save exch /k 1 put", "cachestatus", "/n 0 def save /n n 1 add store", // Executable strings and keys other than names (PLRM 3rd ed., `cvx`, `load`). - "(>>) cvx", "(1 2 add) cvx exec", "(x) cvx dup exec", "0 load", "1 { } def", "(mark) cvx cvlit" + "(>>) cvx", "(1 2 add) cvx exec", "(x) cvx dup exec", "0 load", "1 { } def", "(mark) cvx cvlit", + // CID-keyed fonts found by name over predefined CMaps, horizontal and vertical. + "/Ryumin-Light-90ms-RKSJ-H", "/Ryumin-Light-EUC-V", "/Ryumin-Light-H", "/GBT-EUC-H", "/KSCms-UHC-V", "/UniJIS-UTF16-V", + "[/Ryumin-Light]", "composefont", "<93fa967b8540fd0d41>", "" ]) .prop_map(str::to_string), ] @@ -2914,6 +2938,73 @@ proptest! { } } +// ---------- HP-GL plot files: opened and placed ---------- + +/// A plot file with every kind of instruction the reader plays, printer escapes around it. +const HPGL_SAMPLE: &[u8] = b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\r\n\x1bE\x1b%0BIN;BP1,\"job\";CO\"sample\";NP16;PC9,10,20,30;CR0,100,0,100,0,100;\ +SP1;PW0.5;WU0;LA1,4,2,4,3,7;LT2,5,1;PA0,0;PD1000,0,1000,1000;PU;LT;PR;PD-500,0,0,-500;PA2000,2000;CI300,5;AA2000,2500,120;AR0,100,-90;\ +AT2500,2500,3000,2000;RT100,100,200,0;BZ0,100,100,100,100,0;BR10,10,20,10,30,0;UL3,1,2,1;LT-3,2;EA3000,3000;ER100,-100;FT10,40;RA3500,3500;\ +RR200,200;WG400,30,120;EW-400,0,360;PM0;PD4000,4000,4500,4000,4500,4500;PM1;PU4100,4100;PD4200,4100,4200,4200;PM2;FP1;EP;FT3,10,45;FP;\ +IP0,0,10160,7620;SC0,100,0,100,1,20,80;PU10,10;PD20,20;SC0,10,0,10,2;PD5,5;SC;RO90;PD100,100;RO;IR10,10,90,90;IW0,0,5000,5000;\ +DT*,1;LBlabel*SMx;PA0,0;SM;PE:\xc1<=\xbf\xc0\xc2\xc2;LB\x03PG;\x1b%0A\x1b*r1A\x1b*b4W\x01\x02\x03\x04\x1b*rC\x1b%1BPD1,1;\x1b%-12345X"; + +/// The sample the mutations start from opens as a plot with art. +#[test] +fn the_hpgl_sample_opens() { + let l = vectorcraft_engine::cmd::fileio::load("x.plt", HPGL_SAMPLE).unwrap(); + assert_eq!(l.format.id, "hpgl"); + let mut paths = 0; + l.doc.walk(|n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert!(paths > 15, "{paths} paths, warnings {:?}", l.warnings); +} + +/// A random instruction: a mnemonic the reader plays (or one it doesn't) with hostile numbers. +fn arb_hpgl_instruction() -> impl Strategy { + let op = prop::sample::select(vec![ + "IN", "DF", "PU", "PD", "PA", "PR", "SP", "PW", "WU", "NP", "PC", "CR", "LT", "UL", "LA", "FT", "SC", "IP", "IR", "RO", "CI", "AA", "AR", + "AT", "RT", "BZ", "BR", "EA", "ER", "RA", "RR", "EW", "WG", "PM", "FP", "EP", "LB", "DT", "SM", "CO", "PG", "IW", "PE", "ZZ", + ]); + let number = prop_oneof![ + Just("0".to_string()), + Just("-1".to_string()), + (-3000i32..3000).prop_map(|v| v.to_string()), + Just("99999999999999999999999".to_string()), + Just("0.000001".to_string()), + Just("32767".to_string()), + Just("-32768".to_string()), + Just("360".to_string()), + ]; + (op, prop::collection::vec(number, 0..8)).prop_map(|(o, n)| format!("{o}{};", n.join(","))) +} + +proptest! { + #![proptest_config(config())] + + #[test] + fn random_hpgl_instructions_never_panic(instructions in prop::collection::vec(arb_hpgl_instruction(), 0..40)) { + let bytes = format!("IN;SP1;{}", instructions.concat()).into_bytes(); + survive_metafile("HP-GL instructions", "x.plt", &bytes)?; + } + + #[test] + fn mutated_hpgl_files_never_panic(cut in 0usize..1200, edits in prop::collection::vec((0usize..1200, any::()), 0..16)) { + let mut bytes = HPGL_SAMPLE.to_vec(); + let n = bytes.len(); + for &(at, b) in &edits { + bytes[at % n] = b; + } + bytes.truncate(cut.max(4)); + survive_metafile("mutated HP-GL", "x.plt", &bytes)?; + } + + #[test] + fn hpgl_garbage_never_panics(bytes in prop::collection::vec(any::(), 0..400)) { + let mut b = b"IN;SP1;PD".to_vec(); + b.extend(bytes); + survive_metafile("HP-GL garbage", "x.hpgl", &b)?; + } +} + // ---------- print presets files ---------- /// Import print presets from `data`, then lay out (and print, when short) the rich document with diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index 511fbb25fe..6a0338ee17 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -568,12 +568,14 @@ fn artistic_text_aligns_its_lines_within_the_longest() { assert!(matches!(t.kind, TextKind::Point)); let lines = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines; let (wide, mid) = (&lines[0], &lines[1]); - let w = wide.x1 - wide.x0; + // Each line as wide as it is aligned: without the tracking after its last character. + let width = |l: &vectorcraft_text::LineInfo| l.x1 - l.trailing - l.x0; + let w = width(wide); assert!(w > 0.0); // The block stays where the first paragraph's alignment puts it on the anchor. let start = [0.0, -0.5, -1.0][first as usize] * w; assert!((wide.x0 - start).abs() < 1e-6, "{first}/{second}: {} vs {start}", wide.x0); - let expected = wide.x0 + (w - (mid.x1 - mid.x0)) * at; + let expected = wide.x0 + (w - width(mid)) * at; assert!((mid.x0 - expected).abs() < 1e-6, "{first}/{second}: {} vs {expected}", mid.x0); // Each paragraph keeps its own alignment. use vectorcraft_doc::text::Justify; diff --git a/crates/engine/tests/it/beyond_canvas.rs b/crates/engine/tests/it/beyond_canvas.rs index 9dee868d54..6ac31398f6 100644 --- a/crates/engine/tests/it/beyond_canvas.rs +++ b/crates/engine/tests/it/beyond_canvas.rs @@ -51,7 +51,7 @@ fn an_artboard_a_guide_or_a_ruler_origin_beyond_the_canvas_no_longer_blocks_edit v["document"]["ruler_origin"] = json!([1e17, 0.0]); let (s, warnings) = open_and_move(&v, "setup"); let d = &s.doc().unwrap().doc; - assert_eq!((d.artboards.len(), d.guides.len(), d.ruler_origin.x), (1, 1, 0.0)); + assert_eq!((d.artboards.len(), d.ruler_guides().len(), d.ruler_origin.x), (1, 1, 0.0)); assert!(warnings.to_string().contains("1 artboard, 1 guide beyond the canvas"), "{warnings}"); assert!(warnings.to_string().contains("ruler origin"), "{warnings}"); } diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index 655c719965..a50c70c18d 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -177,12 +177,12 @@ fn clear_guides_and_empty_explicit_targets_keep_their_separate_behavior() { s.execute("edit.clear", &json!({"ids": []})).unwrap(); assert_eq!(s.active().unwrap().history.undo.len(), history); assert_eq!(s.active().unwrap().selection, selection); - assert_eq!(s.active().unwrap().doc.guides.len(), 1); + assert_eq!(s.active().unwrap().doc.ruler_guides().len(), 1); s.execute("edit.clear", &json!({})).unwrap(); - assert!(s.active().unwrap().doc.guides.is_empty()); + assert!(s.active().unwrap().doc.ruler_guides().is_empty()); assert!(s.active().unwrap().doc.node(a).is_some()); s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.guides.len(), 1); + assert_eq!(s.active().unwrap().doc.ruler_guides().len(), 1); } #[test] diff --git a/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs b/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs index 6c84c66b33..db8696a10f 100644 --- a/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs +++ b/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs @@ -1,8 +1,8 @@ //! The JavaScript parser's lexer (`vectorcraft-js`) and the script checker's (`vectorcraft-scriptcheck`) //! read the same scripts the same way: both crates stand alone, so each has its own lexer, and these //! tests run both over one set of scripts and fail on any disagreement about the lines a script has, -//! its preprocessor lines, and where a string, comment or regular expression that is never closed -//! starts. The scripts stay inside ECMAScript 3, the language both read (no XML literals, which +//! its preprocessor lines, where a string, comment or regular expression that is never closed +//! starts, and the characters a name may hold. The scripts stay inside ECMAScript 3, the language both read (no XML literals, which //! only the checker reads). use vectorcraft_js::{Options, TokenKind, parse, tokenize}; @@ -88,6 +88,56 @@ fn both_lexers_find_the_same_unclosed_token_on_the_same_line() { } } +/// Characters on both sides of the identifier rule: `Other_ID_Start`, `Other_ID_Continue`, connector +/// punctuation, marks, digits and letters of other scripts, a letter and a mark Unicode 17.0 +/// assigned, and a superscript digit, a `Pattern_Syntax` letter and punctuation that no name holds. +const NAME_CHARS: &[char] = &[ + '\u{AA}', '\u{B2}', '\u{B7}', '\u{D7}', '\u{300}', '\u{387}', '\u{660}', '\u{88F}', '\u{1369}', '\u{1885}', '\u{19DA}', '\u{1ACF}', '\u{200C}', + '\u{200D}', '\u{203F}', '\u{2040}', '\u{2118}', '\u{212E}', '\u{2160}', '\u{2E2F}', '\u{3005}', '\u{309B}', '\u{30FB}', '\u{FE33}', '\u{FF10}', + '\u{FF65}', +]; + +/// Whether the parser reads `src` as one identifier spelling `name`. +fn one_identifier(src: &str, name: &str) -> bool { + let want = TokenKind::Ident(name.to_string()); + tokenize(src, &js_options()).is_ok_and(|tokens| tokens.iter().filter(|t| t.kind != TokenKind::Eof).map(|t| &t.kind).eq([&want])) +} + +/// Whether the checker lists the member `app.` as `app.`. +fn checker_member(src: &str, name: &str) -> bool { + let report = check("script.jsx", format!("app.{src};\n").as_bytes(), None, &Limits::default()); + report.members.iter().any(|m| m.name == format!("app.{name}")) +} + +#[test] +fn both_lexers_take_the_same_characters_into_names() { + assert!(checker_member("a\u{2118}b", "a\u{2118}b") && one_identifier("a\u{2118}b", "a\u{2118}b")); + assert!(checker_member("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}") && one_identifier("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}")); + for &c in NAME_CHARS { + let escape = format!("\\u{:04X}", u32::from(c)); + let braced = format!("\\u{{{:X}}}", u32::from(c)); + for (src, name) in [ + (format!("a{c}b"), format!("a{c}b")), + (format!("{c}b"), format!("{c}b")), + (format!("a{escape}b"), format!("a{c}b")), + (format!("{escape}b"), format!("{c}b")), + (format!("a{braced}b"), format!("a{c}b")), + (format!("{braced}b"), format!("{c}b")), + ] { + assert_eq!(checker_member(&src, &name), one_identifier(&src, &name), "{src:?} (U+{:04X})", u32::from(c)); + } + } + // Braced escapes past U+FFFF and with leading zeros are read by both. + for (src, name) in [("\\u{1D49C}b", "\u{1D49C}b"), ("a\\u{0000000062}", "ab")] { + assert!(checker_member(src, name) && one_identifier(src, name), "{src:?}"); + } + // Out of range, a surrogate and an empty one: the parser reads no identifier, and the checker's + // name ends before the escape. + for src in ["a\\u{110000}", "a\\u{D800}", "a\\u{}"] { + assert!(checker_member(src, "a") && !one_identifier(src, "a"), "{src:?}"); + } +} + #[test] fn the_parser_reads_a_regexp_wherever_the_checker_does() { // Each `/` that divides has no second `/` after it on its line, so a lexer that read one as a diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 7f85e5acd3..9227ee199d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -27,6 +27,8 @@ mod param_keys; mod paste_many; mod pen_click_after_smooth; mod pen_endpoint_picking; +mod ruler_guide_nodes; +mod ruler_guide_perf; mod ruler_origin; mod selection_commands; mod stroke_visibility; diff --git a/crates/engine/tests/it/ruler_guide_nodes.rs b/crates/engine/tests/it/ruler_guide_nodes.rs new file mode 100644 index 0000000000..950da2f065 --- /dev/null +++ b/crates/engine/tests/it/ruler_guide_nodes.rs @@ -0,0 +1,450 @@ +//! Ruler guides held as nodes of a layer: commands that work on a layer's art leave them out and +//! keep them above the art. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{Node, NodeId, NodeKind}; +use vectorcraft_engine::Session; + +fn id(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()) +} + +/// A ruler guide added on top of `layer`'s contents. +fn guide(s: &mut Session, layer: NodeId, pos: f64) -> NodeId { + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos, artboard: None }); + d.insert(Some(layer), usize::MAX, g).unwrap() +} + +fn children(s: &Session, layer: NodeId) -> Vec { + s.doc().unwrap().doc.children(Some(layer)).unwrap().iter().map(|c| c.id).collect() +} + +/// A document with a layer holding two rectangles and two ruler guides: (layer, [art], [guides]). +fn session() -> (Session, NodeId, Vec, Vec) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + let art = vec![rect(&mut s, 10.0), rect(&mut s, 50.0)]; + let guides = vec![guide(&mut s, layer, 5.0), guide(&mut s, layer, 7.0)]; + (s, layer, art, guides) +} + +#[test] +fn layer_commands_keep_ruler_guides_above_the_art() { + // Send to Current Layer puts the object below the current layer's guides. + let (mut s, a, art, guides) = session(); + let b = id(&s.execute("layer.new", &json!({})).unwrap()); + let moved = rect(&mut s, 90.0); + s.execute("layer.setCurrent", &json!({"id": a.0})).unwrap(); + s.execute("select.set", &json!({"ids": [moved.0]})).unwrap(); + s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap(); + assert_eq!(children(&s, a), [art[0], art[1], moved, guides[0], guides[1]]); + // Already on top of the art: nothing changes and no undo step is added. + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + + // Moving a row on top of a layer's contents puts it below the guides. + let other = rect(&mut s, 130.0); + s.execute("layer.move", &json!({"id": other.0, "target": a.0})).unwrap(); + assert_eq!(children(&s, a), [art[0], art[1], moved, other, guides[0], guides[1]]); + + // Merging layers keeps every guide above the merged art. + let gb = guide(&mut s, b, 9.0); + let late = { + s.execute("layer.setCurrent", &json!({"id": b.0})).unwrap(); + rect(&mut s, 170.0) + }; + s.execute("layer.merge", &json!({"ids": [a.0, b.0]})).unwrap(); + let merged = children(&s, b); + let first_guide = merged.iter().position(|c| [guides[0], guides[1], gb].contains(c)).unwrap(); + assert_eq!(merged.len() - first_guide, 3, "{merged:?}"); + assert!(merged.contains(&late)); +} + +#[test] +fn release_and_clipping_leave_ruler_guides_alone() { + let (mut s, layer, art, guides) = session(); + // Make Clipping Mask clips by the top object, not by a guide above it. + assert_eq!(s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap()["clip"], json!(true)); + assert_eq!(children(&s, layer), [art[1], art[0], guides[0], guides[1]]); + s.execute("edit.undo", &json!({})).unwrap(); + + // Release to Layers makes layers of the art only, below the guides. + s.execute("layer.releaseToLayers", &json!({"id": layer.0})).unwrap(); + let ch = children(&s, layer); + assert_eq!(ch.len(), 4); + assert_eq!(ch[2..], [guides[0], guides[1]]); + let d = &s.doc().unwrap().doc; + assert!(ch[..2].iter().all(|c| d.node(*c).is_some_and(Node::is_layer))); +} + +#[test] +fn ruler_guides_are_not_art_to_select_paint_or_inspect() { + let (mut s, layer, art, guides) = session(); + // Target Contents selects the layer's objects only. + let out = s.execute("appearance.targetContents", &json!({"ids": [layer.0]})).unwrap(); + assert_eq!(out["ids"], json!([art[0].0, art[1].0])); + // Painting the layer paints its objects and leaves the guides with no appearance. + s.execute("paint.setFill", &json!({"ids": [layer.0], "color": "#ff0000"})).unwrap(); + let d = &s.doc().unwrap().doc; + for g in &guides { + assert_eq!(d.node(*g).unwrap().appearance, vectorcraft_doc::Appearance::default()); + } + // Document inspection lists the objects, not the guides. + assert_eq!(s.execute("document.find", &json!({"kind": "Guide"})).unwrap()["total"], json!(0)); + let layer_row = s.execute("document.inspect", &json!({"ids": [layer.0]})).unwrap(); + let listed = layer_row.to_string(); + assert!(guides.iter().all(|g| !listed.contains(&format!("\"id\":{}", g.0))), "{listed}"); + // Unlock All does not reach a locked guide. + Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(guides[0]).unwrap().locked = true; + s.execute("object.unlockAll", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(guides[0]).unwrap().locked); +} + +#[test] +fn flattening_a_sublayers_art_keeps_its_ruler_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + let sub = id(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let r = rect(&mut s, 10.0); + s.execute("transparency.set", &json!({"ids": [r.0], "opacity": 50})).unwrap(); + let g = guide(&mut s, sub, 5.0); + s.execute("object.flattenTransparency", &json!({"ids": [sub.0]})).unwrap(); + // The sublayer stands for its art: the art is flattened and the guide stays on top of it. + let d = &s.doc().unwrap().doc; + assert!(d.node(r).is_none(), "the art was flattened"); + assert!(d.node(g).is_some_and(Node::is_ruler_guide), "the guide is kept"); + assert_eq!(d.parent_of(g), Some(sub)); + assert_eq!(children(&s, sub).len(), 2); + assert_eq!(children(&s, sub).last(), Some(&g)); + assert_eq!(d.parent_of(sub), Some(layer)); +} + +#[test] +fn object_commands_refuse_a_ruler_guide_id() { + let (mut s, _, art, guides) = session(); + s.execute("select.set", &json!({"ids": [art[0].0]})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len()); + for (command, params) in [ + ("select.set", json!({"ids": [guides[0].0]})), + ("select.set", json!({"ids": [art[1].0, guides[1].0]})), + ("edit.clear", json!({"ids": [guides[0].0]})), + ("object.lock", json!({"ids": [guides[0].0]})), + ("object.move", json!({"ids": [guides[0].0], "dx": 5, "dy": 0})), + ("paint.setFill", json!({"ids": [guides[1].0], "color": "#ff0000"})), + ] { + let e = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(e.contains("is a ruler guide, not an object"), "{command}: {e}"); + let d = s.doc().unwrap(); + assert_eq!((&d.doc, &d.selection, d.history.undo.len()), (&before.0, &before.1, before.2), "{command} changed something"); + } + // A selection holding a guide id as an object loses it when pruned; the guide stays. + let d = &s.doc().unwrap().doc; + let mut sel = vectorcraft_doc::Selection { objects: vec![art[0], guides[0]], key: Some(guides[1]), ..Default::default() }; + sel.prune(d); + assert_eq!((sel.objects, sel.key), (vec![art[0]], None)); + assert!(d.node(guides[0]).is_some_and(Node::is_ruler_guide)); +} + +#[test] +fn a_ruler_guide_stays_directly_in_a_layer() { + let (mut s, layer, art, guides) = session(); + s.execute("select.set", &json!({"ids": [art[0].0, art[1].0]})).unwrap(); + let group = id(&s.execute("object.group", &json!({})).unwrap()); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + // Reorder refuses a group as a guide's parent, and the top level. + for parent in [json!(group.0), json!(null)] { + assert!(s.execute("node.move", &json!({"id": guides[0].0, "parent": parent, "index": 0})).is_err(), "{parent}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before.0, before.1)); + } + // So do the document's own insert and move. + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + assert!(d.move_node(guides[1], Some(group), 0).is_err()); + let loose = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None }); + assert!(d.insert(Some(group), 0, loose.clone()).is_err()); + assert!(d.insert(None, 0, loose.clone()).is_err()); + assert_eq!(d.ruler_guides().iter().filter_map(|g| g.id).collect::>(), guides); + assert_eq!(children(&s, layer), [group, guides[0], guides[1]]); + // Within its layer it still moves among the guides. + s.execute("node.move", &json!({"id": guides[1].0, "parent": layer.0, "index": 0})).unwrap(); + assert_eq!(children(&s, layer), [group, guides[1], guides[0]]); +} + +/// Arrange counts only a layer's art: the guides above it are no place to move to. +#[test] +fn arranging_counts_only_a_layers_art() { + let (mut s, layer, art, guides) = session(); + let top = rect(&mut s, 90.0); + assert_eq!(children(&s, layer), [art[0], art[1], top, guides[0], guides[1]]); + s.execute("select.set", &json!({"ids": [art[0].0, top.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + assert_eq!(children(&s, layer), [art[1], art[0], top, guides[0], guides[1]], "the selection keeps its order at the top of the art"); + // The topmost art brought to the front or forward: nothing changes and no undo step is added. + s.execute("select.set", &json!({"ids": [top.0]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for command in ["object.arrange.bringToFront", "object.arrange.bringForward"] { + s.execute(command, &json!({})).unwrap(); + assert_eq!(children(&s, layer), [art[1], art[0], top, guides[0], guides[1]], "{command}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{command}"); + } + s.execute("select.set", &json!({"ids": [art[1].0]})).unwrap(); + s.execute("object.arrange.bringForward", &json!({})).unwrap(); + assert_eq!(children(&s, layer), [art[0], art[1], top, guides[0], guides[1]]); +} + +/// A guide made while an opacity mask, a pattern or a symbol is edited goes on the temporary +/// editing layer, and stays in the document when editing ends; a save made during mask editing +/// keeps it. +#[test] +fn guides_made_while_editing_a_mask_a_pattern_or_a_symbol_stay() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 10.0); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let edit_layer = s.doc().unwrap().doc.mask_edit.expect("editing the mask").layer; + s.execute("guide.add", &json!({"vertical": true, "pos": 40})).unwrap(); + let made = s.doc().unwrap().doc.ruler_guides(); + assert_eq!(made.iter().map(|g| (g.layer, g.pos)).collect::>(), [(Some(edit_layer), 40.0)]); + let saved = s.doc().unwrap().doc.without_edit_modes().ruler_guides(); + assert_eq!(saved.iter().map(|g| (g.id, g.pos)).collect::>(), [(made[0].id, 40.0)], "a save keeps the guide"); + s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let kept = d.ruler_guides(); + assert_eq!(kept.iter().map(|g| (g.id, g.pos)).collect::>(), [(made[0].id, 40.0)]); + assert!(kept[0].layer.is_some_and(|l| l != edit_layer && d.node(l).is_some_and(Node::is_layer))); + + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 10.0); + s.execute("object.pattern.make", &json!({})).unwrap(); + let tile_layer = s.doc().unwrap().doc.pattern_edit.as_ref().expect("editing the pattern").layer; + s.execute("guide.add", &json!({"vertical": false, "pos": 25})).unwrap(); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].layer, Some(tile_layer)); + s.execute("object.pattern.done", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let kept = d.ruler_guides(); + assert_eq!(kept.iter().map(|g| g.pos).collect::>(), [25.0]); + assert!(kept[0].layer.is_some_and(|l| l != tile_layer && d.node(l).is_some_and(Node::is_layer))); + let tile = &d.patterns.last().expect("the new pattern").art; + assert!(tile.iter().all(|n| !n.is_ruler_guide()), "the guide is not part of the tile"); + + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 10.0); + let instance = id(&s.execute("symbol.new", &json!({"name": "Mark"})).unwrap()); + s.execute("symbol.edit", &json!({"ids": [instance.0]})).unwrap(); + let edit_layer = s.doc().unwrap().doc.symbol_edit.as_ref().expect("editing the symbol").layer; + s.execute("guide.add", &json!({"vertical": true, "pos": 15})).unwrap(); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].layer, Some(edit_layer)); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let kept = d.ruler_guides(); + assert_eq!(kept.iter().map(|g| g.pos).collect::>(), [15.0]); + assert!(kept[0].layer.is_some_and(|l| l != edit_layer && d.node(l).is_some_and(Node::is_layer))); + let art = &d.symbols.iter().find(|x| x.name == "Mark").expect("the symbol").art; + let mut in_symbol = false; + art.walk(&mut |n| in_symbol |= n.is_ruler_guide()); + assert!(!in_symbol, "the guide is not part of the symbol"); +} + +/// `bytes` without the lines that depend on when the file was written: the PDF dates, and the XMP +/// packet (one line, with its dates and IDs) and trailer `/ID`. +fn undated(bytes: &[u8]) -> Vec { + let stamps: [&[u8]; 5] = [b"CreationDate", b"ModDate", b"xmp:CreateDate", b"xmp:ModifyDate", b"/ID["]; + let dated = |line: &&[u8]| stamps.iter().any(|s| line.windows(s.len()).any(|w| w == *s)); + bytes.split(|b| *b == b'\n').filter(|l| !dated(l)).flat_map(|l| l.iter().copied().chain(*b"\n")).collect() +} + +/// The bytes of each export format (PDF without the embedded native document, which keeps the +/// guides, and without its dates), and the box Fit All in Window fits (the art and every artboard). +fn exports(s: &mut Session) -> (Vec<(String, Vec)>, Option) { + let files = [json!({"format": "svg"}), json!({"format": "pdf", "preserveEditing": false}), json!({"format": "png"}), json!({"format": "psd"})] + .iter() + .map(|p| { + let out = s.execute("document.export", p).unwrap(); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let format = p["format"].as_str().unwrap().to_string(); + let bytes = if format == "pdf" { undated(&bytes) } else { bytes }; + (format, bytes) + }) + .collect(); + let d = &s.doc().unwrap().doc; + let fit = d.art_bounds().map(|a| d.artboards.iter().fold(a, |r, ab| r.union(ab.rect))); + (files, fit) +} + +/// Ruler guides on a layer, on a sublayer and on an artboard change no export and not the box +/// Fit All in Window fits. +#[test] +fn exports_and_fit_all_are_the_same_with_ruler_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 150, "artboards": 2})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + rect(&mut s, 10.0); + let sub = id(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 30, "width": 40, "height": 30})).unwrap(); + let without = exports(&mut s); + assert_eq!(exports(&mut s), without, "the exports are repeatable"); + // Guides far outside the art too: they must not widen any box. + s.execute("guide.add", &json!({"vertical": true, "pos": -5000, "layer": layer.0})).unwrap(); + s.execute("guide.add", &json!({"vertical": false, "pos": 9000, "layer": sub.0})).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120, "artboard": 1})).unwrap(); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 3); + let with = exports(&mut s); + for ((format, a), (_, b)) in without.0.iter().zip(&with.0) { + assert!(a == b, "{format} export changed with ruler guides present"); + } + assert_eq!(with.1, without.1, "Fit All"); + // A PDF that preserves editing carries them in its native document, and opens with them. + let guides = s.doc().unwrap().doc.ruler_guides(); + let pdf = s.execute("document.export", &json!({"format": "pdf"})).unwrap()["dataBase64"].clone(); + s.execute("document.open", &json!({"name": "guides.pdf", "dataBase64": pdf})).unwrap(); + assert_eq!(s.doc().unwrap().doc.ruler_guides(), guides); +} + +/// One step of [`guide_commands_follow_a_list_model`]. +#[derive(Clone, Debug)] +enum GuideOp { + Add { vertical: bool, pos: u16, layer: usize }, + Remove(usize), + Copy(usize), + Paste, + SetCurrent(usize), + Undo, + Redo, +} + +fn guide_op() -> impl proptest::strategy::Strategy { + use proptest::prelude::*; + prop_oneof![ + 3 => (any::(), 0u16..400, 0usize..3).prop_map(|(vertical, pos, layer)| GuideOp::Add { vertical, pos, layer }), + 2 => (0usize..16).prop_map(GuideOp::Remove), + 1 => (0usize..16).prop_map(GuideOp::Copy), + 1 => Just(GuideOp::Paste), + 1 => (0usize..3).prop_map(GuideOp::SetCurrent), + 2 => Just(GuideOp::Undo), + 1 => Just(GuideOp::Redo), + ] +} + +/// A guide as `guide.list` reports it: (vertical, pos, layer). +type Line = (bool, f64, u64); + +fn listed(s: &mut Session) -> Vec { + let rows = s.execute("guide.list", &json!({})).unwrap(); + rows.as_array() + .unwrap() + .iter() + .enumerate() + .map(|(i, r)| { + assert_eq!(r["index"], json!(i)); + (r["vertical"].as_bool().unwrap(), r["pos"].as_f64().unwrap(), r["layer"].as_u64().unwrap()) + }) + .collect() +} + +/// Runs `ops` on a document with two layers and a sublayer, checking `guide.list` against a plain +/// list after every step: Add appends (a new guide takes the highest id), Remove takes the entry +/// out, Paste appends the copied guide on the current layer at the same place, and Undo and +/// Redo bring back the list as it was, the same indexes included. +fn run_guide_ops(ops: &[GuideOp]) -> Result<(), proptest::test_runner::TestCaseError> { + use proptest::prop_assert_eq; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let bottom = s.doc().unwrap().doc.layers[0].id; + let top = id(&s.execute("layer.new", &json!({})).unwrap()); + let sub = id(&s.execute("layer.newSublayer", &json!({"parent": bottom.0})).unwrap()); + let layers = [bottom, top, sub]; + s.execute("layer.setCurrent", &json!({"id": bottom.0})).unwrap(); + let mut current = bottom; + let mut model: Vec = vec![]; + let mut clip: Option<(bool, f64)> = None; + let (mut undo, mut redo): (Vec>, Vec>) = (vec![], vec![]); + for (step, op) in ops.iter().enumerate() { + let steps = s.doc().unwrap().history.undo.len(); + let before = model.clone(); + // Whether the step is an edit (one undo step). + let edit = match *op { + GuideOp::Add { vertical, pos, layer } => { + let l = layers[layer]; + let r = s.execute("guide.add", &json!({"vertical": vertical, "pos": pos, "layer": l.0})).unwrap(); + model.push((vertical, f64::from(pos), l.0)); + prop_assert_eq!(&r["index"], &json!(model.len() - 1), "step {}", step); + true + } + GuideOp::Remove(i) if !model.is_empty() => { + let i = i % model.len(); + s.execute("guide.remove", &json!({"index": i})).unwrap(); + model.remove(i); + true + } + GuideOp::Copy(i) if !model.is_empty() => { + let i = i % model.len(); + s.execute("guide.select", &json!({"indexes": [i]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + clip = Some((model[i].0, model[i].1)); + false + } + GuideOp::Paste => match clip { + Some((vertical, pos)) => { + s.execute("edit.paste", &json!({})).unwrap(); + model.push((vertical, pos, current.0)); + true + } + None => false, + }, + GuideOp::SetCurrent(l) => { + current = layers[l]; + s.execute("layer.setCurrent", &json!({"id": current.0})).unwrap(); + false + } + GuideOp::Undo => { + if let Some(m) = undo.pop() { + s.execute("edit.undo", &json!({})).unwrap(); + redo.push(std::mem::replace(&mut model, m)); + } + false + } + GuideOp::Redo => { + if let Some(m) = redo.pop() { + s.execute("edit.redo", &json!({})).unwrap(); + undo.push(std::mem::replace(&mut model, m)); + } + false + } + GuideOp::Remove(_) | GuideOp::Copy(_) => false, + }; + let after = s.doc().unwrap().history.undo.len(); + if edit { + prop_assert_eq!(after, steps + 1, "step {} {:?}: one undo step", step, op); + undo.push(before); + redo.clear(); + } else if !matches!(op, GuideOp::Undo | GuideOp::Redo) { + prop_assert_eq!(after, steps, "step {} {:?}: no undo step", step, op); + } + prop_assert_eq!(listed(&mut s), model.clone(), "step {} {:?}", step, op); + } + Ok(()) +} + +proptest::proptest! { + #![proptest_config(proptest::test_runner::Config { cases: 64, failure_persistence: None, ..proptest::test_runner::Config::default() })] + + /// Add, remove, copy, paste, undo and redo keep `guide.list` in step with a plain list, on + /// three layers. + #[test] + fn guide_commands_follow_a_list_model(ops in proptest::collection::vec(guide_op(), 1..40)) { + run_guide_ops(&ops)?; + } +} diff --git a/crates/engine/tests/it/ruler_guide_perf.rs b/crates/engine/tests/it/ruler_guide_perf.rs new file mode 100644 index 0000000000..1b5de5c5e2 --- /dev/null +++ b/crates/engine/tests/it/ruler_guide_perf.rs @@ -0,0 +1,130 @@ +//! Timings of a document with 10,000 ruler guides and 100,000 objects: save, load, open, the guide +//! list, hovering and dragging with the Selection tool, an edit that does not touch guides and one +//! that does. Ignored by default; it prints its timings and sets no bound on them: +//! `cargo test -p vectorcraft-engine --test it ruler_guide_perf -- --ignored --nocapture`. + +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::Document; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +const GUIDES: usize = 10_000; +const LAYERS: usize = 4; +const GROUPS_PER_LAYER: usize = 250; +const RECTS_PER_GROUP: usize = 100; + +/// The `.vectorcraft` file of the document: 100,000 rectangles in groups of 100 on four layers, +/// and the ruler guides in its saved list, spread over the layers. +fn file() -> Vec { + let mut b = DocBuilder::new(2000.0, 2000.0); + let mut layers = vec![b.layer]; + for l in 0..LAYERS { + if l > 0 { + layers.push(b.layer(&format!("Layer {}", l + 1))); + } + for g in 0..GROUPS_PER_LAYER { + let kids = (0..RECTS_PER_GROUP) + .map(|r| { + let (x, y) = (((g * RECTS_PER_GROUP + r) % 400) as f64 * 5.0, (l * GROUPS_PER_LAYER + g) as f64 * 2.0); + b.rect_node(Rect::new(x, y, x + 3.0, y + 1.5), Color::rgb(0.2, 0.4, 0.6)) + }) + .collect(); + b.group(kids, false); + } + } + let d: Document = b.build(); + let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&d, false)).unwrap(); + v["document"]["guides"] = + (0..GUIDES).map(|i| json!({"vertical": i % 2 == 0, "pos": (i / 2) as f64 * 0.37 + 0.1, "layer": layers[i % LAYERS]})).collect(); + serde_json::to_vec(&v).unwrap() +} + +/// The median of `n` runs of `f`. +fn median(n: usize, mut f: impl FnMut()) -> Duration { + let mut t: Vec = (0..n) + .map(|_| { + let start = Instant::now(); + f(); + start.elapsed() + }) + .collect(); + t.sort(); + t[n / 2] +} + +fn report(what: &str, d: Duration) { + eprintln!("ruler_guide_perf: {what:<44} {:>10.3} ms", d.as_secs_f64() * 1000.0); +} + +fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) { + s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap(); +} + +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn ruler_guide_perf() { + let bytes = file(); + eprintln!("ruler_guide_perf: file of {} bytes", bytes.len()); + report("load (format::load), median of 5", median(5, || drop(vectorcraft_format::load(&bytes).unwrap()))); + let doc = vectorcraft_format::load(&bytes).unwrap(); + report("save (format::save), median of 5", median(5, || drop(vectorcraft_format::save(&doc, false)))); + + let mut s = Session::new(); + let data = vectorcraft_format::base64_encode(&bytes); + let start = Instant::now(); + s.execute("document.open", &json!({"name": "perf.vectorcraft", "dataBase64": data})).unwrap(); + report("document.open", start.elapsed()); + let listed = s.execute("guide.list", &json!({})).unwrap().as_array().map_or(0, Vec::len); + assert_eq!(listed, GUIDES); + report("guide.list, median of 11", median(11, || drop(s.execute("guide.list", &json!({})).unwrap()))); + + s.select_tool("selection", ViewInfo::default()).unwrap(); + let mut i = 0.0; + report( + "hover (Selection tool move), median of 201", + median(201, || { + i += 1.0; + pointer(&mut s, PointerKind::Move, 600.0 + i * 0.13, 300.0 + i * 0.07); + }), + ); + // A drag of the first rectangle's group (the rectangle is at 0,0 to 3,1.5), with its + // snapping: one undo step. + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 1.5, 0.75); + let mut j = 0.0; + report( + "drag (Selection tool drag step), median of 51", + median(51, || { + j += 1.0; + pointer(&mut s, PointerKind::Drag, 1.5 + j * 0.9, 0.75 + j * 0.4); + }), + ); + let start = Instant::now(); + pointer(&mut s, PointerKind::Up, 1.5 + j * 0.9, 0.75 + j * 0.4); + report("drag release (commit)", start.elapsed()); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "the drag moved the group"); + + let mut k = 0.0; + report( + "edit without guides (shape.rectangle), median of 21", + median(21, || { + k += 1.0; + s.execute("shape.rectangle", &json!({"x": k, "y": 1900, "width": 5, "height": 5})).unwrap(); + }), + ); + report("undo, median of 11", median(11, || drop(s.execute("edit.undo", &json!({})).unwrap()))); + let mut m = 0.0; + report( + "guide edit (guide.move), median of 21", + median(21, || { + m += 1.0; + s.execute("guide.move", &json!({"index": GUIDES / 2, "pos": 100.0 + m})).unwrap(); + }), + ); + report("file.saveCopy, median of 3", median(3, || drop(s.execute("file.saveCopy", &json!({})).unwrap()))); +} diff --git a/crates/engine/tests/it/ruler_origin.rs b/crates/engine/tests/it/ruler_origin.rs index 4b5c06286d..f6a910515e 100644 --- a/crates/engine/tests/it/ruler_origin.rs +++ b/crates/engine/tests/it/ruler_origin.rs @@ -78,7 +78,7 @@ fn native_versions_and_compression_keep_the_origin_and_old_files_default_to_zero assert_eq!(back.ruler_origin_for(0), doc.ruler_origin_for(0), "v{version}, compression {compress}"); assert_eq!((back.rulers, &back.artboard_ruler_origins), (doc.rulers, &doc.artboard_ruler_origins), "v{version}, compression {compress}"); assert_eq!(back.layers, doc.layers); - assert_eq!(back.guides, doc.guides); + assert_eq!(back.ruler_guides(), doc.ruler_guides()); } } diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 0bc8615d6f..58cc302279 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -15,7 +15,7 @@ use proptest::prelude::*; use serde_json::{Map, Value, json}; use vectorcraft_engine::Session; use vectorcraft_plugins::wat as tpl; -use vectorcraft_plugins::{Error, Kind, Limits, Plugin}; +use vectorcraft_plugins::{BYTES_COPIED_PER_FUEL, Error, FUEL_SLICE, Kind, Limits, Plugin}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::rich_session; @@ -187,9 +187,6 @@ fn arb_paint() -> impl Strategy { /// Bytes in the passive data segment that bulk memory cases initialize memory from. const SEGMENT_LEN: u32 = 4096; -/// Fuel the host hands a run per slice (`FUEL_SLICE` in `vectorcraft_plugins`' runtime). -const FUEL_SLICE: u64 = 20_000_000; - /// Where a bulk memory plug-in keeps its output (the manifest sits at 16). const BULK_OUTPUT_AT: u32 = 0x8000; @@ -319,10 +316,10 @@ impl BulkCase { } } - /// A generous estimate of the fuel the instructions use: a unit per 64 bytes moved, and a few - /// per pass. + /// A generous estimate of the fuel the instructions use: a unit per [`BYTES_COPIED_PER_FUEL`] + /// bytes moved, and a few per pass. fn fuel(self) -> u64 { - u64::from(self.runs()) * (u64::from(self.len) / 64 + 16) + u64::from(self.runs()) * (u64::from(self.len) / u64::from(BYTES_COPIED_PER_FUEL) + 16) } /// The plug-in module in WAT, with `manifest`. @@ -352,11 +349,12 @@ impl BulkCase { } } -/// Lengths: zero, a byte, around the 64 bytes a unit of fuel pays for, the data segment's length, -/// a page, a mebibyte, or anything up to four pages. +/// Lengths: zero, a byte, around the bytes a unit of fuel pays for, the data segment's length, a +/// page, a mebibyte, or anything up to four pages. fn arb_bulk_len() -> impl Strategy { + let per = BYTES_COPIED_PER_FUEL; prop_oneof![ - 3 => prop::sample::select(vec![0u32, 1, 63, 64, 65, SEGMENT_LEN - 1, SEGMENT_LEN, SEGMENT_LEN + 1, 0xffff, 0x1_0000, 0x1_0001, 1 << 20]), + 3 => prop::sample::select(vec![0u32, 1, per - 1, per, per + 1, SEGMENT_LEN - 1, SEGMENT_LEN, SEGMENT_LEN + 1, 0xffff, 0x1_0000, 0x1_0001, 1 << 20]), 1 => 0u32..0x4_0000, ] } @@ -394,7 +392,7 @@ fn arb_bulk_case() -> impl Strategy { let repeat = match repeat { Repeat::Times(n) => n, Repeat::AroundSlice(k) => { - let slice = (FUEL_SLICE * 64 / u64::from(len.max(1))) as i64; + let slice = (FUEL_SLICE * u64::from(BYTES_COPIED_PER_FUEL) / u64::from(len.max(1))) as i64; (slice + k).clamp(1, 2_000) as u32 } }; diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index b780c115c3..f091062308 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -326,7 +326,7 @@ fn an_importer_past_its_budget_opens_nothing() { ]; for (id, limits, _) in &cases { let wasm = wat::parse_str(tpl::module(&tpl::importer(id, r#"["tbg"]"#, "{}"), SPINS, "", 1)).unwrap(); - vectorcraft_plugins::registry::install(Plugin::load(&wasm, limits.clone()).unwrap()); + vectorcraft_plugins::registry::install(Plugin::load(&wasm, limits.clone()).unwrap()).unwrap(); } let mut s = Session::new(); for (id, _, why) in &cases { diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8efa0637ad..1ab878fc62 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3785,6 +3785,34 @@ fn an_unstroked_run_with_a_stroke_style_loses_nothing() { } } +/// The text document has no Korean Line Break Anywhere: a paragraph with it on and Hangul in it +/// is reported as left out, and comes back off; with it off, or with no Hangul, nothing is +/// reported. +#[test] +fn korean_line_break_anywhere_is_reported_only_for_korean_paragraphs() { + use vectorcraft_doc::TextObject; + for (text, on, reported) in [("가나다 라마", true, true), ("가나다 라마", false, false), ("Plain", true, false)] { + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), text, style(14.0, Color::BLACK)); + t.para.korean_line_break_anywhere = on; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(!out.warnings.is_empty(), reported, "{text} {on}: {:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&doc).layers, &mut all); + let paras: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.para_at(0).korean_line_break_anywhere), + _ => None, + }) + .collect(); + assert_eq!(paras, [false], "{text} {on}"); + } +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); @@ -4338,6 +4366,49 @@ fn scaled_area_type_and_type_on_a_path_stay_type() { assert!(!program(&doc).contains("/AI11Text")); } +/// Type on a path with Dynamic Text is written as type at the sizes it is drawn at, with a warning +/// that the setting is not written. +#[test] +fn dynamic_text_is_written_at_its_drawn_sizes() { + use vectorcraft_doc::{TextKind, TextObject}; + let mut doc = Document::new(600.0, 300.0); + let layer = doc.layers[0].id; + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Grow", style(12.0, Color::BLACK)); + t.kind = TextKind::OnPath { + path: shapes::line(vectorcraft_geom::Point::new(50.0, 200.0), vectorcraft_geom::Point::new(550.0, 200.0)), + start: 0.0, + end: None, + }; + t.xf = Affine::IDENTITY; + t.dynamic_text = true; + let drawn = 12.0 * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).fit_scale; + assert!(drawn > 50.0, "{drawn}"); + let node = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::DYNAMIC_TEXT), "{:?}", out.warnings); + let back = read_back(&doc); + let texts: Vec<&TextObject> = + back.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.as_ref()) } else { None }).collect(); + assert_eq!(texts.len(), 1); + assert!(!texts[0].dynamic_text); + let k = texts[0].xf.as_coeffs()[0]; + assert_eq!(r3(texts[0].runs[0].style.size * k), r3(drawn)); + // Type written as outlines (here on an open path whose ends meet) loses the setting too, and + // says so. + let mut doc = Document::new(600.0, 300.0); + let layer = doc.layers[0].id; + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Grow", style(12.0, Color::BLACK)); + let ends_meet = [(50.0, 200.0).into(), (550.0, 200.0).into(), (300.0, 50.0).into(), (50.0, 200.0).into()]; + t.kind = TextKind::OnPath { path: PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ends_meet, false)]), start: 0.0, end: None }; + t.xf = Affine::IDENTITY; + t.dynamic_text = true; + let node = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::TYPE) && out.warnings.iter().any(|w| w == writer::DYNAMIC_TEXT), "{:?}", out.warnings); +} + /// See-through type with the knockout shape flag comes back with the flag and writes no warning. #[test] fn the_knockout_shape_of_type_comes_back() { @@ -6597,6 +6668,7 @@ fn every_effect_a_graphic_style_holds_is_read_back() { for id in &ids { cases.push((id, json!({"bend": 30.0, "horizontal": -10.0, "vertical": 20.0, "orientation": "vertical"}))); cases.push((id, json!({"bend": -30.0, "horizontal": 0.0, "vertical": 0.0, "orientation": "horizontal"}))); + cases.push((id, json!({"bend": 45.0, "horizontal": 15.0, "vertical": -5.0, "orientation": "horizontal", "version": 1}))); } for (id, params) in cases { let effect = fx(id, params.clone()); @@ -6613,6 +6685,10 @@ fn every_effect_a_graphic_style_holds_is_read_back() { let got = &back.graphic_styles[0].appearance.effects; assert_eq!(got.len(), 1, "{id} {params}"); assert_eq!(got[0].id, effect.id); + // A warp read from a file bends as its style's Bézier net. + if id.starts_with("warp.") { + assert_eq!(got[0].params["version"], json!(vectorcraft_doc::live::WARP_NET), "{id} {params}"); + } let (g, w) = (vectorcraft_effects::merged_params(&got[0].id, &got[0].params), vectorcraft_effects::merged_params(&effect.id, &effect.params)); for (key, value) in w.as_object().unwrap() { // Random isn't written, and a style with it isn't read; its seed is the default. @@ -6633,6 +6709,19 @@ fn every_effect_a_graphic_style_holds_is_read_back() { } } } + // A warp saved before the map version existed is written with its settings too, and reads back on + // the nets' map. + let old = vectorcraft_doc::Effect { id: "warp.flag".into(), params: json!({"bend": 40.0, "horizontal": 10.0}), visible: true }; + let mut doc = Document::new(200.0, 100.0); + let mut g = vectorcraft_doc::GraphicStyle::new("Old", Appearance { effects: vec![old], ..Appearance::basic(black_fill(), Paint::None, 0.0) }); + g.id = 3; + *doc.graphic_styles = vec![g]; + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + let back = read_back(&doc); + let [warp] = back.graphic_styles[0].appearance.effects.as_slice() else { panic!("{:?}", back.graphic_styles) }; + assert_eq!((warp.id.as_str(), &warp.params["bend"], &warp.params["horizontal"]), ("warp.flag", &json!(40.0), &json!(10.0))); + assert_eq!(warp.params["version"], json!(vectorcraft_doc::live::WARP_NET)); // A Zig Zag with its 0 to 1 settings written under the size's own key, and a turn in radians. let mut doc = Document::new(200.0, 100.0); let effects = vec![ @@ -7506,3 +7595,84 @@ fn variable_font_instances_name_their_design_space() { fn style_of(size: f64) -> vectorcraft_doc::CharStyle { style(size, Color::BLACK) } + +/// The data has no conic gradient: a conic fill is a linear gradient along its vector, with the +/// same stops, and so is a conic gradient swatch, with a warning. +#[test] +fn conic_gradients_are_written_as_linear_gradients_with_their_stops() { + let stops = + vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(0.6, SKY), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops.clone())); + let (start, end) = (vectorcraft_geom::Point::new(100.0, 50.0), vectorcraft_geom::Point::new(150.0, 50.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: -0.5, focal: None }); + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + let fill = Paint::Gradient(Box::new(g.clone())); + doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill.clone(), Paint::None, 0.0))) + .unwrap(); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Sweep".into(), paint: Paint::Gradient(Box::new(GradientPaint { geom: None, ..g })), global: false, spot: false }); + doc.swatches = swatches.into(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("conic gradients are written as linear gradients")), "{:?}", out.warnings); + let back = read_back(&doc); + let mut read = None; + back.walk(|n| { + if let Paint::Gradient(g) = n.appearance.fill_paint() { + read = Some(g.clone()); + } + }); + let read = read.expect("a gradient fill"); + assert_eq!(read.gradient.kind, GradientKind::Linear); + assert_eq!( + read.gradient.stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::>(), + stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::>() + ); + let geom = read.geom.unwrap(); + assert!(geom.start.distance(start) < 0.01 && geom.end.distance(end) < 0.01, "{geom:?}"); + let Some(Paint::Gradient(swatch)) = back.swatch("Sweep").map(|s| &s.paint) else { panic!("the swatch is lost") }; + assert_eq!(swatch.gradient.kind, GradientKind::Linear); +} + +/// The data has no diamond gradient: a diamond fill is the radial gradient through its square's +/// corners (centered on it, its vector and the aspect across it), with the same stops, and so is +/// a diamond gradient swatch, with a warning. +#[test] +fn diamond_gradients_are_written_as_radial_gradients_through_their_corners() { + let stops = + vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(0.6, SKY), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops.clone())); + let (start, end) = (vectorcraft_geom::Point::new(100.0, 50.0), vectorcraft_geom::Point::new(150.0, 50.0)); + // A focal point (a plug-in's or a file's) draws nothing on a diamond and isn't written. + let focal = Some(vectorcraft_geom::Point::new(110.0, 55.0)); + g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 0.5, focal }); + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + let l = doc.layers[0].id; + let fill = Paint::Gradient(Box::new(g.clone())); + doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, Paint::None, 0.0))).unwrap(); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Gem".into(), paint: Paint::Gradient(Box::new(GradientPaint { geom: None, ..g })), global: false, spot: false }); + doc.swatches = swatches.into(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("diamond gradients are written as radial gradients")), "{:?}", out.warnings); + let back = read_back(&doc); + let mut read = None; + back.walk(|n| { + if let Paint::Gradient(g) = n.appearance.fill_paint() { + read = Some(g.clone()); + } + }); + let read = read.expect("a gradient fill"); + assert_eq!(read.gradient.kind, GradientKind::Radial); + assert_eq!( + read.gradient.stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::>(), + stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::>() + ); + let geom = read.geom.unwrap(); + assert!(geom.start.distance(start) < 0.01 && geom.end.distance(end) < 0.01 && (geom.aspect - 0.5).abs() < 0.01, "{geom:?}"); + assert!(geom.focal.is_none_or(|f| f.distance(start) < 0.01), "{geom:?}"); + let Some(Paint::Gradient(swatch)) = back.swatch("Gem").map(|s| &s.paint) else { panic!("the swatch is lost") }; + assert_eq!(swatch.gradient.kind, GradientKind::Radial); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index c598e2cd9a..dea4ad0c24 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -64,6 +64,7 @@ pub(super) const SWATCHES: &str = "freeform gradient swatches, gradient swatches 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"; pub(super) const OBJECT_LIMIT: &str = "art past 4,000,000 objects in all is 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"; +pub(super) const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at in the editing data for other apps"; /// The transparency `mode opacity isolate knockout shape Xy` sets: the blending mode ([`blend_code`]), /// the opacity, Isolate Blending, Knockout Group (0 off, 1 on, 2 neutral) and Opacity & Mask Define @@ -460,6 +461,9 @@ impl<'a> Writer<'a> { let flag = |b: bool| u8::from(b); let dim = dim_images.unwrap_or(50); let name = n.name.as_deref().unwrap_or("Layer"); + // Ruler guides are kept in the document's native copy only. + let children: Vec> = children.iter().filter(|c| !c.is_ruler_guide()).cloned().collect(); + let children = &children; // The last flag makes the layer a clipping layer: its top object clips the rest. Only a // clipping path or compound path, outside any art cut to a clipping object, is written as // one ([`Self::clip_group`] writes the others). @@ -583,6 +587,10 @@ impl<'a> Writer<'a> { if let NodeKind::Layer { .. } = n.kind { return self.write_layer(n, &[]); } + // Ruler guides are kept in the document's native copy only: no object, state or style. + if n.is_ruler_guide() { + return; + } if self.in_symbol { self.wrote_fixed |= symbols::redrawn(n); } @@ -697,6 +705,8 @@ impl<'a> Writer<'a> { } self.end_group("U", xy); } + // Ruler guides are kept in the document's native copy only. + NodeKind::RulerGuide { .. } => {} } if self.body.len() > start { // A group's dictionary goes between its end and its state block. @@ -1194,6 +1204,9 @@ impl<'a> Writer<'a> { /// names the story of its thread, which its first frame holds. fn text(&mut self, n: &Node, xy: Xy) { let NodeKind::Text(t) = &n.kind else { return }; + // Dynamic Text is written as the sizes its layout draws the type at. + let fitted = t.dynamic_text.then(|| vectorcraft_text::drawn(t)); + let t = fitted.as_deref().unwrap_or(&**t); let doc = self.doc; let thread = doc.text_threads.iter().find(|th| th.contains(&n.id)); // Type that can't be a stub is written as its outlines, which count their own objects. @@ -1222,6 +1235,9 @@ impl<'a> Writer<'a> { if lost { self.warn(texts::TYPE_ATTRIBUTES); } + if fitted.is_some() { + self.warn(DYNAMIC_TEXT); + } // The stub takes the transparency set before it, as a path does. Its isolation and knockout // are read only from a state block after it, as a group's are. self.set_object_xy(xy.object()); @@ -1241,6 +1257,10 @@ impl<'a> Writer<'a> { return; } self.warn(TYPE); + // The outlines keep the sizes Dynamic Text draws the type at, but not the setting. + if matches!(&n.kind, NodeKind::Text(t) if t.dynamic_text) { + self.warn(DYNAMIC_TEXT); + } let doc = self.doc; let resolved = match &n.kind { NodeKind::Text(t) => Some(doc.inline_resolved(t).into_owned()), diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index b9d28253d0..0dbe24c937 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -21,6 +21,8 @@ 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 CONIC: &str = + "conic gradients are written as linear gradients along their vector, with the same stops, 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. @@ -43,12 +45,22 @@ pub(super) struct PatternOut { used: bool, } -/// Can `g` be written as a gradient (a linear or radial one with stops, no more than the `.ai` -/// reader reads)? +pub(in crate::ai_editing) const DIAMOND: &str = + "diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps"; + +/// Can `g` be written as a gradient (a linear, radial, conic or diamond one with stops, no more +/// than the `.ai` reader reads; a conic is written linear, [`CONIC`], and a diamond radial, +/// [`DIAMOND`])? fn writable_gradient(g: &Gradient) -> bool { g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS } +/// Is a gradient of `kind` written as a radial one: a radial gradient, or a diamond (the ellipse +/// through its square's corners, [`DIAMOND`])? +fn written_radial(kind: GradientKind) -> bool { + matches!(kind, GradientKind::Radial | GradientKind::Diamond) +} + /// 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 { @@ -126,7 +138,7 @@ impl Writer<'_> { 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; + let radial = written_radial(g.gradient.kind); if g.gradient.kind == GradientKind::Freeform { self.warn(GRADIENTS); return Paint::solid(average(&g.gradient)); @@ -242,7 +254,7 @@ impl Writer<'_> { self.instance_head(g, clip, path); let m = self.grad_space; let u = geom.end - geom.start; - let radial = g.gradient.kind == GradientKind::Radial; + let radial = written_radial(g.gradient.kind); // The unit vector along the gradient, and across it as long. let frame = |from: f64, to: f64| { let p = geom.start + u * from; @@ -273,10 +285,15 @@ impl Writer<'_> { /// A gradient instance's focal point (`Bh`, radial gradients only) and its `Bg` line, as /// [`Self::instance`] writes them; also what a fill's art style holds after its `Bb`. pub(super) fn instance_head(&mut self, g: &GradientPaint, clip: bool, path: &BezPath) { - let Some(geom) = g.geom else { return }; + let Some(mut geom) = g.geom else { return }; + if g.gradient.kind != GradientKind::Radial { + // Only a radial gradient has a focal point (a plug-in's or a file's other kinds can + // carry one that draws nothing): a diamond's circle stays centered. + geom.focal = None; + } let name = self.define_gradient(&g.gradient, g.swatch.as_deref()); let m = self.grad_space; - let radial = g.gradient.kind == GradientKind::Radial; + let radial = written_radial(g.gradient.kind); let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas); if radial { let c = m * geom.start; @@ -300,8 +317,14 @@ impl Writer<'_> { if d.gradient.dither || !d.gradient.method.is_classic() { self.warn(GRADIENT_MIX); } + if d.gradient.kind == GradientKind::Conic { + self.warn(CONIC); + } + if d.gradient.kind == GradientKind::Diamond { + self.warn(DIAMOND); + } let name = ps::bytes(d.name.as_bytes()); - let radial = d.gradient.kind == GradientKind::Radial; + let radial = written_radial(d.gradient.kind); 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 { @@ -503,7 +526,7 @@ impl Writer<'_> { 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 { + if written_radial(g.gradient.kind) { 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())); diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 65fe918599..c28c538bcf 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -28,6 +28,10 @@ pub(in crate::ai_editing) const STYLE_LINKS: &str = "links to graphic styles are /// How many objects of `doc`'s layers, opacity masks and symbols are linked to a graphic style. pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize { fn count(n: &Node) -> usize { + // Ruler guides are not written as objects. + if n.is_ruler_guide() { + return 0; + } let own = usize::from(n.extras().graphic_style.is_some()); let mask = n.extras().mask.as_ref().map_or(0, |m| count(&m.art)); own + mask + n.children().map_or(0, |c| c.iter().map(|m| count(m)).sum()) @@ -885,9 +889,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> } /// Effect `e`'s settings with its defaults filled in, its blending mode in lower case and its color as -/// `#rrggbb`. +/// `#rrggbb`. A Warp's map `version` is left out: the file holds the warp's settings, and the reader +/// gives every warp it reads the newest map, so a warp saved before the version existed is written +/// with its settings as before. fn normalized_params(e: &Effect) -> Value { let mut p = vectorcraft_effects::merged_params(&e.id, &e.params); + if e.id.starts_with("warp.") + && let Value::Object(m) = &mut p + { + m.remove("version"); + } if let Some(m) = word(&p, "mode") { p["mode"] = Value::String(m); } diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 5ebd73de3a..1d791afadf 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -385,6 +385,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { if p.justify == Justify::Auto && p.direction.is_none() && rtl_letter { return true; } + let hangul = + text.chars().any(|c| matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{FFA0}'..='\u{FFDC}')); let held = ParaStyle { justify: p.justify, left_indent: p.left_indent, @@ -398,6 +400,9 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { // Width, Standard burasagari) isn't reported: it changes no other script's lines. mojikumi: if p.mojikumi == Mojikumi::LineEndHalf { p.mojikumi } else { ParaStyle::default().mojikumi }, burasagari: if p.burasagari == Burasagari::Standard { p.burasagari } else { ParaStyle::default().burasagari }, + // The text document has no Korean Line Break Anywhere: it reads back off, which + // changes only the lines of a paragraph with Hangul in it. + korean_line_break_anywhere: p.korean_line_break_anywhere && !hangul, ..ParaStyle::default() }; *p != held diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0a5799ddf9..dc335bf1a1 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -42,6 +42,7 @@ mod interp; mod lex; mod native; mod obj; +mod predefined_cmap; mod preview; mod shading; mod text; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 8b3fceecf3..50674860a6 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -244,6 +244,7 @@ fn warp(o: &Obj) -> Option { h: percent("DeformHoriz")?, v: percent("DeformVert")?, horizontal: !vertical, + version: vectorcraft_doc::live::WARP_NET, }) } diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a1b24662ec..6cdbb96747 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -14,12 +14,12 @@ use std::sync::Arc; -use craft_pdf::interpret::hayro_cmap::{BfString, CMap, CMapName, load_embedded}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen}; use vectorcraft_color::Paint; use vectorcraft_doc::{Burasagari, CharStyle, Justify, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject, TextRun}; use vectorcraft_geom::AnchorKind; +use super::super::super::predefined_cmap::{self, CMapCodes, composite_font}; use super::super::obj::V; use super::art::path_data; use super::{FLIP, GState, HashSet, Kind, Node, NodeId, Reader}; @@ -284,259 +284,15 @@ impl TypeState { /// How strings in a font with predefined CMap `cmap` decode; `None` when the CMap can't be read. fn cmap_codes(&mut self, cmap: &str) -> Option> { - if let Some(form) = unicode_cmap(cmap) { - return Some(Arc::new(CMapCodes::Unicode(form))); - } if let Some((_, codes)) = self.cmaps.iter().find(|(n, _)| n == cmap) { return codes.clone(); } - let codes = cid_codes(cmap).map(Arc::new); + let codes = predefined_cmap::codes(cmap).map(Arc::new); self.cmaps.push((cmap.to_string(), codes.clone())); codes } } -/// How a composite font's strings decode. -#[derive(Debug)] -enum CMapCodes { - /// By a predefined CMap's codes to CIDs, then by its character collection's CID → Unicode CMap; - /// with `high_bit`, each byte 0x21 to 0x7E gets its high bit set first. `space` is the CMap's - /// code space ([`code_space`]). - Cids { codes: Box, unicode: Box, high_bit: bool, space: Option }, - /// A predefined Unicode CMap: the codes are the characters. - Unicode(Unicode), -} - -/// A CMap's code space: ranges of codes, each given by its lowest and highest code, both with the -/// code's length in bytes. -type CodeSpace = &'static [(&'static [u8], &'static [u8])]; - -/// What control byte `b` is in a composite font's string: `\r` a paragraph break, `\t` a tab. -fn control(b: u8) -> Option { - match b { - b'\r' => Some('\n'), - b'\t' => Some('\t'), - _ => None, - } -} - -impl CMapCodes { - /// The characters of string `bytes`, leaving out codes the CMaps don't map; a `\r` is a - /// paragraph break and a `\t` a tab (also as a byte left over after the last whole code of a - /// UTF-16 or UTF-32 string). - fn decode(&self, bytes: &[u8]) -> String { - let (codes, unicode, high_bit, space) = match self { - Self::Unicode(form) => { - let unit = match form { - Unicode::Utf16 => 2, - Unicode::Utf8 => 1, - Unicode::Utf32 => 4, - }; - let (whole, rest) = bytes.split_at_checked(bytes.len() - bytes.len() % unit).unwrap_or((bytes, &[])); - let mut text = unicode_text(whole, *form).replace('\r', "\n"); - text.extend(rest.last().copied().and_then(control)); - return text; - } - Self::Cids { codes, unicode, high_bit, space } => (codes, unicode, *high_bit, space), - }; - let euc: Vec; - let bytes = if high_bit { - euc = bytes.iter().map(|&b| if (0x21..0x7f).contains(&b) { b | 0x80 } else { b }).collect(); - euc.as_slice() - } else { - bytes - }; - let mut out = String::new(); - let mut at = 0; - while let Some(&first) = bytes.get(at) { - // VectorCraft reads a 0x0D byte as a paragraph break and a 0x09 byte as a tab in every - // CMap, as in other fonts' strings, including the row-and-cell CMaps, whose code space - // has no one-byte codes. - if let Some(control) = control(first) { - out.push(control); - at += 1; - continue; - } - let rest = bytes.get(at..).unwrap_or_default(); - let code = |len: u8| rest.get(..usize::from(len)).map(|b| b.iter().fold(0u32, |c, &b| c << 8 | u32::from(b))); - let found = match space { - // The code is as long as the code space range it falls in; a byte that starts no - // code in the code space is skipped. - Some(space) => { - let Some(len) = code_len(space, rest) else { - at += 1; - continue; - }; - code(len).map(|c| (len, codes.lookup_cid_code(c, len))) - } - None => (1..=4u8).find_map(|len| Some((len, Some(codes.lookup_cid_code(code(len)?, len)?)))), - }; - let Some((len, cid)) = found else { - at += 1; - continue; - }; - at += usize::from(len); - // A code the CMap leaves out is dropped. - let Some(cid) = cid else { continue }; - match unicode.lookup_bf_string(cid) { - // A one-byte Roman code whose CID the table gives as a combining mark alone (0x7E in - // the Mac Shift-JIS CMaps, U+0303): the ASCII character, as Adobe's cid2code.txt lists first. - Some(BfString::Char('\u{300}'..='\u{36f}')) if len == 1 && (0x20..0x7f).contains(&first) => out.push(char::from(first)), - Some(BfString::Char(c)) if c != char::REPLACEMENT_CHARACTER => out.push(c), - Some(BfString::String(s)) => out.extend(s.chars().filter(|c| *c != char::REPLACEMENT_CHARACTER)), - _ => {} - } - } - out - } -} - -/// How a predefined Unicode CMap's codes encode their characters. -#[derive(Clone, Copy, PartialEq, Debug)] -enum Unicode { - /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. - Utf16, - Utf8, - /// Four bytes, the high byte first. - Utf32, -} - -/// The encoding of predefined Unicode CMap `name`: `Uni` and a character collection, then `-UCS2`, -/// `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), then `-H` or `-V` -/// (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: ). -fn unicode_cmap(name: &str) -> Option { - let rest = name.strip_suffix("-H").or_else(|| name.strip_suffix("-V"))?; - let rest = rest.strip_suffix("-HW").unwrap_or(rest); - let (collection, form) = rest.rsplit_once('-')?; - let collections = ["UniJIS", "UniJISPro", "UniJIS2004", "UniJISX0213", "UniJISX02132004", "UniHojo", "UniGB", "UniCNS", "UniKS", "UniAKR"]; - if !collections.contains(&collection) { - return None; - } - match form { - "UCS2" | "UTF16" => Some(Unicode::Utf16), - "UTF8" => Some(Unicode::Utf8), - "UTF32" => Some(Unicode::Utf32), - _ => None, - } -} - -/// The characters string `s` encodes in Unicode form `form` (invalid codes left out). -fn unicode_text(s: &[u8], form: Unicode) -> String { - match form { - Unicode::Utf16 => { - let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)); - char::decode_utf16(units).filter_map(Result::ok).collect() - } - Unicode::Utf8 => s.utf8_chunks().map(|chunk| chunk.valid()).collect(), - Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(), - } -} - -/// Predefined CMap `name` among those VectorCraft carries, leaving out the Identity CMaps, whose -/// codes are CIDs of no known character collection. -fn predefined(name: &str) -> Option> { - match CMapName::from_bytes(name.as_bytes()) { - CMapName::Custom(_) | CMapName::IdentityH | CMapName::IdentityV => None, - name => Some(name), - } -} - -/// Adobe's predefined CMaps that VectorCraft doesn't carry, by name without `-H` or `-V` -/// (): the nearest carried CMap with the same -/// code space, and whether each byte of a row-and-cell code gets its high bit set first (the EUC -/// form of the same code; `GB-H`, `CNS1-H` and `KSC-H` have no one-byte codes, their code space -/// is `<2121>` to `<7E7E>`); `None` for those no carried CMap reads. -fn stand_in(stem: &str) -> Option> { - Some(match stem { - "RKSJ" | "78-RKSJ" | "78ms-RKSJ" => Some(("90ms-RKSJ-H", false)), - "78-EUC" => Some(("EUC-H", false)), - "78" | "Add" | "Ext" | "NWP" => Some(("H", false)), - "GB" => Some(("GB-EUC-H", true)), - "CNS1" => Some(("CNS-EUC-H", true)), - "KSC" => Some(("KSC-EUC-H", true)), - "B5" => Some(("ETen-B5-H", false)), - "ETHK-B5" | "HKdla-B5" | "HKdlb-B5" | "HKgccs-B5" | "HKm314-B5" | "HKm471-B5" => Some(("HKscs-B5-H", false)), - "GBT" | "GBT-EUC" | "GBTpc-EUC" | "CNS2" | "KSC-Johab" => None, - _ => return None, - }) -} - -/// Predefined CMap `cmap`'s codes to CIDs, and its character collection's CID → Unicode CMap. A -/// vertical CMap's codes are read with its horizontal CMap when VectorCraft carries that: the two -/// differ only in the CIDs of vertical glyph forms. A CMap VectorCraft doesn't carry is read with -/// its [`stand_in`]. -fn cid_codes(cmap: &str) -> Option { - let read = |name: &str| CMap::parse(load_embedded(predefined(name)?)?, load_embedded); - let horizontal = cmap.strip_suffix('V').map(|stem| format!("{stem}H")); - let stem = cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")); - let (codes, high_bit) = horizontal.iter().map(String::as_str).chain([cmap]).find_map(|n| Some((read(n)?, false))).or_else(|| { - let (name, high_bit) = stand_in(stem?).flatten()?; - Some((read(name)?, high_bit)) - })?; - let table = codes.metadata().character_collection.as_ref()?.family.ucs2_cmap()?; - let unicode = CMap::parse(load_embedded(table)?, load_embedded)?; - // A row-and-cell code read in its EUC form falls in the EUC CMap's code space. - let space = if high_bit { stand_in(stem?).flatten().and_then(|(name, _)| code_space(name)) } else { code_space(cmap) }; - Some(CMapCodes::Cids { codes: Box::new(codes), unicode: Box::new(unicode), high_bit, space }) -} - -/// The code space of predefined CMap `cmap`, as Adobe's CMap files give it -/// (); a CMap's vertical form has its -/// horizontal form's. `None` for a CMap not listed here. -fn code_space(cmap: &str) -> Option { - const RKSJ: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; - const RKSJ_MAC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\xfd", b"\xff"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; - const EUC_JP: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\xa0", b"\x8e\xdf"), (b"\xa1\xa1", b"\xfe\xfe")]; - const ROW_CELL: CodeSpace = &[(b"\x21\x21", b"\x7e\x7e")]; - const EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe")]; - const GB_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\xa1", b"\xfc\xfe")]; - const GBK: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x40", b"\xfe\xfe")]; - const GBK2K: CodeSpace = &[(b"\x00", b"\x7f"), (b"\x81\x40", b"\xfe\xfe"), (b"\x81\x30\x81\x30", b"\xfe\x39\xfe\x39")]; - const B5_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\x40", b"\xfc\xfe")]; - const B5: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\x40", b"\xfe\xfe")]; - const HKSCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x87\x40", b"\xfe\xfe")]; - const HKDLB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\x40", b"\xfe\xfe")]; - const HKGCCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8a\x40", b"\xfe\xfe")]; - const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")]; - const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")]; - const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")]; - let stem = match cmap { - "H" | "V" => "", - _ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?, - }; - let stem = stem.strip_suffix("-HW").unwrap_or(stem); - Some(match stem { - "83pv-RKSJ" | "90pv-RKSJ" => RKSJ_MAC, - _ if stem.ends_with("RKSJ") => RKSJ, - "EUC" | "78-EUC" => EUC_JP, - "" | "78" | "Add" | "Ext" | "NWP" => ROW_CELL, - "GB-EUC" | "GBT-EUC" | "KSC-EUC" => EUC, - "GBpc-EUC" | "GBTpc-EUC" => GB_PC, - "GBK-EUC" | "GBKp-EUC" => GBK, - "GBK2K" => GBK2K, - "B5pc" => B5_PC, - "B5" | "ETen-B5" | "ETenms-B5" | "HKdla-B5" | "HKm314-B5" | "HKm471-B5" => B5, - "HKscs-B5" | "ETHK-B5" => HKSCS, - "HKdlb-B5" => HKDLB, - "HKgccs-B5" => HKGCCS, - "CNS-EUC" => CNS_EUC, - "KSCpc-EUC" => KSC_PC, - "KSCms-UHC" => UHC, - _ => return None, - }) -} - -/// The length of the code string `bytes` starts with: the length of the code space range whose -/// lowest and highest codes hold each of its bytes between them. `None` when no range does. -fn code_len(space: CodeSpace, bytes: &[u8]) -> Option { - space - .iter() - .filter(|(lo, hi)| bytes.get(..lo.len()).is_some_and(|b| b.iter().zip(lo.iter().zip(hi.iter())).all(|(b, (lo, hi))| (lo..=hi).contains(&b)))) - .map(|(lo, _)| lo.len()) - .min() - .and_then(|len| u8::try_from(len).ok()) -} - /// 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; @@ -556,36 +312,6 @@ fn encoding_pairs(table: &mut [Option], vals: &[V]) { } } -/// A composite font's name `base-CMap`: the base font's name and its CMap's name, when that is a -/// predefined Unicode CMap ([`unicode_cmap`]), one of the predefined CMaps VectorCraft carries -/// ([`predefined`]) or one of the others ([`stand_in`]), in its horizontal (`-H`) or vertical -/// (`-V`) form. A name ending in an Identity CMap is not read as one, nor is one that ends in an -/// unknown CMap name with an encoding part (`UniFoo-UTF8-H`), which would otherwise end in `H`. -fn composite_font(name: &str) -> Option<(&str, &str)> { - if !(name.ends_with("-H") || name.ends_with("-V")) { - return None; - } - // The longest CMap name first: `83pv-RKSJ-H` before `H`. - // No predefined CMap name is longer than 32 bytes. - for (at, _) in name.match_indices('-').filter(|(at, _)| name.len() - at <= 33) { - let (Some(base), Some(cmap)) = (name.get(..at).filter(|b| !b.is_empty()), name.get(at + 1..)) else { continue }; - if matches!(cmap, "Identity-H" | "Identity-V") { - return None; - } - let encoding_part = - base.rsplit('-').next().is_some_and(|part| ["UCS2", "UTF8", "UTF16", "UTF32", "HW", "EUC", "RKSJ", "B5", "UHC", "Johab"].contains(&part)); - if matches!(cmap, "H" | "V") && encoding_part { - return None; - } - let vertical_of_predefined = || cmap.strip_suffix('V').is_some_and(|stem| predefined(&format!("{stem}H")).is_some()); - let other = || cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")).is_some_and(|stem| stand_in(stem).is_some()); - if unicode_cmap(cmap).is_some() || predefined(cmap).is_some() || vertical_of_predefined() || other() { - return Some((base, cmap)); - } - } - None -} - /// An operator's `N` operands, the last `N` values before it, when each is a finite number. fn nums(vals: &[V]) -> Option<[f64; N]> { let operands = vals.get(vals.len().checked_sub(N)?..)?; diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 4f667fbe45..91e8975e90 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -55,7 +55,9 @@ pub(super) enum NotOne { /// it applies to, even within a patch; a mesh starts grey. Besides the device spaces it may be a /// named colour, `[c m y k /DeviceCMYK (name) /Process]` (or `/Spot`), or several process or spot /// inks, `[[ink] [ink] … n /NChannel]` (each ink `[c m y k /DeviceCMYK (name) /Separation]`). A -/// corner gives a named colour's tint (1 is the full colour), or each ink's in order. +/// corner gives a named color's tint (1 is the full color), or each ink's, process and spot inks +/// alike, the last ink listed first: under `[[Yellow] [Magenta] [Cyan] 3 /NChannel]`, `[0 0 1 …]` +/// is full yellow. #[derive(Debug, Clone, Default, PartialEq)] enum Space { #[default] @@ -113,10 +115,11 @@ impl Space { Space::Cmyk => Color::cmyk(u(0)?, u(1)?, u(2)?, u(3)?), Space::Inks(inks) => match inks.as_slice() { [one] => one.tinted(u(0)?), - // Several inks overprint: their CMYK at their tints, added up. + // Several inks overprint: their CMYK at their tints, added up. The tints come in + // the opposite order to the inks. many => { let mut sum = [0.0f32; 4]; - for (i, ink) in many.iter().enumerate() { + for (i, ink) in many.iter().rev().enumerate() { let Color::Cmyk { c, m, y, k } = *ink else { return None }; let t = u(i)?; for (s, v) in sum.iter_mut().zip([c, m, y, k]) { @@ -911,7 +914,8 @@ mod tests { let mut reader = MeshReader::default(); square(&mut reader, [&[0.25, 1.0], &[0.0, 0.0], &[1.0, 1.0], &[0.0, 0.0]], [vec![(channels(2.0), "CS")], vec![], vec![], vec![]]); assert!(!reader.unread); - assert_color(reader.patches[0].points[0].color, Color::cmyk(0.0, 1.0, 0.25, 0.0)); + // The tints come last ink first: 0.25 Magenta, 1 Yellow. + assert_color(reader.patches[0].points[0].color, Color::cmyk(0.0, 0.25, 1.0, 0.0)); assert_color(reader.patches[0].points[3].color, Color::cmyk(0.0, 1.0, 1.0, 0.0)); // An ink count that doesn't match its inks, or an ink in a space not read. @@ -923,6 +927,51 @@ mod tests { } } + /// `/NChannel` inks take a corner's tints in the opposite order to their listing, whatever + /// order the inks are listed in, spot inks included: under Yellow, Magenta, Cyan `0 0 1` is + /// full yellow and `1 0.5 0` full cyan with half magenta; under Cyan, Magenta, Yellow `0 0 1` + /// is full cyan; under a spot ink and Cyan, `0.5 1` is the full spot ink with half cyan. + #[test] + fn inks_take_their_tints_last_listed_first() { + let ink = |c: [f64; 4], name: &str| { + let mut v: Vec = c.iter().map(|x| V::Num(*x)).collect(); + v.extend([V::Name("DeviceCMYK".into()), V::Str(name.as_bytes().to_vec()), V::Name("Separation".into())]); + V::Arr(v) + }; + let channels = |inks: Vec| { + let n = inks.len() as f64; + let mut a = inks; + a.extend([V::Num(n), V::Name("NChannel".into())]); + V::Arr(a) + }; + let (yellow, magenta, cyan) = (ink([0.0, 0.0, 1.0, 0.0], "Yellow"), ink([0.0, 1.0, 0.0, 0.0], "Magenta"), ink([1.0, 0.0, 0.0, 0.0], "Cyan")); + let rose = ink([0.1, 0.6, 0.4, 0.2], "Rose"); + // Two corners' tints (then opacity) under the inks, and the colors they give. + let check = |inks: Vec, a: &[f64], b: &[f64], want_a: Color, want_b: Color| { + let mut reader = MeshReader::default(); + square(&mut reader, [a, b, a, b], [vec![(channels(inks), "CS")], vec![], vec![], vec![]]); + assert!(!reader.unread); + let points = &reader.patches[0].points; + assert_color(points[0].color, want_a); + assert_color(points[2].color, want_b); + }; + check( + vec![yellow.clone(), magenta.clone(), cyan.clone()], + &[0.0, 0.0, 1.0, 1.0], + &[1.0, 0.5, 0.0, 1.0], + Color::cmyk(0.0, 0.0, 1.0, 0.0), + Color::cmyk(1.0, 0.5, 0.0, 0.0), + ); + check( + vec![cyan.clone(), magenta, yellow], + &[0.0, 0.0, 1.0, 1.0], + &[1.0, 0.5, 0.0, 1.0], + Color::cmyk(1.0, 0.0, 0.0, 0.0), + Color::cmyk(0.0, 0.5, 1.0, 0.0), + ); + check(vec![rose, cyan], &[0.5, 1.0, 1.0], &[1.0, 0.0, 1.0], Color::cmyk(0.6, 0.6, 0.4, 0.2), Color::cmyk(1.0, 0.0, 0.0, 0.0)); + } + /// A corner holding anything but numbers is unread: skipping it would shift the numbers after /// it into its colour and opacity (two inks' tints `0.25 /bad 0.5`, read as `0.25 0.5` and no /// opacity). diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index f7df4f35d6..911d8340cc 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1259,7 +1259,7 @@ mod tests { 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 want = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: vectorcraft_doc::live::WARP_NET }; 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""); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index eb3d73c691..ad7f266036 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1244,9 +1244,9 @@ impl<'a> Reader<'a> { None => None, }; let pos = if vertical { p.x } else { p.y }; - pos.is_finite().then_some(Guide { vertical, pos, artboard, layer: None }) + pos.is_finite().then_some(Guide { artboard, ..Guide::new(vertical, pos) }) }; - take_ruler_guides(&mut doc.layers, &pick, &mut doc.guides, 0); + take_ruler_guides(&mut doc.layers, &pick, 0); } let mut brushes = self.brush_library(); if let Some((lib, _)) = &brushes { @@ -1429,9 +1429,9 @@ fn ruler_guide(a: Point, b: Point, centre: Option<(f64, f64)>, boards: &[Rect]) } } -/// Moves the children of the layers and sublayers of `nodes` that `pick` makes a guide of into -/// `guides`, each on its layer. -fn take_ruler_guides(nodes: &mut [Arc], pick: &dyn Fn(NodeId) -> Option, guides: &mut Vec, depth: usize) { +/// Makes the children of the layers and sublayers of `nodes` that `pick` makes a guide of into +/// ruler guide nodes with the same ids, moved to the top of their layer in their order. +fn take_ruler_guides(nodes: &mut [Arc], pick: &dyn Fn(NodeId) -> Option, depth: usize) { if depth > MAX_DEPTH { return; } @@ -1439,16 +1439,17 @@ fn take_ruler_guides(nodes: &mut [Arc], pick: &dyn Fn(NodeId) -> Option { - guides.push(Guide { layer: Some(id), ..g }); + guides.push(Arc::new(Node::new(k.id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }))); false } None => true, }); - take_ruler_guides(kids, pick, guides, depth + 1); + take_ruler_guides(kids, pick, depth + 1); + kids.extend(guides); } } diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index f15744f30c..ef661c1446 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -1159,6 +1159,7 @@ fn effect(f: &Filter, under: Under) -> Option { "horizontal": pct("DeformHoriz"), "vertical": pct("DeformVert"), "orientation": if flag("Rotate") { "vertical" } else { "horizontal" }, + "version": vectorcraft_doc::live::WARP_NET, }), ) } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index d39a87b5c0..47086ca171 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -495,6 +495,8 @@ fn a_stack_of_fills_with_effects_of_their_own_is_read_as_itself() { // The warp is the whole object's; the characters paint below every item. let [warp] = st.effects.as_slice() else { panic!("{:?}", st.effects) }; assert_eq!((warp.id.as_str(), &warp.params["bend"], &warp.params["orientation"]), ("warp.arch", &json!(5.0), &json!("horizontal"))); + // A file's warp bends as its style's Bézier net. + assert_eq!(warp.params["version"], json!(vectorcraft_doc::live::WARP_NET)); assert_eq!(st.contents_index, None); } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index c04d06c6ab..8fa0a58346 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use kurbo::{Affine, Point, Rect}; use vectorcraft_color::gradient::GradientKind; use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::live::WARP_NET; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Guide, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; use super::*; @@ -62,9 +63,14 @@ fn arrays_nested_past_the_depth_limit_are_refused() { assert!(nested(100_000)); } -/// The children of the first layer. +/// The children of the first layer, its ruler guides left out. fn art(doc: &Document) -> Vec> { - doc.layers.first().and_then(|l| l.children()).cloned().unwrap_or_default() + doc.layers.first().and_then(|l| l.children()).into_iter().flatten().filter(|c| !c.is_ruler_guide()).cloned().collect() +} + +/// The ruler guides of `doc` by their line, artboard and layer. +fn guide_lines(doc: &Document) -> Vec { + doc.ruler_guides().into_iter().map(|g| Guide { artboard: g.artboard, layer: g.layer, ..Guide::new(g.vertical, g.pos) }).collect() } fn fill(n: &Node) -> Paint { @@ -7398,15 +7404,16 @@ fn a_warp_envelope_opens_live() { for (style, bend, h, v, rotate, id) in [(1, 0.5, 0.0, 0.0, 0, "arc"), (1, 0.5, -0.2, 0.3, 1, "arc"), (8, 0.5, 0.0, 0.0, 0, "flag"), (15, 0.5, 0.0, 0.0, 0, "twist")] { - let want = EnvelopeKind::Warp { style: id.into(), bend: bend * 100.0, h: h * 100.0, v: v * 100.0, horizontal: rotate == 0 }; + let want = + EnvelopeKind::Warp { style: id.into(), bend: bend * 100.0, h: h * 100.0, v: v * 100.0, horizontal: rotate == 0, version: WARP_NET }; let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(style, bend, h, v, rotate), &envelope_content(), 1, &drawn_content(&want)); let r = read_ok(&layer(&body)); let a = art(&r.doc); assert_eq!(a.len(), 1, "{a:#?}"); let (content, kind, fidelity, editing, options) = live_envelope(&a[0]); - let EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal } = kind else { panic!("{kind:?}") }; - assert_eq!((s.as_str(), *horizontal), (id, rotate == 0)); + let EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal, version } = kind else { panic!("{kind:?}") }; + assert_eq!((s.as_str(), *horizontal, *version), (id, rotate == 0, WARP_NET)); assert!([(*b, bend), (*dh, h), (*dv, v)].iter().all(|(got, f)| (got - f * 100.0).abs() < 1e-9), "{kind:?}"); assert_eq!((fidelity, editing, options), (50.0, false, vectorcraft_doc::live::EnvelopeOptions::NEW)); assert_eq!(content.len(), 1, "{content:#?}"); @@ -7438,7 +7445,7 @@ fn warp_envelopes_read_every_style() { "twist", ]; for (n, id) in ids.iter().enumerate() { - let want = EnvelopeKind::Warp { style: (*id).into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let want = EnvelopeKind::Warp { style: (*id).into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; let keys = warp_keys(n as u32 + 1, 0.3, 0.0, 0.0, 0); let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &envelope_content(), 1, &drawn_content(&want)))); let a = art(&r.doc); @@ -7969,7 +7976,7 @@ fn an_envelope_that_doesnt_read_keeps_its_drawn_art() { #[test] fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { use vectorcraft_doc::live::EnvelopeKind; - let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; let body = 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(&other)); let r = read_ok(&layer(&body)); let a = art(&r.doc); @@ -7984,7 +7991,7 @@ fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { fn a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { use vectorcraft_doc::live::EnvelopeKind; const WHITE: &str = "0 0 0 0 1 1 1 Xa\n"; - let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true, version: WARP_NET }; let content = envelope_content().replace(RED, WHITE); let drawn = drawn_content(&other).replace(RED, WHITE); let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &content, 1, &drawn); @@ -8459,17 +8466,16 @@ fn canvas_wide_guide_paths_are_ruler_guides_of_their_layer() { ); let doc = read(canvas_stream(&layer(&body)).as_bytes()).unwrap().doc; let top = &doc.layers[0]; - let kids = top.children().unwrap(); + let kids = art(&doc); assert_eq!(kids.len(), 2, "the square and the sublayer"); assert!(matches!(kids[0].kind, NodeKind::Path { guide: false, .. })); let sub = &kids[1]; - assert!(sub.children().unwrap().is_empty()); - let want = [ - Guide { vertical: false, pos: 60.0, artboard: None, layer: Some(top.id) }, - Guide { vertical: true, pos: 25.0, artboard: None, layer: Some(top.id) }, - Guide { vertical: false, pos: 10.0, artboard: None, layer: Some(sub.id) }, - ]; - assert_eq!(doc.guides, want); + assert!(sub.children().unwrap().iter().all(|c| c.is_ruler_guide())); + let at = |vertical, pos, layer| Guide { layer: Some(layer), ..Guide::new(vertical, pos) }; + let want = [at(false, 60.0, top.id), at(true, 25.0, top.id), at(false, 10.0, sub.id)]; + assert_eq!(guide_lines(&doc), want); + // The guides sit above the layers' art. + assert!(top.children().unwrap()[2..].iter().all(|c| c.is_ruler_guide())); } /// #779: a straight `(N) *` guide path from edge to edge of one artboard is a ruler guide of that @@ -8478,7 +8484,7 @@ fn canvas_wide_guide_paths_are_ruler_guides_of_their_layer() { fn artboard_wide_guide_paths_are_ruler_guides_of_their_artboard() { // The crop marks' artboard, 0 0 200 100. let doc = read(canvas_stream(&layer(&guide_line(0.0, 30.0, 200.0, 30.0, "N"))).as_bytes()).unwrap().doc; - assert_eq!(doc.guides, [Guide { vertical: false, pos: 70.0, artboard: Some(1), layer: Some(doc.layers[0].id) }]); + assert_eq!(guide_lines(&doc), [Guide { artboard: Some(1), layer: Some(doc.layers[0].id), ..Guide::new(false, 70.0) }]); assert!(art(&doc).is_empty()); // The second of two artboards: art space x 400 to 600, y -150 to 0. let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ @@ -8487,7 +8493,7 @@ fn artboard_wide_guide_paths_are_ruler_guides_of_their_artboard() { %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; let doc = read_ok(&format!("{boards}{}", layer(&guide_line(500.0, 0.0, 500.0, -150.0, "N")))).doc; assert_eq!(doc.artboards[1].id, 2); - assert_eq!(doc.guides, [Guide { vertical: true, pos: 500.0, artboard: Some(2), layer: Some(doc.layers[0].id) }]); + assert_eq!(guide_lines(&doc), [Guide { artboard: Some(2), layer: Some(doc.layers[0].id), ..Guide::new(true, 500.0) }]); } /// Guide paths that aren't ruler guides stay guide paths: `(S) *` ones (guides made from objects), @@ -8506,7 +8512,7 @@ fn other_guide_paths_stay_guide_paths() { ]; for body in cases { let doc = read(canvas_stream(&layer(&body)).as_bytes()).unwrap().doc; - assert!(doc.guides.is_empty(), "{body}"); + assert!(doc.ruler_guides().is_empty(), "{body}"); assert_eq!(art(&doc).len(), 1, "{body}"); } } diff --git a/crates/eps/src/import/cid.rs b/crates/eps/src/import/cid.rs index e2ad169f79..a54c11ae2b 100644 --- a/crates/eps/src/import/cid.rs +++ b/crates/eps/src/import/cid.rs @@ -18,6 +18,7 @@ use vectorcraft_geom::BezPath; use super::interp::{Interp, matrix_obj}; use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err}; +use super::predefined_cmap::Unicode; /// Most codespace ranges, character and notdef mappings a CMap may hold. const MAX_RANGES: usize = 1 << 16; @@ -210,16 +211,6 @@ fn number(data: &[u8], at: usize, n: usize) -> Option { (n <= 8).then(|| bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b))) } -/// How a predefined Unicode CMap's codes encode their characters. -#[derive(Clone, Copy, PartialEq, Debug)] -pub(super) enum Unicode { - /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. - Utf16, - Utf8, - /// Four bytes, the high byte first. - Utf32, -} - /// The encoding of predefined Unicode CMap `name` and whether it is vertical: one of Adobe's /// public CMap resources whose name says its codes are Unicode: `Uni` and a character /// collection, then `-UCS2`, `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), @@ -246,18 +237,6 @@ pub(super) fn unicode_cmap(name: &str) -> Option<(Unicode, bool)> { Some((form, vertical)) } -/// The characters show string `s` encodes in Unicode form `form` (invalid codes left out). -pub(super) fn unicode_text(s: &[u8], form: Unicode) -> String { - match form { - Unicode::Utf16 => { - let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)); - char::decode_utf16(units).filter_map(Result::ok).collect() - } - Unicode::Utf8 => String::from_utf8_lossy(s).chars().filter(|c| *c != char::REPLACEMENT_CHARACTER).collect(), - Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(), - } -} - /// A predefined Identity CMap: two-byte codes, each the CID of its own value; vertical for /// `Identity-V`. pub(super) fn identity(name: &str, vertical: bool) -> Obj { @@ -417,8 +396,13 @@ impl Interp<'_> { return Ok(d.clone()); } let text = name.text().map(|t| t.to_string()).unwrap_or_default(); - match unicode_cmap(&text) { - Some((_, vertical)) => { + // Another predefined CMap the file doesn't define, without its mappings: its codes are + // read by its name when type is set (see `text`). + let predefined = unicode_cmap(&text) + .map(|(_, vertical)| vertical) + .or_else(|| super::predefined_cmap::known(&text).then(|| super::predefined_cmap::vertical(&text))); + match predefined { + Some(vertical) => { let mut d = Dict::new(); d.insert(Key::name("CMapName"), Obj::name(&text)); d.insert(Key::name("CMapType"), Obj::Int(1)); diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index e3268b240a..79dce67ea0 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -131,6 +131,10 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { } } +/// Most pixels a DCTDecode JPEG may have: twice the most an image is read with, so every image that +/// was read before is still read. +const MAX_DCT_PIXELS: u64 = 1 << 27; + /// A JPEG's pixels (gray, RGB or CMYK, 8 bits) with its channel count, and how many bytes of /// `raw` it took. A CMYK JPEG gives its samples as stored, for the image's Decode array to read /// (Adobe's CMYK JPEGs store them inverted, which a Decode array of `[1 0 1 0 1 0 1 0]` undoes). @@ -143,6 +147,12 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { { return Ok((inks.data.into_iter().map(|v| 255 - v).collect(), end, 4)); } + // The header's size is checked before the decoder allocates for it (a progressive JPEG keeps its + // coefficients besides its output). + let size = image::ImageReader::with_format(std::io::Cursor::new(jpeg), image::ImageFormat::Jpeg).into_dimensions(); + if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_DCT_PIXELS) { + return Err(PsError::Limit("decoded data is too large")); + } let img = image::load_from_memory_with_format(jpeg, image::ImageFormat::Jpeg).map_err(|_| PsError::Ps("ioerror", "DCTDecode".into()))?; if img.color().channel_count() == 1 { Ok((img.to_luma8().into_raw(), end, 1)) } else { Ok((img.to_rgb8().into_raw(), end, 3)) } } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 33f394482a..04e5431d30 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -7,6 +7,9 @@ use super::{ /// Most bytes one filter or image reads. pub(super) const MAX_DATA: usize = 1 << 28; + +/// Most data sources one image may name (a DeviceN space has up to 32 components). +const MAX_SOURCES: usize = 32; /// The longest chain of filters over one pending file (real programs stack two or three). const MAX_FILTER_CHAIN: usize = 64; @@ -389,6 +392,25 @@ impl Interp<'_> { /// Decode the filters a file waits to run over the data the program reads, from where it is /// now in the file they were made over: a file being run, or the program's own file. pub(in super::super) fn materialize(&mut self, f: &Rc>) -> Res { + let input = match &*f.borrow() { + Stream::Pending { from: Some(r), .. } => match &*r.borrow() { + Stream::Buf { data, pos, .. } => data.len().saturating_sub(*pos), + _ => 0, + }, + Stream::Pending { from: None, .. } => self.lex.data().len(), + _ => return Ok(()), + }; + let r = self.decode_pending(f); + // A decode that failed is over: the stream is empty from now on, and the work it did is + // charged, so a program that catches the error can't have it run again and again. + if r.is_err() && matches!(&*f.borrow(), Stream::Pending { .. }) { + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + self.spend_bytes(input)?; + } + r + } + + fn decode_pending(&mut self, f: &Rc>) -> Res { let (chain, from) = match &*f.borrow() { Stream::Pending { chain, from } => (chain.clone(), from.clone()), _ => return Ok(()), @@ -663,6 +685,8 @@ impl Interp<'_> { let multi = get("MultipleDataSources").is_some_and(|o| matches!(o, Obj::Bool(true))); let sources = match (get("DataSource"), multi) { (None, _) => vec![], + // An image has a data source for each of its components, so many more is no image: refused before any copy. + (Some(Obj::Array { items, exec: false }), true) if items.len() > MAX_SOURCES => return ps_err("rangecheck", "DataSource"), (Some(Obj::Array { items, exec: false }), true) => items.borrow().iter().map(source).collect::>>()?, (Some(src), _) => vec![source(&src)?], }; diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 4920b1d66d..58708bb97e 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -92,6 +92,9 @@ pub(crate) struct Interp<'a> { pub cid_subrs: super::cid::CidSubrs, /// The font number `usefont` gave the CMap mappings that follow. pub cmap_font: i64, + /// The predefined CMaps type was set in so far, by name, with how their strings decode + /// (`None` when one can't be read; see `text`). + pub predefined_cmaps: Vec<(Rc, Option>)>, pub g: GState, pub saved: Vec, pub out: Out, @@ -232,6 +235,7 @@ impl<'a> Interp<'a> { cff: vec![], cid_subrs: vec![], cmap_font: 0, + predefined_cmaps: vec![], type42_counted: HashSet::new(), g, saved: vec![], @@ -550,10 +554,30 @@ impl<'a> Interp<'a> { /// An object as the scanner gives it: with `immediate`, its `//name`s replaced by their /// values (down through procedures), as they are when read. - pub fn scanned(&self, o: Obj, immediate: bool) -> Res { + pub fn scanned(&mut self, o: Obj, immediate: bool) -> Res { + // Every scan builds a fresh string or procedure, so a loop that rescans one text is charged + // for each copy it keeps, not only for the text. + self.charge_scanned(&o, 0)?; if immediate { self.resolve(o, 0) } else { Ok(o) } } + /// Count the storage of the string or procedure the scanner just made against [`MAX_MEMORY`], + /// and the time to build it. + fn charge_scanned(&mut self, o: &Obj, depth: usize) -> Res { + match o { + Obj::Str(s) => { + self.alloc(s.len())?; + self.spend_bytes(s.len()) + } + Obj::Array { items, .. } if depth < MAX_DEPTH as usize => { + self.alloc(items.len().saturating_mul(std::mem::size_of::()))?; + self.spend_bytes(items.len())?; + items.borrow().iter().try_for_each(|i| self.charge_scanned(i, depth + 1)) + } + _ => Ok(()), + } + } + fn resolve(&self, o: Obj, depth: usize) -> Res { match o { Obj::Exec(n) if n.starts_with(IMMEDIATE) => { diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 31cd90d79b..c86cdb9516 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1669,7 +1669,7 @@ fn page_boards(doc: &Document, visible: &Document, first: usize, pages: &[Rect]) /// Drops the guides of artboards `doc` no longer has: an artboard guide goes with its artboard. fn drop_guides_off_boards(doc: &mut Document) { let kept: Vec = doc.artboards.iter().map(|a| a.id).collect(); - doc.guides.retain(|g| g.artboard.is_none_or(|id| kept.contains(&id))); + doc.retain_guides(&mut vectorcraft_doc::Selection::default(), |g| g.artboard.is_none_or(|id| kept.contains(&id))); } /// Draw `doc`'s layers, artboards and guides `k` times as large, from the origin, with their @@ -1682,13 +1682,12 @@ pub(crate) fn scale_document(doc: &mut Document, k: f64, styles: bool) { let layer = Arc::make_mut(layer); layer.transform(a, scaling); scale_wrap_offsets(layer, k); + // A transform leaves ruler guides where they are: their positions scale here. + layer.map_ruler_guide_positions(&mut |_, pos| *pos *= k); } for board in &mut doc.artboards { board.rect = a.transform_rect_bbox(board.rect); } - for guide in &mut doc.guides { - guide.pos *= k; - } if styles { for g in doc.graphic_styles.iter_mut() { g.appearance.scale_strokes(k); diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 5b87a03c7d..34f458f328 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -122,7 +122,7 @@ pub(super) fn comparison_samples(doc: &Document) -> u32 { let (mut images, mut vector) = (false, false); doc.walk(|n| match n.kind { NodeKind::Image(_) => images = true, - NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Path { clipping: true, .. } => {} + NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Path { clipping: true, .. } | NodeKind::RulerGuide { .. } => {} _ => vector = true, }); if images && !vector { 4 } else { 1 } diff --git a/crates/eps/src/import/predefined_cmap.rs b/crates/eps/src/import/predefined_cmap.rs new file mode 100644 index 0000000000..1a9b3b95be --- /dev/null +++ b/crates/eps/src/import/predefined_cmap.rs @@ -0,0 +1,358 @@ +//! Strings in fonts over Adobe's predefined CMaps () +//! read as characters: the codes of a predefined Unicode CMap are the characters; those of the +//! others map to CIDs of a character collection, whose CID → Unicode CMap gives the characters. +//! Used by legacy `.ai` type in composite fonts and by type in CID-keyed fonts found by name. + +use craft_pdf::interpret::hayro_cmap::{BfString, CMap, CMapName, load_embedded}; + +/// How a composite font's strings decode. +#[derive(Debug)] +pub(super) enum CMapCodes { + /// By a predefined CMap's codes to CIDs, then by its character collection's CID → Unicode CMap; + /// with `high_bit`, each byte 0x21 to 0x7E gets its high bit set first. `space` is the CMap's + /// code space ([`code_space`]). + Cids { codes: Box, unicode: Box, high_bit: bool, space: Option }, + /// A predefined Unicode CMap: the codes are the characters. + Unicode(Unicode), +} + +/// A CMap's code space: ranges of codes, each given by its lowest and highest code, both with the +/// code's length in bytes. +type CodeSpace = &'static [(&'static [u8], &'static [u8])]; + +/// What control byte `b` is in a composite font's string: `\r` a paragraph break, `\t` a tab. +fn control(b: u8) -> Option { + match b { + b'\r' => Some('\n'), + b'\t' => Some('\t'), + _ => None, + } +} + +impl CMapCodes { + /// The characters of string `bytes`, leaving out codes the CMaps don't map; a `\r` is a + /// paragraph break and a `\t` a tab (also as a byte left over after the last whole code of a + /// UTF-16 or UTF-32 string). + pub(super) fn decode(&self, bytes: &[u8]) -> String { + let mut text = String::new(); + self.each_code(bytes, |_, chars| text.extend(chars)); + text + } + + /// The codes of string `bytes`, each with its value and the characters it stands for (as + /// [`Self::decode`] reads them; none for a code the CMaps don't map, or for a byte that starts + /// no code, which counts as a code of its own). + pub(super) fn codes(&self, bytes: &[u8]) -> Decoded { + let mut out = Decoded::default(); + self.each_code(bytes, |code, chars| out.push(code, chars)); + out + } + + /// Calls `emit` with each code of string `bytes` in turn ([`Self::codes`]): its value and the + /// characters it stands for. + fn each_code(&self, bytes: &[u8], mut emit: impl FnMut(u32, &mut dyn Iterator)) { + let value = |b: &[u8]| b.iter().fold(0u32, |c, &b| c << 8 | u32::from(b)); + let (codes, unicode, high_bit, space) = match self { + Self::Unicode(form) => { + let unit = match form { + Unicode::Utf16 => 2, + Unicode::Utf8 => 1, + Unicode::Utf32 => 4, + }; + let (whole, rest) = bytes.split_at_checked(bytes.len() - bytes.len() % unit).unwrap_or((bytes, &[])); + unicode_codes(whole, *form, |code, c| emit(value(code), &mut c.map(|c| if c == '\r' { '\n' } else { c }).into_iter())); + if let Some(&last) = rest.last() { + emit(value(rest), &mut control(last).into_iter()); + } + return; + } + Self::Cids { codes, unicode, high_bit, space } => (codes, unicode, *high_bit, space), + }; + // A code's value is that of the string's bytes, also where they're read in their EUC form. + let original = bytes; + let value_at = |at: usize, len: usize| original.get(at..at + len).map_or(0, value); + let euc: Vec; + let bytes = if high_bit { + euc = bytes.iter().map(|&b| if (0x21..0x7f).contains(&b) { b | 0x80 } else { b }).collect(); + euc.as_slice() + } else { + bytes + }; + let mut at = 0; + while let Some(&first) = bytes.get(at) { + // VectorCraft reads a 0x0D byte as a paragraph break and a 0x09 byte as a tab in every + // CMap, as in other fonts' strings, including the row-and-cell CMaps, whose code space + // has no one-byte codes. + if let Some(control) = control(first) { + emit(value_at(at, 1), &mut Some(control).into_iter()); + at += 1; + continue; + } + let rest = bytes.get(at..).unwrap_or_default(); + let code = |len: u8| rest.get(..usize::from(len)).map(value); + let found = match space { + // The code is as long as the code space range it falls in; a byte that starts no + // code in the code space is skipped. + Some(space) => code_len(space, rest).and_then(|len| code(len).map(|c| (len, codes.lookup_cid_code(c, len)))), + None => (1..=4u8).find_map(|len| Some((len, Some(codes.lookup_cid_code(code(len)?, len)?)))), + }; + let Some((len, cid)) = found else { + emit(value_at(at, 1), &mut None.into_iter()); + at += 1; + continue; + }; + let value = value_at(at, usize::from(len)); + at += usize::from(len); + // A code the CMap leaves out stands for no character. + match cid.and_then(|cid| unicode.lookup_bf_string(cid)) { + // A one-byte Roman code whose CID the table gives as a combining mark alone (0x7E in + // the Mac Shift-JIS CMaps, U+0303): the ASCII character, as Adobe's cid2code.txt lists first. + Some(BfString::Char('\u{300}'..='\u{36f}')) if len == 1 && (0x20..0x7f).contains(&first) => { + emit(value, &mut Some(char::from(first)).into_iter()) + } + Some(BfString::Char(c)) if c != char::REPLACEMENT_CHARACTER => emit(value, &mut Some(c).into_iter()), + Some(BfString::String(s)) => emit(value, &mut s.chars().filter(|c| *c != char::REPLACEMENT_CHARACTER)), + _ => emit(value, &mut None.into_iter()), + } + } + } +} + +/// A string's characters, and its codes: each code's value and how many of the characters it +/// stands for, in order. +#[derive(Debug, Default)] +pub(super) struct Decoded { + pub text: String, + pub codes: Vec<(u32, usize)>, +} + +impl Decoded { + /// Code `code`, standing for characters `chars`. + pub(super) fn push(&mut self, code: u32, chars: impl IntoIterator) { + let before = self.text.len(); + self.text.extend(chars); + let n = self.text.get(before..).map_or(0, |added| added.chars().count()); + self.codes.push((code, n)); + } +} + +/// How strings in a font over predefined CMap `cmap` decode; `None` when the CMap can't be read. +pub(super) fn codes(cmap: &str) -> Option { + match unicode_cmap(cmap) { + Some(form) => Some(CMapCodes::Unicode(form)), + None => cid_codes(cmap), + } +} + +/// How a predefined Unicode CMap's codes encode their characters. +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Unicode { + /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. + Utf16, + Utf8, + /// Four bytes, the high byte first. + Utf32, +} + +/// The encoding of predefined Unicode CMap `name`: `Uni` and a character collection, then `-UCS2`, +/// `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), then `-H` or `-V` +/// (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: ). +fn unicode_cmap(name: &str) -> Option { + let rest = name.strip_suffix("-H").or_else(|| name.strip_suffix("-V"))?; + let rest = rest.strip_suffix("-HW").unwrap_or(rest); + let (collection, form) = rest.rsplit_once('-')?; + let collections = ["UniJIS", "UniJISPro", "UniJIS2004", "UniJISX0213", "UniJISX02132004", "UniHojo", "UniGB", "UniCNS", "UniKS", "UniAKR"]; + if !collections.contains(&collection) { + return None; + } + match form { + "UCS2" | "UTF16" => Some(Unicode::Utf16), + "UTF8" => Some(Unicode::Utf8), + "UTF32" => Some(Unicode::Utf32), + _ => None, + } +} + +/// Calls `out` with each code of string `s` in Unicode form `form` in turn, and the character it +/// encodes (none for an invalid code: a lone surrogate, a byte that starts no UTF-8 character, a +/// value past U+10FFFF). +fn unicode_codes(s: &[u8], form: Unicode, mut out: impl FnMut(&[u8], Option)) { + match form { + Unicode::Utf16 => { + let unit = |i: usize| s.get(i..i + 2).and_then(|b| <[u8; 2]>::try_from(b).ok()).map(u16::from_be_bytes); + let mut at = 0; + while let Some(u) = unit(at) { + let next = unit(at + 2); + let pair = next.filter(|n| (0xd800..0xdc00).contains(&u) && (0xdc00..0xe000).contains(n)); + let len = if pair.is_some() { 4 } else { 2 }; + let c = char::decode_utf16([u].into_iter().chain(pair)).next().and_then(Result::ok); + out(s.get(at..at + len).unwrap_or_default(), c); + at += len; + } + } + Unicode::Utf8 => { + let mut at = 0; + for chunk in s.utf8_chunks() { + for c in chunk.valid().chars() { + out(s.get(at..at + c.len_utf8()).unwrap_or_default(), Some(c)); + at += c.len_utf8(); + } + for _ in chunk.invalid() { + out(s.get(at..at + 1).unwrap_or_default(), None); + at += 1; + } + } + } + Unicode::Utf32 => { + for b in s.as_chunks::<4>().0 { + out(b.as_slice(), char::from_u32(u32::from_be_bytes(*b))); + } + } + } +} + +/// Predefined CMap `name` among those VectorCraft carries, leaving out the Identity CMaps, whose +/// codes are CIDs of no known character collection. +fn predefined(name: &str) -> Option> { + match CMapName::from_bytes(name.as_bytes()) { + CMapName::Custom(_) | CMapName::IdentityH | CMapName::IdentityV => None, + name => Some(name), + } +} + +/// Adobe's predefined CMaps that VectorCraft doesn't carry, by name without `-H` or `-V` +/// (): the nearest carried CMap with the same +/// code space, and whether each byte of a row-and-cell code gets its high bit set first (the EUC +/// form of the same code; `GB-H`, `CNS1-H` and `KSC-H` have no one-byte codes, their code space +/// is `<2121>` to `<7E7E>`); `None` for those no carried CMap reads. +fn stand_in(stem: &str) -> Option> { + Some(match stem { + "RKSJ" | "78-RKSJ" | "78ms-RKSJ" => Some(("90ms-RKSJ-H", false)), + "78-EUC" => Some(("EUC-H", false)), + "78" | "Add" | "Ext" | "NWP" => Some(("H", false)), + "GB" => Some(("GB-EUC-H", true)), + "CNS1" => Some(("CNS-EUC-H", true)), + "KSC" => Some(("KSC-EUC-H", true)), + "B5" => Some(("ETen-B5-H", false)), + "ETHK-B5" | "HKdla-B5" | "HKdlb-B5" | "HKgccs-B5" | "HKm314-B5" | "HKm471-B5" => Some(("HKscs-B5-H", false)), + "GBT" | "GBT-EUC" | "GBTpc-EUC" | "CNS2" | "KSC-Johab" => None, + _ => return None, + }) +} + +/// Predefined CMap `cmap`'s codes to CIDs, and its character collection's CID → Unicode CMap. A +/// vertical CMap's codes are read with its horizontal CMap when VectorCraft carries that: the two +/// differ only in the CIDs of vertical glyph forms. A CMap VectorCraft doesn't carry is read with +/// its [`stand_in`]. +fn cid_codes(cmap: &str) -> Option { + let read = |name: &str| CMap::parse(load_embedded(predefined(name)?)?, load_embedded); + let horizontal = cmap.strip_suffix('V').map(|stem| format!("{stem}H")); + let stem = cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")); + let (codes, high_bit) = horizontal.iter().map(String::as_str).chain([cmap]).find_map(|n| Some((read(n)?, false))).or_else(|| { + let (name, high_bit) = stand_in(stem?).flatten()?; + Some((read(name)?, high_bit)) + })?; + let table = codes.metadata().character_collection.as_ref()?.family.ucs2_cmap()?; + let unicode = CMap::parse(load_embedded(table)?, load_embedded)?; + // A row-and-cell code read in its EUC form falls in the EUC CMap's code space. + let space = if high_bit { stand_in(stem?).flatten().and_then(|(name, _)| code_space(name)) } else { code_space(cmap) }; + Some(CMapCodes::Cids { codes: Box::new(codes), unicode: Box::new(unicode), high_bit, space }) +} + +/// The code space of predefined CMap `cmap`, as Adobe's CMap files give it +/// (); a CMap's vertical form has its +/// horizontal form's. `None` for a CMap not listed here. +fn code_space(cmap: &str) -> Option { + const RKSJ: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; + const RKSJ_MAC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\xfd", b"\xff"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; + const EUC_JP: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\xa0", b"\x8e\xdf"), (b"\xa1\xa1", b"\xfe\xfe")]; + const ROW_CELL: CodeSpace = &[(b"\x21\x21", b"\x7e\x7e")]; + const EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe")]; + const GB_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\xa1", b"\xfc\xfe")]; + const GBK: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x40", b"\xfe\xfe")]; + const GBK2K: CodeSpace = &[(b"\x00", b"\x7f"), (b"\x81\x40", b"\xfe\xfe"), (b"\x81\x30\x81\x30", b"\xfe\x39\xfe\x39")]; + const B5_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\x40", b"\xfc\xfe")]; + const B5: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\x40", b"\xfe\xfe")]; + const HKSCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x87\x40", b"\xfe\xfe")]; + const HKDLB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\x40", b"\xfe\xfe")]; + const HKGCCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8a\x40", b"\xfe\xfe")]; + const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")]; + const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")]; + const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")]; + let stem = match cmap { + "H" | "V" => "", + _ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?, + }; + let stem = stem.strip_suffix("-HW").unwrap_or(stem); + Some(match stem { + "83pv-RKSJ" | "90pv-RKSJ" => RKSJ_MAC, + _ if stem.ends_with("RKSJ") => RKSJ, + "EUC" | "78-EUC" => EUC_JP, + "" | "78" | "Add" | "Ext" | "NWP" => ROW_CELL, + "GB-EUC" | "GBT-EUC" | "KSC-EUC" => EUC, + "GBpc-EUC" | "GBTpc-EUC" => GB_PC, + "GBK-EUC" | "GBKp-EUC" => GBK, + "GBK2K" => GBK2K, + "B5pc" => B5_PC, + "B5" | "ETen-B5" | "ETenms-B5" | "HKdla-B5" | "HKm314-B5" | "HKm471-B5" => B5, + "HKscs-B5" | "ETHK-B5" => HKSCS, + "HKdlb-B5" => HKDLB, + "HKgccs-B5" => HKGCCS, + "CNS-EUC" => CNS_EUC, + "KSCpc-EUC" => KSC_PC, + "KSCms-UHC" => UHC, + _ => return None, + }) +} + +/// The length of the code string `bytes` starts with: the length of the code space range whose +/// lowest and highest codes hold each of its bytes between them. `None` when no range does. +fn code_len(space: CodeSpace, bytes: &[u8]) -> Option { + space + .iter() + .filter(|(lo, hi)| bytes.get(..lo.len()).is_some_and(|b| b.iter().zip(lo.iter().zip(hi.iter())).all(|(b, (lo, hi))| (lo..=hi).contains(&b)))) + .map(|(lo, _)| lo.len()) + .min() + .and_then(|len| u8::try_from(len).ok()) +} + +/// Whether `cmap` names a predefined CMap: a predefined Unicode CMap ([`unicode_cmap`]), one of the +/// predefined CMaps VectorCraft carries ([`predefined`]) or one of the others ([`stand_in`]), in +/// its horizontal (`-H`) or vertical (`-V`) form. The Identity CMaps are not among them. +pub(super) fn known(cmap: &str) -> bool { + let vertical_of_predefined = || cmap.strip_suffix('V').is_some_and(|stem| predefined(&format!("{stem}H")).is_some()); + let other = || cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")).is_some_and(|stem| stand_in(stem).is_some()); + unicode_cmap(cmap).is_some() || predefined(cmap).is_some() || vertical_of_predefined() || other() +} + +/// Whether predefined CMap `cmap` is a vertical CMap (`-V`, or the row-and-cell `V`). +pub(super) fn vertical(cmap: &str) -> bool { + cmap == "V" || cmap.ends_with("-V") +} + +/// A composite font's name `base-CMap`: the base font's name and its CMap's name, when that is a +/// predefined CMap ([`known`]). A name ending in an Identity CMap is not read as one, nor is one +/// that ends in an unknown CMap name with an encoding part (`UniFoo-UTF8-H`), which would otherwise +/// end in `H`. +pub(super) fn composite_font(name: &str) -> Option<(&str, &str)> { + if !(name.ends_with("-H") || name.ends_with("-V")) { + return None; + } + // The longest CMap name first: `83pv-RKSJ-H` before `H`. + // No predefined CMap name is longer than 32 bytes. + for (at, _) in name.match_indices('-').filter(|(at, _)| name.len() - at <= 33) { + let (Some(base), Some(cmap)) = (name.get(..at).filter(|b| !b.is_empty()), name.get(at + 1..)) else { continue }; + if matches!(cmap, "Identity-H" | "Identity-V") { + return None; + } + let encoding_part = + base.rsplit('-').next().is_some_and(|part| ["UCS2", "UTF8", "UTF16", "UTF32", "HW", "EUC", "RKSJ", "B5", "UHC", "Johab"].contains(&part)); + if matches!(cmap, "H" | "V") && encoding_part { + return None; + } + if known(cmap) { + return Some((base, cmap)); + } + } + None +} diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index 9a3f5b7511..d4b4efb131 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -28,7 +28,14 @@ pub(super) fn preview(bytes: &[u8], ps: &[u8], frame: Rect) -> Option { epsi(ps).and_then(|img| image_doc(img, frame)).map(|document| Preview { document, what: IMAGE }) } +/// Most pixels a TIFF preview may have: its RGBA copy is four bytes each besides the decoded image. +const MAX_PREVIEW_PIXELS: u64 = 1 << 26; + fn tiff_rgba(tiff: &[u8]) -> Option { + let size = image::ImageReader::with_format(std::io::Cursor::new(tiff), image::ImageFormat::Tiff).into_dimensions(); + if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_PREVIEW_PIXELS) { + return None; + } match image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff) { Ok(img) => Some(img.to_rgba8()), Err(_) => crate::tiff::palette_rgba(tiff), diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index f4edc0ac8f..6a1df810bc 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -1588,3 +1588,40 @@ fn abutting_blocks_of_distinct_colours_stay_apart() { let gaps: String = (0..10).map(|i| format!("{} setgray {} 10 2 80 rectfill ", f64::from(i) / 40.0, 10 + i * 3)).collect(); assert_eq!(objects(&read(&gaps).document).len(), 10); } + +/// A string a program scans again and again (`token`) makes a fresh copy each time, and the copies +/// count against the memory budget. +#[test] +fn rescanned_strings_are_charged() { + let body = "/s 1048576 string def s 0 40 put s 1048575 41 put\n1100 { s token pop pop pop } repeat\n"; + let e = import(&eps(body)).unwrap_err(); + assert!(e.contains("too much memory"), "{e}"); + // A few scans stay far within it. + let r = import(&eps("/s 1048576 string def s 0 40 put s 1048575 41 put\n20 { s token pop pop pop } repeat\n")).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); +} + +/// An image names no more data sources than a color space has components: thousands of references +/// to one string are refused before any is copied. +#[test] +fn an_image_with_thousands_of_data_sources_is_refused() { + let sources = "<80> ".repeat(2048); + let e = import(&eps(&format!( + "/DeviceCMYK setcolorspace << /ImageType 1 /Width 1 /Height 1 /BitsPerComponent 8 \ + /MultipleDataSources true /ImageMatrix [1 0 0 1 0 0] /DataSource [{sources}] >> image" + ))) + .unwrap_err(); + assert!(e.contains("rangecheck") && e.contains("DataSource"), "{e}"); +} + +/// A filter over the program's own file that fails to decode is spent: a program that catches the +/// error and reads again gets the end of the file, not the same decode over again. +#[test] +fn a_failed_filter_decode_is_not_tried_again() { + let body = "/f currentfile /FlateDecode filter def\n/n 0 def 3 { { f read { pop } if } stopped { /n n 1 add def } if } repeat\n\ + n 1 eq { 0 0 10 10 rectfill } if\n"; + let r = import(&eps(body)).unwrap(); + let mut paths = 0; + r.document.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. }))); + assert_eq!(paths, 1, "{:?}", r.warnings); +} diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs index 2b01b2b4f2..9e452c4bf4 100644 --- a/crates/eps/src/import/tests_cid.rs +++ b/crates/eps/src/import/tests_cid.rs @@ -403,6 +403,171 @@ fn named_cidfonts_over_unicode_cmaps_set_their_characters_as_type() { check("/Ryumin-Light-UniJIS-UCS2-H findfont 20 scalefont setfont <00410042> stringwidth pop dup 5 gt exch 40 lt and"); } +/// The text objects of an import. +fn texts(r: &crate::Imported) -> Vec { + all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() +} + +/// A CID-keyed font over one of the other predefined CMaps (Shift-JIS, EUC, GBK, Big Five, UHC, +/// JIS row and cell: ), the file defining +/// neither, its CIDFont only named: the codes are read by that CMap and its character +/// collection's CIDs to Unicode, and set as type in the font of the CIDFont's name, whether +/// found as `CIDFont-CMap` or composed. Codes the CMap doesn't map and control codes are left out. +#[test] +fn named_cidfonts_over_predefined_cmaps_set_their_characters_as_type() { + let cases: &[(&str, &str, &str)] = &[ + // 日 is 0x93FA and 本 0x967B in Shift-JIS. + ("83pv-RKSJ-H", "93fa967b41", "日本A"), + ("90ms-RKSJ-H", "93fa", "日"), + ("EUC-H", "c6fc", "日"), + // JIS row and cell: 日 is 0x467C. + ("H", "467c", "日"), + ("GBK-EUC-H", "d6d0", "中"), + ("B5pc-H", "a4a4", "中"), + ("ETen-B5-H", "a4a4", "中"), + ("KSCms-UHC-H", "c7d1", "한"), + // A CMap read with the nearest carried one: GB 2312 row and cell in EUC form, 中 0x5650. + ("GB-H", "5650", "中"), + // 0x8540 maps to no CID, 0xFD is in no code space range, 0x0D is a control code. + ("90ms-RKSJ-H", "854093fa41fd0d42", "日AB"), + ]; + for (cmap, hex, want) in cases { + let r = super::tests::read(&format!("/Ryumin-Light-{cmap} findfont 20 scalefont setfont 10 20 moveto <{hex}> show")); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{cmap}: {:?}", r.warnings); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), [*want], "{cmap}"); + let style = &t[0].runs[0].style; + assert_eq!((style.font_family.as_str(), style.font_style.as_str(), style.size), ("Ryumin", "Light", 20.0), "{cmap}"); + assert!(!t[0].vertical, "{cmap}"); + } + let r = super::tests::read("/X /GBK-EUC-H [/NotInFile] composefont 20 scalefont setfont 10 20 moveto show"); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "中A"); + // The point moves past the type, along the line. + check("/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont <93fa967b> stringwidth abs 0.01 lt exch dup 5 gt exch 60 lt and and"); +} + +/// Type in a CID-keyed font over a predefined CMap, its CIDFont only named, shown with `ashow`, +/// `widthshow` (matching a code by its value) and `xshow`, is spaced as the operator says: the +/// point moves that far, and the characters' tracking makes up the difference, as for type in a +/// font found by name. Over a vertical CMap the extra space runs down the column. +#[test] +fn named_cidfonts_over_predefined_cmaps_take_the_show_operators_spacing() { + // Measured without painting. + let measured = |body: &str| check(&format!("gsave nulldevice {body} grestore")); + let set = "/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont"; + // `ashow` adds 5 to each of the two codes. + measured(&format!( + "{set} 10 20 moveto <93fa967b> show currentpoint pop 10 20 moveto 5 0 <93fa967b> ashow currentpoint pop sub -10 sub abs 0.01 lt" + )); + let r = super::tests::read(&format!("{set} 10 20 moveto 5 0 <93fa967b> ashow")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["日本"]); + assert!(t[0].runs.iter().all(|run| (run.style.tracking - 250.0).abs() < 0.5), "{:?}", t[0].runs); + // `widthshow` adds 7 to the space, code 0x20. + measured(&format!( + "{set} 10 20 moveto <93fa20967b> show currentpoint pop 10 20 moveto 7 0 32 <93fa20967b> widthshow currentpoint pop sub -7 sub abs 0.01 lt" + )); + // A row-and-cell code read in its EUC form keeps the value of the string's bytes: 中 0x5650. + let gb = "/STSong-Light-GB-H findfont 20 scalefont setfont"; + measured(&format!( + "{gb} 10 20 moveto <56505650> show currentpoint pop 10 20 moveto 7 0 16#5650 <56505650> widthshow currentpoint pop sub -14 sub abs 0.01 lt" + )); + // `xshow` moves 30 a code. + measured(&format!("{set} 10 20 moveto <93fa967b> [30 30] xshow currentpoint pop 70 sub abs 0.01 lt")); + // Down the column: `ashow`'s 5 down each code. + let set = "/Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont"; + measured(&format!( + "{set} 10 200 moveto <93fa967b> show currentpoint exch pop 10 200 moveto 0 -5 <93fa967b> ashow currentpoint exch pop sub 10 sub abs 0.01 lt" + )); + let r = super::tests::read(&format!("{set} 10 200 moveto 0 -5 <93fa967b> ashow")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::(), "日本"); + assert!(t.iter().all(|t| t.vertical), "{t:?}"); +} + +/// A CID-keyed font over a vertical predefined CMap (`-V`), the file defining neither, its CIDFont +/// only named: the type is a vertical column, and the point moves down it, not along a line. +#[test] +fn named_cidfonts_over_vertical_cmaps_set_vertical_type() { + for (cmap, hex) in [("90ms-RKSJ-V", "93fa967b"), ("UniJIS-UCS2-V", "65e5672c")] { + let r = super::tests::read(&format!("/Ryumin-Light-{cmap} findfont 20 scalefont setfont 10 20 moveto <{hex}> show")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["日本"], "{cmap}: {:?}", r.warnings); + assert!(t[0].vertical, "{cmap}"); + check(&format!("/Ryumin-Light-{cmap} findfont 20 scalefont setfont <{hex}> stringwidth dup -60 gt exch -5 lt and exch abs 0.01 lt and")); + } +} + +/// Down a column each code of a CID-keyed font over a vertical predefined CMap moves the point one +/// em, the default vertical displacement (PDF Reference 1.7, §5.6.3, `DW2`), also two digits that +/// vertical type sets side by side in one em: `show` and `stringwidth` move the point as far as +/// showing the codes one at a time. +#[test] +fn codes_down_a_column_each_move_the_point_one_em() { + // Measured without painting. + let set = "gsave nulldevice /Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont"; + check(&format!("{set} (12) stringwidth grestore -40 sub abs 0.01 lt exch abs 0.01 lt and")); + check(&format!("{set} 10 100 moveto (12) show currentpoint grestore 60 sub abs 0.01 lt exch 10 sub abs 0.01 lt and")); + check(&format!( + "{set} 10 100 moveto (1) show (2) show currentpoint 10 100 moveto (12) show currentpoint grestore \ + 3 -1 roll sub abs 0.01 lt 3 1 roll sub abs 0.01 lt and" + )); +} + +/// Type in a CID-keyed font over a predefined CMap is set the same way by `show` and by the show +/// operators that space it: characters the font would join in a ligature (`fi` in the bundled +/// Source Serif 4) are set without the ligature, and the point moves as far. +#[test] +fn named_cid_type_is_set_alike_by_every_show_operator() { + let set = "/SourceSerif4-Regular-UniJIS-UCS2-H findfont 50 scalefont setfont 10 20 moveto"; + let features = |show: &str| { + let r = super::tests::read(&format!("{set} <00660069> {show}")); + let t = texts(&r); + assert_eq!(t.iter().map(|t| t.plain_text()).collect::>(), ["fi"], "{show}"); + t[0].runs.iter().map(|r| r.style.features.clone()).collect::>() + }; + let plain = features("show"); + assert_eq!(plain, features("0 0 3 -1 roll ashow")); + assert!(plain.iter().all(|f| f.iter().any(|f| f == "-liga")), "{plain:?}"); + check(&format!( + "gsave nulldevice {set} <00660069> stringwidth 10 20 moveto 0 0 <00660069> ashow currentpoint grestore \ + 20 sub 3 -1 roll sub abs 0.01 lt 3 1 roll 10 sub sub abs 0.01 lt and" + )); +} + +/// A font name ending in the row-and-cell CMap `H` after a name without a hyphen stays a font of +/// the whole name, its strings read byte by byte. Type in a predefined CMap whose mappings aren't +/// available is left out with a warning, and a long string in a CID-keyed font over a predefined +/// CMap shown in a loop runs out of the budget. +#[test] +fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() { + let r = super::tests::read("/Futura-H findfont 20 scalefont setfont 10 20 moveto (AB) show"); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::>(), ["AB"]); + let r = super::tests::read("/Ryumin-Light-GBT-H findfont 20 scalefont setfont 10 20 moveto (AB) show 0 0 10 10 rectfill"); + assert!(texts(&r).is_empty(), "{:?}", all(&r.document)); + assert_eq!(super::tests::program_warnings(&r.warnings), [super::text::UNREAD_CMAP], "{:?}", r.warnings); + super::tests::runs_out_of_budget("/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont { 100000 string stringwidth pop pop } loop"); +} + +/// A string in the file, in a CID-keyed font over a predefined CMap, too long to decode within the +/// memory budget stops the program with an error before it is decoded. +#[test] +fn huge_strings_over_predefined_cmaps_count_against_the_memory_budget() { + // Codes the CMap doesn't map, so nothing is laid out when the string is decoded. + let huge = "\u{1}".repeat(17 << 20); + let r = import(&super::tests::eps(&format!( + "0 0 10 10 rectfill /Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont 10 20 moveto ({huge}) stringwidth" + ))) + .unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); +} + /// A Type 2 CIDFont the file carries (its glyph space one unit an em), over a Unicode CMap the /// file doesn't define, sets its characters as type at the font's size, not a thousand times it. #[test] diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 8aad47fc77..193b81a233 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -548,3 +548,21 @@ fn the_data_of_an_image_too_large_to_read_is_skipped() { assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); } } + +/// A JPEG whose header claims far more pixels than an image may have is refused before the decoder +/// allocates for them. +#[test] +fn a_jpeg_with_a_huge_header_is_refused_before_it_is_decoded() { + let mut jpeg = vec![]; + image::codecs::jpeg::JpegEncoder::new(&mut jpeg).encode(&[128; 64], 8, 8, image::ExtendedColorType::L8).unwrap(); + // The frame header (marker, length, precision, height, width) now says 65535 × 65535. + let sof = jpeg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap(); + jpeg[sof + 5..sof + 9].fill(0xFF); + let jpeg: String = jpeg.iter().map(|b| format!("{b:02x}")).collect(); + let e = import(&eps(&format!( + "/DeviceGray setcolorspace << /ImageType 1 /Width 1 /Height 1 /BitsPerComponent 8 /ImageMatrix [1 0 0 1 0 0] \ + /DataSource currentfile /ASCIIHexDecode filter /DCTDecode filter >> image\n{jpeg}>" + ))) + .unwrap_err(); + assert!(e.contains("too large"), "{e}"); +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f9983c6e83..7353c5c190 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -77,6 +77,14 @@ fn names(d: &Document) -> Vec { d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect() } +/// The ruler guides of `d` by their line, artboard and layer. +fn guide_lines(d: &Document) -> Vec { + d.ruler_guides() + .into_iter() + .map(|g| vectorcraft_doc::Guide { artboard: g.artboard, layer: g.layer, ..vectorcraft_doc::Guide::new(g.vertical, g.pos) }) + .collect() +} + #[test] fn ruler_units_in_the_program_header_alone_are_kept() { let art = layer("Art", true, &square(10, 10)); @@ -2219,11 +2227,11 @@ fn an_ai_files_ruler_guides_come_in_on_their_layers() { assert!(read, "{w:?}"); let jig = d.layers[0].id; let want = [ - vectorcraft_doc::Guide { vertical: false, pos: 60.0 * k, artboard: None, layer: Some(jig) }, - vectorcraft_doc::Guide { vertical: true, pos: 20.0 * k, artboard: Some(d.artboards[0].id), layer: Some(jig) }, + vectorcraft_doc::Guide { layer: Some(jig), ..vectorcraft_doc::Guide::new(false, 60.0 * k) }, + vectorcraft_doc::Guide { artboard: Some(d.artboards[0].id), layer: Some(jig), ..vectorcraft_doc::Guide::new(true, 20.0 * k) }, ]; - assert_eq!(d.guides, want); - assert_eq!(d.layers[0].children().map_or(0, |c| c.len()), 1, "the square alone"); + assert_eq!(guide_lines(&d), want); + assert_eq!(d.layers[0].children().map_or(0, |c| c.iter().filter(|c| !c.is_ruler_guide()).count()), 1, "the square alone"); } } @@ -2241,7 +2249,10 @@ fn an_eps_of_its_art_box_keeps_the_guides_of_its_first_artboard() { assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); assert_eq!(r.document.artboards.len(), 1); let (board, layer) = (r.document.artboards[0].id, r.document.layers[0].id); - assert_eq!(r.document.guides, [vectorcraft_doc::Guide { vertical: true, pos: 25.0, artboard: Some(board), layer: Some(layer) }]); + assert_eq!( + guide_lines(&r.document), + [vectorcraft_doc::Guide { artboard: Some(board), layer: Some(layer), ..vectorcraft_doc::Guide::new(true, 25.0) }] + ); } /// A PDF part read from a `UserUnit` page cropped to the art: the art's box, not the artboard, is @@ -5408,7 +5419,14 @@ fn type_envelope_text(family: &str, paint: Option<&str>) -> String { fn arc_envelope(text: &Node, bend: f64) -> Node { let mut text = text.clone(); text.visible = true; - let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { + style: "arc".into(), + bend, + h: 0.0, + v: 0.0, + horizontal: true, + version: vectorcraft_doc::live::WARP_NET, + }; Node::new( vectorcraft_doc::NodeId(1_000_000), NodeKind::Envelope { @@ -5785,7 +5803,8 @@ fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its /// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its /// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope -/// mapping from that box (#3179). +/// mapping from that box (#3179). The drawn art strokes the bent outlines at the stroke's own weight, +/// as files draw it (#6644). #[test] fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does() { use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin}; @@ -5805,7 +5824,7 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_ vectorcraft_doc::NodeId(1_000_000), NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, ); - let (drawn, page) = drawn_envelope(&shaped); + let (drawn, page) = drawn_stroked_envelope(&shaped); let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); @@ -5822,6 +5841,101 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_ assert_eq!(margin, Some(options.bounds_margin)); } +/// The drawn art of `envelope` (on the page axes), an envelope of type stroked by its characters, +/// as the drawn art of `.ai` files strokes type in an envelope: the bent glyph outlines the envelope +/// draws of its type unstroked, each filled in its type's color, then each stroked with the type's +/// stroke (its weight, color, join and miter limit) whatever the grid does to it, and the page's +/// PostScript for them (#6644). +fn drawn_stroked_envelope(envelope: &Node) -> (String, String) { + let NodeKind::Envelope { content, .. } = &envelope.kind else { panic!("an envelope") }; + let Some(NodeKind::Text(t)) = content.first().map(|c| &c.kind) else { panic!("type") }; + let stroke = t.runs[0].style.stroke_layer(); + let mut unstroked = envelope.clone(); + if let NodeKind::Envelope { content, .. } = &mut unstroked.kind { + for c in content.iter_mut() { + if let NodeKind::Text(t) = &mut std::sync::Arc::make_mut(c).kind { + t.runs.iter_mut().for_each(|r| r.style.stroke = vectorcraft_color::Paint::None); + } + } + } + let (fills, fill_page) = drawn_envelope(&unstroked); + let [r, g, b] = stroke.paint.color().map_or([0.0; 3], |c| c.to_rgb()); + let join = match stroke.join { + vectorcraft_doc::LineJoin::Miter => 0, + vectorcraft_doc::LineJoin::Round => 1, + vectorcraft_doc::LineJoin::Bevel => 2, + }; + let (w, limit) = (stroke.width, stroke.miter_limit); + let mut art = format!("{fills}0 0 0 0 {r} {g} {b} XA\n{w} w\n{join} j\n{limit} M\n"); + let mut page = format!("{fill_page}{r} {g} {b} setrgbcolor {w} setlinewidth {join} setlinejoin {limit} setmiterlimit\n"); + let pt = |p: kurbo::Point| { + let (x, y) = to_art(p); + format!("{x} {y}") + }; + vectorcraft_effects::expand_live_deep(None, &unstroked).walk(&mut |n| { + let NodeKind::Path { path, .. } = &n.kind else { return }; + for el in path.to_bezpath().elements() { + match *el { + kurbo::PathEl::MoveTo(p) => { + art += &format!("{} m\n", pt(p)); + page += &format!("newpath {} moveto ", pt(p)); + } + kurbo::PathEl::LineTo(p) => { + art += &format!("{} L\n", pt(p)); + page += &format!("{} lineto ", pt(p)); + } + kurbo::PathEl::CurveTo(a, c, p) => { + art += &format!("{} {} {} C\n", pt(a), pt(c), pt(p)); + page += &format!("{} {} {} curveto ", pt(a), pt(c), pt(p)); + } + kurbo::PathEl::QuadTo(..) => {} + kurbo::PathEl::ClosePath => { + art += "s\n"; + page += "closepath stroke\n"; + } + } + } + }); + (art, page) +} + +/// An envelope of type with a character stroke, Distort Appearance on, whose drawn art strokes the +/// bent glyph outlines at the stroke's own weight (as `.ai` files draw the strokes of type in an +/// envelope, however much the grid squeezes or stretches it) opens live: VectorCraft draws the +/// stroke that way too (#6644). +#[test] +fn an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live() { + let Some(family) = installed_family() else { return }; + // "FLUX" stroked 1.5 points wide in black with round joins. + let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /62 1 /63 1.5"; + let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked); + let mut text = made_envelope_type(&doc); + text.visible = true; + assert!( + matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_width == 1.5 && t.runs[0].style.stroke_join == vectorcraft_doc::LineJoin::Round), + "{text:?}" + ); + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { + content: vec![std::sync::Arc::new(text)], + kind: Box::new(rising_kind()), + fidelity: 50.0, + editing: false, + options: vectorcraft_doc::live::EnvelopeOptions::NEW, + frame: Box::default(), + }, + ); + let (drawn, page) = drawn_stroked_envelope(&shaped); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); +} + /// A warp of type whose editing data saves no grid it can be shaped by keeps its drawn art and its /// type, hidden, with the note, when its own warp draws apart from that art (#3179). #[test] diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 5868aa9228..ee9b0fc759 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -15,6 +15,7 @@ use super::cid::Base; use super::graphics::MAX_APART; use super::interp::{Interp, matrix_obj, matrix_of}; use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, ps_err}; +use super::predefined_cmap::Decoded; use super::type1::Embedded; /// The font a program uses before it sets one. @@ -170,8 +171,8 @@ impl Interp<'_> { ResourceForAll => self.resource_for_all()?, Show | AShow | WidthShow | AWidthShow | XShow | YShow | XYShow | KShow => { let (s, spacing) = self.show_operands(op)?; - if let Some((text, font)) = self.unicode_type(&s)? { - self.show_unicode(&text, &font)?; + if let Some((codes, font, vertical)) = self.named_cid_type(&s)? { + self.show_named_cid(&codes, &font, vertical, &spacing)?; } else if let Some(glyphs) = self.composite_glyphs(&s)? { self.show_composite(&glyphs, &spacing)?; } else { @@ -282,9 +283,9 @@ impl Interp<'_> { /// How far `s` moves the current point (user space). fn width_of(&mut self, s: &[u8]) -> Res { - if let Some((text, font)) = self.unicode_type(s)? { + if let Some((codes, font, vertical)) = self.named_cid_type(s)? { let saved = self.g.font.replace(font); - let r = self.set_text(&text, Point::ZERO).map(|t| t.2); + let r = self.named_cid_width(&codes, vertical); self.g.font = saved; return r; } @@ -395,18 +396,29 @@ impl Interp<'_> { } /// The font named `k`: one the program defined; else, for a name `CIDFont-CMap` whose CMap - /// is a predefined Unicode CMap, the CID-keyed font of those two (the usual name of a - /// CID-keyed font, as `composefont` makes them: PLRM 3rd ed., chapter 8); else a font of - /// that name. + /// is a predefined CMap, the CID-keyed font of those two (the usual name of a CID-keyed font, + /// as `composefont` makes them: PLRM 3rd ed., chapter 8; the CMaps are Adobe's public CMap + /// resources, ); else a font of that name. + /// A name an installed face has is that face's, and a name split at a bare `H` or `V` (the + /// row-and-cell CMaps) needs a CIDFont name with a hyphen in it (`Ryumin-Light-H`), so + /// `Futura-H` stays a font of that name. fn find_font(&mut self, k: &Obj) -> Res { let key = k.key().ok_or(PsError::Ps("typecheck", "findfont".into()))?; if let Some(Obj::Dict(d)) = self.fonts.borrow().get(&key) { return Ok(d.clone()); } let text = k.text().map(|t| t.to_string()).unwrap_or_default(); - let split = - text.match_indices('-').map(|(i, _)| i).find(|&i| i > 0 && super::cid::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some()); - if let Some((cid_font, cmap)) = split.and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?))) { + let split = text + .match_indices('-') + .map(|(i, _)| i) + .find(|&i| i > 0 && super::cid::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some()) + .and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?))) + .or_else(|| { + let (cid_font, cmap) = super::predefined_cmap::composite_font(&text)?; + let installed = vectorcraft_text::FontDb::global().find_postscript(&text).is_some(); + (!installed && !(matches!(cmap, "H" | "V") && !cid_font.contains('-'))).then_some((cid_font, cmap)) + }); + if let Some((cid_font, cmap)) = split { let cmap = self.find_cmap(&Obj::name(cmap))?; let dep = self.find_cid_font(&Obj::name(cid_font))?; return Ok(self.composed(key, cmap, vec![Obj::Dict(dep)])); @@ -476,6 +488,15 @@ impl Interp<'_> { /// [`Self::set_type`] for the characters `text`. fn set_text(&mut self, text: &str, at: Point) -> Res<(TextObject, TextLayout, Vec2)> { + self.set_text_in(text, at, false) + } + + /// [`Self::set_text`], as vertical type when `vertical`: a column anchored at `at`, the top + /// center of its first em box, that moves the current point down the column by the layout's + /// advances. In vertical writing the current point is a glyph's origin 1, by default half its + /// width across and 880 units of 1000 above its origin 0 (PDF Reference 1.7, §5.6.3 "Glyph + /// Metrics in CIDFonts", `DW2`). + fn set_text_in(&mut self, text: &str, at: Point, vertical: bool) -> Res<(TextObject, TextLayout, Vec2)> { // Laying out type costs about as much as 300 operations, and 64 more a character // (measured), so `{ (a) stringwidth pop pop } loop` or `cshow` on a long string ends // within the budget like any other loop instead of running for minutes. @@ -493,11 +514,29 @@ impl Interp<'_> { let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; let style = CharStyle { font_family, font_style, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); + t.vertical = vertical; let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); t.xf = m * Affine::scale_non_uniform(1.0 / size, -1.0 / size); t.cached_bounds = Some(layout.bounds); let adv: f64 = layout.glyphs.iter().map(|g| g.advance).sum(); - Ok((t, layout, f1 * Point::new(adv / size, 0.0) - f1 * Point::ZERO)) + let moved = if vertical { Point::new(0.0, -adv / size) } else { Point::new(adv / size, 0.0) }; + Ok((t, layout, f1 * moved - f1 * Point::ZERO)) + } + + /// [`Self::set_text_in`] for characters the file places one by one: where the layout joins + /// characters in a ligature, the type is set without ligatures, so each character has its own + /// advance. + fn set_placed_text(&mut self, text: &str, at: Point, vertical: bool) -> Res<(TextObject, TextLayout)> { + let (mut t, mut layout, _) = self.set_text_in(text, at, vertical)?; + let glyph_starts: std::collections::HashSet = layout.glyphs.iter().map(|g| g.byte).collect(); + if text.char_indices().any(|(b, _)| !glyph_starts.contains(&b)) { + for run in &mut t.runs { + run.style.features.push("-liga".into()); + } + layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + t.cached_bounds = Some(layout.bounds); + } + Ok((t, layout)) } /// `show`: point type at the current point, which moves past it. @@ -527,27 +566,30 @@ impl Interp<'_> { return self.show_type42_outlines(data, glyphs, s, spacing, at, f1); } // Each code's character, if it has one that shows (control codes don't). - let chars: Vec> = match &plain { + let chars = match &plain { Some((_, glyphs)) => glyphs.iter().map(|g| g.ch).collect::>(), None => self.named_chars(s).into_iter().map(Some).collect(), + }; + let mut codes = Decoded::default(); + for (c, &code) in chars.into_iter().zip(s) { + codes.push(u32::from(code), c.filter(|c| !c.is_control())); } - .into_iter() - .map(|c| c.filter(|c| !c.is_control())) - .collect(); - let text: String = chars.iter().flatten().collect(); - let (mut t, mut layout, _) = self.set_text(&text, at)?; + let widths: Option> = plain.map(|(_, glyphs)| glyphs.iter().map(|g| g.width).collect()); + self.show_codes(&codes, widths.as_deref(), spacing, false, s) + } + + /// The codes `codes` (each standing for some of its characters, or none) shown in the current + /// font as [`Self::show_plain`] shows a string's, spaced as `spacing` says, each code `widths` + /// wide when given (in glyph space, one unit an em), else as wide as its characters' advances; + /// as vertical type when `vertical`, the codes moving the point down the column. `kern` is the + /// string `kshow` gives its procedure the codes of. + fn show_codes(&mut self, codes: &Decoded, widths: Option<&[f64]>, spacing: &Spacing, vertical: bool, kern: &[u8]) -> Res { + let at = self.user_point()?; + let (_, f1) = self.font()?; + let text = &codes.text; + let (mut t, layout) = self.set_placed_text(text, at, vertical)?; let size = t.runs.first().map_or(1.0, |r| r.style.size); let starts: Vec = text.char_indices().map(|(b, _)| b).collect(); - // The file places each character's glyph: where the layout joins characters in a - // ligature, the type is set without ligatures, so each character has its own advance. - let glyph_starts: std::collections::HashSet = layout.glyphs.iter().map(|g| g.byte).collect(); - if starts.iter().any(|b| !glyph_starts.contains(b)) { - for run in &mut t.runs { - run.style.features.push("-liga".into()); - } - layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); - t.cached_bounds = Some(layout.bounds); - } // Each character's advance in the layout (text space). let mut natural = vec![0.0; starts.len()]; for g in &layout.glyphs { @@ -555,29 +597,30 @@ impl Interp<'_> { *n += g.advance; } } - // Each code's move (user space) and that move in text space, along the baseline and across. - let em = |x: f64| f1 * Point::new(x, 0.0) - f1 * Point::ZERO; + // Each code's move (user space) and that move in text space, along the baseline (down the + // column) and across. + let em = |x: f64| f1 * if vertical { Point::new(0.0, -x) } else { Point::new(x, 0.0) } - f1 * Point::ZERO; let inv = f1.inverse(); - let mut moves = Vec::with_capacity(s.len()); + let mut moves = Vec::with_capacity(codes.codes.len()); let mut k = 0; // What `kshow`'s procedure draws goes after the type. let start = self.out.drawn.len(); let mut pen = at; - for (i, (&code, c)) in s.iter().zip(&chars).enumerate() { - let own = match &plain { - Some((_, glyphs)) => glyphs.get(i).map_or(0.0, |g| g.width), - None if c.is_some() => natural.get(k).copied().unwrap_or(0.0) / size, - None => 0.0, + for (i, &(code, n)) in codes.codes.iter().enumerate() { + let own = match widths { + Some(widths) => widths.get(i).copied().unwrap_or(0.0), + None => natural.get(k..k + n).map_or(0.0, |w| w.iter().sum::()) / size, }; - k += usize::from(c.is_some()); + k += n; let mut d = spacing.advance(i, i64::from(code), em(own)); - d += self.kern(spacing, s, i, pen + d)?; + d += self.kern(spacing, kern, i, pen + d)?; pen += d; let e = inv * Point::new(d.x, d.y) - inv * Point::ZERO; - if ![d.x, d.y, e.x * size, e.y * size].iter().all(|v| v.is_finite()) { + let (along, across) = if vertical { (-e.y * size, e.x * size) } else { (e.x * size, e.y * size) }; + if ![d.x, d.y, along, across].iter().all(|v| v.is_finite()) { return ps_err("undefinedresult", "a show"); } - moves.push((d, e.x * size, e.y * size)); + moves.push((d, along, across)); } let total: Vec2 = moves.iter().map(|m| m.0).sum(); if !(total.x.is_finite() && total.y.is_finite()) { @@ -589,12 +632,11 @@ impl Interp<'_> { if across { // Moves across the baseline (`yshow`, `xyshow`): each character where the file puts it. let mut pen = at; - for ((d, ..), c) in moves.iter().zip(&chars) { - if let Some(c) = c - && painted - && !c.is_whitespace() - { - let (t, ..) = self.set_text(c.encode_utf8(&mut [0; 4]), pen)?; + let mut chars = text.chars(); + for ((d, ..), &(_, n)) in moves.iter().zip(&codes.codes) { + let c: String = chars.by_ref().take(n).collect(); + if painted && !c.trim().is_empty() { + let (t, ..) = self.set_text_in(&c, pen, vertical)?; let clips = self.g.clips.clone(); self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); } @@ -605,11 +647,17 @@ impl Interp<'_> { // a character, before the next, are that character's. let mut lead = Vec2::ZERO; let mut target: Vec = Vec::with_capacity(natural.len()); - for ((d, along, _), c) in moves.iter().zip(&chars) { - match (c, target.last_mut()) { - (Some(_), _) => target.push(*along), - (None, Some(last)) => *last += along, - (None, None) => lead += *d, + for ((d, along, _), &(_, n)) in moves.iter().zip(&codes.codes) { + if n > 0 { + // A code of several characters: those before its last keep their advances. + let before = natural.get(target.len()..target.len() + n - 1).unwrap_or_default().to_vec(); + let rest = *along - before.iter().sum::(); + target.extend(before); + target.push(rest); + } else if let Some(last) = target.last_mut() { + *last += along; + } else { + lead += *d; } } let tracking: Vec = target @@ -931,23 +979,47 @@ impl Interp<'_> { .collect()) } - /// The characters of `s` and the font to set them in when the current font is a CID-keyed - /// font over a predefined Unicode CMap the file doesn't define (`UniJIS-UCS2-H`), whose - /// mappings to CIDs aren't known: its codes say the characters, set as type in the font of - /// its CIDFont's name. - fn unicode_type(&mut self, s: &[u8]) -> Res> { - let Some((text, font, name)) = self.unicode_parts(s) else { return Ok(None) }; + /// The codes of `s` with the characters each stands for, the font to set them in and whether + /// they run down a column, when the current font is a CID-keyed font over a predefined CMap + /// the file doesn't define (`UniJIS-UCS2-H`, `90ms-RKSJ-H`), whose mappings to CIDs the file + /// doesn't give: a Unicode CMap's codes are the characters, another CMap's are read by the CMap + /// of that name and its character collection's CID → Unicode CMap (a code it doesn't map + /// stands for none), set as type in the font of its CIDFont's name, vertical over a vertical + /// CMap (`WMode` 1). Control codes stand for no character. Type in a CMap VectorCraft can't + /// read is left out, with a warning. + fn named_cid_type(&mut self, s: &[u8]) -> Res> { + let Some((cmap, font, name, vertical)) = self.named_cid_parts() else { return Ok(None) }; + // Each code is looked up in the CMap's mappings. + self.spend(s.len() as u64)?; + // The decoded codes and characters are held while the string is shown: checked against + // the memory budget first, so a huge string in the file stops the program with an error. + let held = s.len().saturating_mul(DECODED_BYTES); + self.alloc(held)?; + self.unalloc(held); + let decoded = match self.predefined_codes(&cmap) { + Some(codes) => codes.codes(s), + None => { + self.out.warn(UNREAD_CMAP); + Decoded::default() + } + }; + let mut codes = Decoded::default(); + let mut chars = decoded.text.chars(); + for &(code, n) in &decoded.codes { + codes.push(code, chars.by_ref().take(n).filter(|c| !c.is_control())); + } // The composite font is copied under the CIDFont's name for every string: charged by // its size, so a huge font dictionary shown in a loop runs out of the budget. let entries = font.borrow().len(); self.spend(entries as u64)?; let mut named = font.borrow().clone(); named.insert(Key::name("FontName"), name); - Ok(Some((text, DictRef::new(named)))) + Ok(Some((codes, DictRef::new(named), vertical))) } - /// The text, the composite font and the CIDFont's name of [`Self::unicode_type`]. - fn unicode_parts(&self, s: &[u8]) -> Option<(String, DictRef, Obj)> { + /// The CMap's name, the composite font, the CIDFont's name and the writing mode of + /// [`Self::named_cid_type`]. + fn named_cid_parts(&self) -> Option<(String, DictRef, Obj, bool)> { let font = self.g.font.clone()?; let f = font.borrow(); if font_type(&f) != Some(0.0) || f.get(&Key::name("FMapType")).and_then(Obj::as_num) != Some(9.0) { @@ -959,29 +1031,63 @@ impl Interp<'_> { if cmap.contains_key(&Key::name("CodeSpaceRange")) { return None; } - let (form, _) = super::cid::unicode_cmap(&cmap.get(&Key::name("CMapName")).and_then(Obj::text)?)?; + let cmap_name = cmap.get(&Key::name("CMapName")).and_then(Obj::text)?.to_string(); + if super::cid::unicode_cmap(&cmap_name).is_none() && !super::predefined_cmap::known(&cmap_name) { + return None; + } + let wmode = f.get(&Key::name("WMode")).or_else(|| cmap.get(&Key::name("WMode"))).and_then(Obj::as_num); let Some(Obj::Dict(dep)) = f.get(&Key::name("FDepVector")).and_then(|v| v.items()?.get(0)) else { return None }; let name = { let d = dep.borrow(); d.get(&Key::name("CIDFontName")).or_else(|| d.get(&Key::name("FontName"))).cloned()? }; - Some((super::cid::unicode_text(s, form), font.clone(), name)) + Some((cmap_name, font.clone(), name, wmode == Some(1.0))) } - /// `text` set as point type at the current point in font `font` (see - /// [`Self::unicode_type`]), which moves past it. - fn show_unicode(&mut self, text: &str, font: &DictRef) -> Res { - let at = self.user_point()?; - let saved = self.g.font.replace(font.clone()); - let r = self.set_text(text, at); - self.g.font = saved; - let (t, _, adv) = r?; - if !self.g.paint.is_none() && !self.g.null && !text.trim().is_empty() { - let clips = self.g.clips.clone(); - self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + /// How strings in predefined CMap `cmap` decode (a CMap other than a Unicode CMap read once a + /// file); `None` when VectorCraft can't read it. + fn predefined_codes(&mut self, cmap: &str) -> Option> { + if let Some((form, _)) = super::cid::unicode_cmap(cmap) { + return Some(Rc::new(super::predefined_cmap::CMapCodes::Unicode(form))); } - self.g.cur = Some(self.xf() * (at + adv)); - Ok(()) + if let Some((_, codes)) = self.predefined_cmaps.iter().find(|(n, _)| **n == *cmap) { + return codes.clone(); + } + let codes = super::predefined_cmap::codes(cmap).map(Rc::new); + // Only the names of the other predefined CMaps reach here (`named_cid_parts`), so the + // list stays short. + self.predefined_cmaps.push((Rc::from(cmap), codes.clone())); + codes + } + + /// The codes `codes` (with their characters) set as point type at the current point in font + /// `font` (see [`Self::named_cid_type`]), running down a column when `vertical`, which moves + /// past them, spaced as `spacing` says, as [`Self::show_codes`] shows them. `widthshow` and + /// `awidthshow` match a code by its value (font number 0 times 256 plus the code: PLRM 3rd ed., + /// `widthshow` in chapter 8); `kshow`'s procedure isn't run between them (a composite font's + /// codes aren't single bytes). Down a column each code moves the point one em, the default + /// vertical displacement of a CIDFont whose metrics the file doesn't give (PDF Reference 1.7, + /// §5.6.3, `DW2`). + fn show_named_cid(&mut self, codes: &Decoded, font: &DictRef, vertical: bool, spacing: &Spacing) -> Res { + let widths = vertical.then(|| vec![1.0; codes.codes.len()]); + let saved = self.g.font.replace(font.clone()); + let r = self.show_codes(codes, widths.as_deref(), spacing, vertical, &[]); + self.g.font = saved; + r + } + + /// How far the codes `codes` move the current point (user space) when [`Self::show_named_cid`] + /// shows them with no extra spacing. + fn named_cid_width(&mut self, codes: &Decoded, vertical: bool) -> Res { + let (_, f1) = self.font()?; + let moved = if vertical { + Point::new(0.0, -(codes.codes.len() as f64)) + } else { + let (t, layout) = self.set_placed_text(&codes.text, Point::ZERO, false)?; + let size = t.runs.first().map_or(1.0, |r| r.style.size); + Point::new(layout.glyphs.iter().map(|g| g.advance).sum::() / size, 0.0) + }; + Ok(f1 * moved - f1 * Point::ZERO) } /// The characters of a composite font shown at the current point, spaced as `spacing` says. @@ -1282,6 +1388,13 @@ const MAX_TYPE1: usize = 256; /// The warning for CID-keyed type in a CIDFont the file doesn't carry. const MISSING_CID_FONT: &str = "CID-keyed type in a font the file doesn't carry was left out"; +/// Most bytes [`Interp::named_cid_type`] holds for each byte of a string: two lists of codes (16 +/// bytes a code) and their characters (up to 4 bytes a character, a few characters a code). +const DECODED_BYTES: usize = 64; + +/// The warning for type in a predefined CMap whose mappings VectorCraft doesn't have. +pub(super) const UNREAD_CMAP: &str = "Type in a CMap that couldn't be read was left out"; + /// Most Type 42 fonts whose TrueType data is kept between glyphs. const MAX_TYPE42: usize = 16; diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 6b553b8d1a..2a09cf003c 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -33,7 +33,10 @@ //! - Type (§15): point type, area type and type on a path as text objects, `type To`, `a b c d tx //! ty startPt Tp` (the text matrix; the frame or path in art space between it and `TP`), each //! run's paint style, `Tr` (fill, stroke, both or neither), `/_font size ascent descent Tf`, -//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Only the +//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Standard +//! Vertical Roman Alignment is written as `1 Tv` and `0 Tv`, and Tate-chu-yoko in horizontal +//! type as a Kumi block recorded for later use, `1 TY` … `0 TY` (§15.3.4); neither operator is +//! written for type that has neither mark. Only the //! revisable form is written: readers lay the type out again (§15.1). Fonts are named by their //! PostScript names in `%%DocumentFonts` and `%%IncludeFont` (§3.1) and re-encoded to //! Windows-1252 (`TE`, then `%AI3_BeginEncoding: _name name`, `TZ`, §3.3), the 8-bit encoding @@ -97,6 +100,7 @@ pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines"; pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)"; pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, manual kerning, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; +pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)"; pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)"; pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)"; pub const HIDDEN_SHOWN: &str = "hidden objects are written visible (legacy .ai files can hide only layers)"; @@ -107,6 +111,10 @@ pub const TITLE_AND_COLOR_NAMES: &str = pub const NAMES: &str = "object names are left out (legacy .ai files name only layers)"; const PATTERNS: &str = "pattern fills are written as their tiles, clipped to the shape"; const FREEFORM: &str = "freeform gradients are written as their average colour"; +const CONIC: &str = "conic gradients are written as solid wedges clipped to the shape (legacy .ai files have no conic gradient)"; +const DIAMOND: &str = "diamond gradients are written as four linear gradients clipped to the shape (legacy .ai files have no diamond gradient)"; +/// Wedges a conic gradient is written as: one a degree. +const CONIC_WEDGES: usize = 360; const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines"; const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index 8ea787f8a5..5528ad7529 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -201,7 +201,9 @@ pub(super) fn segment_point(path: &BezPath, fraction: f64) -> f64 { pub(super) fn direct_fill(p: &Paint) -> bool { match p { Paint::Solid { .. } => true, - Paint::Gradient(g) => g.gradient.kind != GradientKind::Freeform && !g.gradient.stops.is_empty(), + Paint::Gradient(g) => { + !matches!(g.gradient.kind, GradientKind::Freeform | GradientKind::Conic | GradientKind::Diamond) && !g.gradient.stops.is_empty() + } _ => false, } } diff --git a/crates/eps/src/legacy_ai/prolog.rs b/crates/eps/src/legacy_ai/prolog.rs index b0d606bba9..5ee77f89cf 100644 --- a/crates/eps/src/legacy_ai/prolog.rs +++ b/crates/eps/src/legacy_ai/prolog.rs @@ -106,7 +106,7 @@ VCLegacy begin /TE {cleartomark} bd /TZ {cleartomark} bd /To {pop} bd /Tp {7 {pop} repeat} bd /TP {} bd /TO {} bd /Tr {pop} bd /Tf {pop pop pop pop} bd /Ts {pop} bd /Tz {pop pop} bd /Tt {pop} bd /TA {pop} bd -/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd +/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd /Tv {pop} bd /TY {pop} bd % The page trailer (3): annotatepage marks nothing. /annotatepage {} bd end diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 979cd2a436..d189c94ed9 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -83,6 +83,62 @@ fn write(doc: &Document) -> LegacyAiOutput { write_with(doc, LegacyAiOptions::default()) } +/// The format has no conic gradient: a conic fill, and a conic stroke (written as its filled +/// outline), are solid wedges clipped to the shape, with a warning, and print as the canvas +/// draws them ([`write`] runs the file). +#[test] +fn conic_gradients_are_written_as_wedges_clipped_to_the_shape() { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops)); + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(100.0, 50.0), + end: vectorcraft_geom::Point::new(140.0, 30.0), + aspect: -0.7, + focal: None, + }); + let conic = Paint::Gradient(Box::new(g)); + for (fill, stroke) in [(conic.clone(), Paint::None), (Paint::None, conic)] { + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), fill.clone(), stroke.clone()); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == CONIC), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes); + assert!(!text.contains("%AI5_BeginGradient"), "no gradient stands in"); + assert!(text.matches("\nf\n").count() >= CONIC_WEDGES, "a wedge a degree"); + } +} + +/// The format has no diamond gradient: a diamond fill, and a diamond stroke (written as its filled +/// outline), are four path objects clipped to the shape, each a linear gradient over a quadrant +/// of the diamond's frame, with a warning; the definition is not named after the swatch. +#[test] +fn diamond_gradients_are_written_as_four_linear_gradients_clipped_to_the_shape() { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops)); + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(100.0, 50.0), + end: vectorcraft_geom::Point::new(140.0, 30.0), + aspect: 0.7, + focal: None, + }); + g.swatch = Some("Gem".into()); + let diamond = Paint::Gradient(Box::new(g)); + for (fill, stroke) in [(diamond.clone(), Paint::None), (Paint::None, diamond)] { + let mut doc = Document::new(200.0, 100.0); + let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), fill.clone(), stroke.clone()); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == DIAMOND), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes); + assert_eq!(text.matches("%AI5_BeginGradient: (Gradient)").count(), 1, "one linear definition: {text}"); + assert!(!text.contains("(Gem)"), "not named after the swatch"); + assert_eq!(text.matches(" Bg\n").count(), 4, "a gradient a quadrant"); + } +} + /// `doc` written with options `o`. Every file the tests write is also run as a PostScript program /// ([`prints_as`]) and must draw what `doc` draws. fn write_with(doc: &Document, o: LegacyAiOptions) -> LegacyAiOutput { @@ -155,7 +211,10 @@ fn as_printed(doc: &Document, o: &LegacyAiOptions) -> Document { AppearanceItem::Fill(f) => &mut f.paint, AppearanceItem::Stroke(s) => &mut s.paint, }; - if let Paint::Gradient(g) = paint { + // Conic gradients are written as wedges, which print. + if let Paint::Gradient(g) = paint + && g.gradient.kind != GradientKind::Conic + { *paint = g.gradient.stops.first().map_or(Paint::None, |s| Paint::solid(s.color)); } } @@ -1134,6 +1193,59 @@ fn variable_font_settings_are_warned_as_left_out() { assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); } +/// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a +/// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back +/// on the same characters, a block is closed before its text object ends, and type with neither +/// mark has neither operator. +#[test] +fn vertical_roman_and_tate_chu_yoko_are_written_and_read_back() { + use vectorcraft_doc::{TextObject, TextRun}; + let plain = style(12.0, Paint::solid(Color::BLACK)); + let roman = vectorcraft_doc::CharStyle { standard_vertical_roman: true, ..plain.clone() }; + let tcy = vectorcraft_doc::CharStyle { tate_chu_yoko: true, ..plain.clone() }; + let both = vectorcraft_doc::CharStyle { tate_chu_yoko: true, standard_vertical_roman: true, ..plain.clone() }; + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let mut marked = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "A", plain.clone()); + for (text, st) in [("12", &tcy), ("b", &roman), ("c", &both), ("34", &tcy)] { + marked.runs.push(TextRun::new(text, st.clone())); + } + let next = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "D", plain.clone()); + for t in [marked, next] { + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes.clone()).unwrap(); + assert_eq!((text.matches("1 TY\n").count(), text.matches("0 TY\n").count()), (2, 2), "{text}"); + assert_eq!((text.matches("1 Tv\n").count(), text.matches("0 Tv\n").count()), (1, 1), "{text}"); + // The last block ends before its text object does. + assert!(text.contains("(34) Tx\n0 TY\nTO\n"), "{text}"); + let read = texts(&crate::import(&out.bytes).unwrap().document); + let flags = |t: &TextObject| -> Vec<(String, bool, bool)> { + let mut out: Vec<(String, bool, bool)> = vec![]; + for r in &t.runs { + let key = (r.style.tate_chu_yoko, r.style.standard_vertical_roman); + match out.last_mut() { + Some(last) if (last.1, last.2) == key => last.0.push_str(&r.text), + _ => out.push((r.text.clone(), key.0, key.1)), + } + } + out + }; + let s = |x: &str| x.to_string(); + assert_eq!( + flags(&read[0].1), + [(s("A"), false, false), (s("12"), true, false), (s("b"), false, true), (s("c"), true, true), (s("34"), true, false)] + ); + assert_eq!(flags(&read[1].1), [(s("D"), false, false)]); + + // Type with neither mark has neither operator. + let text = String::from_utf8(write(&typed()).bytes).unwrap(); + assert!(!text.contains(" Tv\n") && !text.contains(" TY\n"), "{text}"); +} + /// A legacy `.ai` text path holds the path and where the type starts on it, and no Align to Path /// or end bracket: type on a path with either is written as text, with the warning that they are /// left out. An end bracket at the end of an open path, or once around a closed one, is kept. A @@ -1233,6 +1345,74 @@ fn a_font_height_reference_is_written_as_the_size_drawn() { assert!((size - 20.0).abs() < 1e-6, "{size}"); } +/// Type on a path with Dynamic Text is written at the sizes it is drawn at, with a warning that +/// the setting itself is not written; without Dynamic Text there is no warning. +#[test] +fn dynamic_text_is_written_at_its_drawn_sizes_with_a_warning() { + let mut doc = typed(); + assert!(!write(&doc).warnings.iter().any(|w| w == DYNAMIC_TEXT)); + let id = texts(&doc).into_iter().find(|(_, t)| matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })).unwrap().0.id; + let mut drawn = 0.0; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.size = 4.0; + t.dynamic_text = true; + drawn = 4.0 * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale; + } + assert!(drawn > 4.0, "{drawn}"); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings); + let imported = crate::import(&out.bytes).unwrap(); + let (_, back) = texts(&imported.document).into_iter().find(|(_, t)| t.runs.iter().any(|r| r.text.contains("path"))).unwrap(); + assert!(!back.dynamic_text); + assert!((back.runs[0].style.size - drawn).abs() < 1e-3, "{} vs {drawn}", back.runs[0].style.size); + // Type written as outlines loses the setting too, and says so. + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].text.push('\u{2192}'); + } + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == TYPE) && out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings); + let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }); + assert!(out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings); +} + +/// Dynamic Text fits type whose size measures the cap height at the size the Character panel +/// shows: 1,000 pt measuring a 0.7 em cap height on a long path grows to the 1,296 pt limit and is +/// written at the em size drawn there, as text and as outlines. +#[test] +fn dynamic_text_with_a_font_height_reference_is_written_at_its_drawn_size() { + use vectorcraft_doc::{TextKind, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + let db = vectorcraft_text::FontDb::global(); + db.add_font(height_font(true).unwrap()); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "HE", style(1000.0, red())); + let st = &mut t.runs[0].style; + st.font_family = HEIGHT_FAMILY.into(); + st.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight; + let mut line = PathData::new(vec![]); + line.subpaths.push(vectorcraft_geom::SubPath::polyline(&[(0.0, 2000.0).into(), (100_000.0, 2000.0).into()], false)); + t.kind = TextKind::OnPath { path: line, start: 0.0, end: None }; + t.xf = Affine::IDENTITY; + t.dynamic_text = true; + let lay = vectorcraft_text::layout(db, &t); + assert!((lay.fit_scale - 1.296).abs() < 1e-9, "{}", lay.fit_scale); + let em = 1296.0 / 0.7; + let mut glyphs = kurbo::BezPath::new(); + for g in &lay.glyphs { + glyphs.extend(g.outline.iter()); + } + let want = glyphs.bounding_box(); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let back = crate::import(&write(&doc).bytes).unwrap().document; + let size = texts(&back)[0].1.runs[0].style.size; + assert!((size - em).abs() < 1e-3, "{size} vs {em}"); + let back = crate::import(&write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }).bytes).unwrap().document; + let b = children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap(); + assert!((b.height() - want.height()).abs() < 0.05 && (b.width() - want.width()).abs() < 0.05, "{b:?}, laid out at {want:?}"); +} + /// Characters with Auto leading are written with their paragraph's Auto Leading share of the /// size: 18 pt type in paragraphs at 150% is written with 27 pt leading. #[test] diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index c95940b95d..032317ab7a 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -3,12 +3,13 @@ use super::encoding::{ unit, writable, }; use super::{ - Affine, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, Gradient, - GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE, + Affine, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, DYNAMIC_TEXT, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, + Gradient, GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE, LAYER_NAME, LIVE, LegacyAiOptions, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, Paint, ParaDirection, ParaStyle, PathData, ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; +use super::{CONIC, CONIC_WEDGES, DIAMOND}; pub(super) struct Writer<'a> { doc: &'a Document, @@ -38,6 +39,10 @@ pub(super) struct Writer<'a> { in_hidden: bool, /// The fonts type is set in: PostScript name, and whether it's TrueType. pub(super) fonts: Vec<(String, bool)>, + /// The Standard Vertical Roman Alignment the last `Tv` set (it lasts into later text objects). + roman: bool, + /// Inside a Kumi block `1 TY` began (Tate-chu-yoko in horizontal type). + kumi: bool, } impl<'a> Writer<'a> { @@ -58,6 +63,8 @@ impl<'a> Writer<'a> { hidden_art: vec![], in_hidden: false, fonts: vec![], + roman: false, + kumi: false, } } @@ -152,7 +159,9 @@ impl<'a> Writer<'a> { self.locked = false; self.line("0 A"); self.in_hidden = !n.visible; - self.contents(children, *clip, false); + // Ruler guides are kept in the document's native copy only. + let art: Vec> = children.iter().filter(|c| !c.is_ruler_guide()).cloned().collect(); + self.contents(&art, *clip, false); self.in_hidden = false; self.line("LB\n%AI5_EndLayer--"); true @@ -209,6 +218,10 @@ impl<'a> Writer<'a> { /// One object (inside a container locked when `locked`). fn node(&mut self, n: &Node, locked: bool) { + // Ruler guides are kept in the document's native copy only. + if n.is_ruler_guide() { + return; + } if !n.visible && !self.in_hidden { match self.hidden { HiddenObjects::Omit => { @@ -292,6 +305,8 @@ impl<'a> Writer<'a> { self.nest -= 1; } } + // Ruler guides are kept in the document's native copy only. + NodeKind::RulerGuide { .. } => {} } } @@ -415,6 +430,16 @@ impl<'a> Writer<'a> { if direct_fill(&f.paint) { return self.path_object(path, rule, Some(f), None); } + if let Paint::Gradient(g) = &f.paint + && g.gradient.kind == GradientKind::Conic + { + return self.conic_object(path, rule, f, g); + } + if let Paint::Gradient(g) = &f.paint + && g.gradient.kind == GradientKind::Diamond + { + return self.diamond_object(path, rule, f, g); + } let Paint::Pattern { pattern, xf } = &f.paint else { // A freeform gradient: its average colour. self.warn(FREEFORM); @@ -453,6 +478,71 @@ impl<'a> Writer<'a> { self.line("Q"); } + /// A conic gradient fill (the format has no conic gradient) as [`CONIC_WEDGES`] solid wedges + /// about its center clipped to `path` (filled by `rule`), each running on to the seam under + /// the next ([`vectorcraft_color::GradientGeom::conic_wedges`]). + fn conic_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, g: &GradientPaint) { + self.warn(CONIC); + if g.gradient.stops.iter().any(|s| s.opacity < 1.0) { + self.warn(TRANSPARENCY); + } + let area = path.to_bezpath().bounding_box(); + let wedges = g.resolve(area).conic_wedges(area, CONIC_WEDGES, true); + self.line("q"); + self.fill_rule(rule); + let several = path.subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { + self.mask(sp); + } + if several { + self.line("*U"); + } + for (pts, t) in wedges { + let (color, _) = g.gradient.sample_keep_model(t as f32); + let wedge = FillLayer { paint: Paint::solid(color), ..f.clone() }; + self.path_object(&PathData::single(SubPath::polyline(&pts, true)), FillRule::NonZero, Some(&wedge), None); + } + self.line("Q"); + } + + /// A diamond gradient fill (the format has no diamond gradient) as four linear gradients + /// clipped to `path` (filled by `rule`), one for each quadrant of its frame and equal to the + /// diamond there, each running on under the next + /// ([`vectorcraft_color::GradientGeom::diamond_quadrants`]). A diamond without an extent is its + /// last stop. + fn diamond_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, g: &GradientPaint) { + let area = path.to_bezpath().bounding_box(); + let Some(quadrants) = g.resolve(area).diamond_quadrants(area) else { + let color = g.gradient.stops.last().map_or(Color::gray(0.5), |s| s.color); + let flat = FillLayer { paint: Paint::solid(color), ..f.clone() }; + return self.path_object(path, rule, Some(&flat), None); + }; + self.warn(DIAMOND); + self.line("q"); + self.fill_rule(rule); + let several = path.subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { + self.mask(sp); + } + if several { + self.line("*U"); + } + let gradient = Gradient { kind: GradientKind::Linear, ..g.gradient.clone() }; + for (pts, geom) in quadrants { + // Not named after the swatch: the definition is a linear gradient, not the swatch's. + let linear = GradientPaint { gradient: gradient.clone(), geom: Some(geom), swatch: None, ..g.clone() }; + let quadrant = FillLayer { paint: Paint::Gradient(Box::new(linear)), ..f.clone() }; + self.path_object(&PathData::single(SubPath::polyline(&pts, true)), FillRule::NonZero, Some(&quadrant), None); + } + self.line("Q"); + } + /// A path object painted with `fill` (a colour or a linear or radial gradient) and `stroke` /// (a plain line of a colour) over it; several subpaths make a compound path. fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) { @@ -649,15 +739,15 @@ impl<'a> Writer<'a> { // ---------- type ---------- /// Type: a text object when the format can hold it as text, else its outlines (type with - /// rotated characters among them, which keeps their rotation). A run whose - /// font size measures a height other than the em box is written at the em size it is drawn - /// at ([`vectorcraft_text::FontDb::font_heights_resolved`]). + /// rotated characters among them, which keeps their rotation). fn text(&mut self, t: &TextObject) { if !invertible(t.xf) { return; } - let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t); - let t = &*resolved; + // Written as text or as outlines, the type keeps its drawn sizes but not the setting. + if t.dynamic_text && matches!(t.kind, TextKind::OnPath { .. }) { + self.warn(DYNAMIC_TEXT); + } if !self.outline_text { if writable(self.doc, t) { return self.text_object(t); @@ -675,17 +765,18 @@ impl<'a> Writer<'a> { /// A text object (§15): `type To`, the text path (`a b c d tx ty startPt Tp`, an area's frame /// or the path type runs along, `TP`), then each run's style and characters, `TO`. The matrix /// takes text space (y up, the first baseline's start for point type) to art space; the frame - /// and path are in art space, as the specification's examples have them (§15.5). + /// and path are in art space, as the specification's examples have them (§15.5). Type that + /// Shrink Text to Fit or Dynamic Text scales is written in the styles it draws in, fitted at + /// the sizes the Character panel shows; then a run whose font size measures a height other + /// than the em box is written at the em size it is drawn at + /// ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn text_object(&mut self, t: &TextObject) { if lost_attributes(t) { self.warn(TYPE_ATTRIBUTES); } - // Area type that Shrink Text to Fit scales down is written in the styles it draws in. - let fitted = matches!((&t.kind, t.area.fit), (TextKind::Area { .. }, vectorcraft_doc::AreaFit::ShrinkText { .. })) - .then(|| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale) - .filter(|f| *f != 1.0) - .map(|f| vectorcraft_text::scaled(t, f)); - let t = fitted.as_ref().unwrap_or(t); + let fitted = vectorcraft_text::drawn(t); + let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(&fitted); + let t = &*resolved; let m = self.to_art * t.xf * Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); let (kind, path, start) = match &t.kind { TextKind::Point => (0, None, 0.0), @@ -734,6 +825,10 @@ impl<'a> Writer<'a> { self.line(" Tx"); } } + if self.kumi { + self.line("0 TY"); + self.kumi = false; + } self.line("TO"); } @@ -753,7 +848,8 @@ impl<'a> Writer<'a> { } /// A run's character attributes and paint style: `Tr`, its fill and stroke, `Tf`, `Ts`, `Tz`, - /// `Tt`, `TA`, and the leading with the space before its paragraph, `Tl`. + /// `Tt`, `TA`, and the leading with the space before its paragraph, `Tl`; then `Tv` and `TY` + /// where Standard Vertical Roman Alignment or Tate-chu-yoko changes. fn char_style(&mut self, st: &CharStyle, p: &ParaStyle) { let fill = !st.fill.is_none(); let stroke = st.has_stroke(); @@ -791,6 +887,14 @@ impl<'a> Writer<'a> { let leading = st.leading.unwrap_or_else(|| p.justification.auto_leading_for(st.size)); ps::push_nums(&mut self.body, &[finite(leading, size * 1.2), finite(p.space_before, 0.0)]); self.line("Tl"); + if st.standard_vertical_roman != self.roman { + self.roman = st.standard_vertical_roman; + self.line(if self.roman { "1 Tv" } else { "0 Tv" }); + } + if st.tate_chu_yoko != self.kumi { + self.kumi = st.tate_chu_yoko; + self.line(if self.kumi { "1 TY" } else { "0 TY" }); + } } /// Type as its glyphs' outlines: a group of a compound path for each run, with the run's fill diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 974831b703..96205aa7d3 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -42,6 +42,10 @@ const SPOT_GRADIENTS_L2: &str = "gradients mixing a spot color with other inks are written in process colors at PostScript Level 2 (Level 3 keeps the spot inks)"; const SPOT_GRADIENTS_SHARED: &str = "gradients whose spot inks can't share a DeviceN color space are written without the spot inks"; const SPOT_GRADIENTS_PERCEPTUAL: &str = "Perceptual gradients of spot colors are written in process colors"; +const CONIC_WEDGES: &str = "conic gradients are written as solid wedges (EPS has no conic shading)"; +const DIAMOND_QUADRANTS: &str = "diamond gradients are written as four linear gradients (EPS has no diamond shading)"; +/// Wedges a conic gradient is written as: one a degree. +const CONIC_WEDGE_COUNT: usize = 360; /// The most colorants a DeviceN color space may have (PostScript's limit). const MAX_DEVICE_N: usize = 32; const MISSING_PATTERN: &str = "missing patterns are written as mid-grey"; @@ -389,6 +393,8 @@ impl<'a> Scene<'a> { self.node(c, false); } } + // Ruler guides draw on screen only. + NodeKind::RulerGuide { .. } => {} } if self.body.len() > MAX_BODY { self.body.truncate(was); @@ -929,8 +935,9 @@ impl<'a> Scene<'a> { (space, out) } - /// Paint all of `area` (inside the current clip) with linear or radial gradient `g`, placed on - /// `bounds`: a smooth shading at Level 3, else stepped fills. + /// Paint all of `area` (inside the current clip) with linear, radial, conic or diamond gradient + /// `g`, placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at + /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) { let geom = g.resolve(bounds); let (space, stops) = self.gradient_stops(&g.gradient); @@ -944,6 +951,8 @@ impl<'a> Scene<'a> { let space = &space; let smooth = self.o.level == Level::Three && !self.o.compatible_gradients; match g.gradient.kind { + GradientKind::Conic => self.conic_steps(&geom, area, space, &stops), + GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth), GradientKind::Radial => { let r = geom.length().max(1e-6); let squash = geom.radial_squash(); @@ -972,6 +981,63 @@ impl<'a> Scene<'a> { } } + /// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area` + /// (PostScript has no conic shading), each running on to the seam under the next, so no + /// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]). + fn conic_steps(&mut self, geom: &vectorcraft_color::GradientGeom, area: Rect, space: &GradientSpace, stops: &[(f64, Vec)]) { + self.warn(CONIC_WEDGES); + let at = |t: f64| match stops.windows(2).find(|w| t <= w[1].0) { + Some(w) if w[1].0 > w[0].0 => mix(&w[0].1, &w[1].1, ((t - w[0].0) / (w[1].0 - w[0].0)).clamp(0.0, 1.0) as f32), + Some(w) => w[1].1.clone(), + None => stops.last().map_or_else(Vec::new, |s| s.1.clone()), + }; + for (pts, t) in geom.conic_wedges(area, CONIC_WEDGE_COUNT, true) { + self.set_comps(space, &at(t)); + for (i, p) in pts.iter().enumerate() { + push_nums(&mut self.body, &[p.x, p.y]); + self.line(if i == 0 { "newpath moveto" } else { "lineto" }); + } + self.line("closepath fill"); + } + } + + /// A diamond gradient over `area` as four linear gradients, each clipped to a quadrant of its + /// frame and equal to the diamond there (PostScript has no diamond shading; + /// [`vectorcraft_color::GradientGeom::diamond_quadrants`]): smooth axial shadings, else + /// stepped fills. Each quadrant but the last runs on under the next (stops are opaque here), + /// so no hairline shows between them. A diamond without an extent is its last stop. + fn diamond_quadrants( + &mut self, + geom: &vectorcraft_color::GradientGeom, + area: Rect, + space: &GradientSpace, + stops: &[(f64, Vec)], + smooth: bool, + ) { + let Some(quadrants) = geom.diamond_quadrants(area) else { + if let Some((_, c)) = stops.last() { + self.set_comps(space, c); + self.rect_fill(area); + } + return; + }; + self.warn(DIAMOND_QUADRANTS); + for (pts, q) in quadrants { + self.line("q"); + for (i, p) in pts.iter().enumerate() { + push_nums(&mut self.body, &[p.x, p.y]); + self.line(if i == 0 { "newpath moveto" } else { "lineto" }); + } + self.line("closepath clip newpath"); + if smooth { + self.shading(2, space, &[q.start.x, q.start.y, q.end.x, q.end.y], stops); + } else { + self.linear_steps(q.start, q.end, area, space, stops); + } + self.line("Q"); + } + } + /// A Level 3 smooth shading of `kind` (2 axial, 3 radial) at `coords`, extended both ways. fn shading(&mut self, kind: u8, space: &GradientSpace, coords: &[f64], stops: &[(f64, Vec)]) { let n = space.n(); diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index f447d7b7d9..db9ae2837c 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -189,6 +189,61 @@ fn gradients_are_smooth_shadings_at_level_3_and_stepped_fills_at_level_2() { assert_eq!(dsc(&ps, "LanguageLevel").as_deref(), Some("2")); } +/// PostScript has no conic shading: a conic is solid wedges about its center at both levels, each +/// running on to the seam, and read back from the PostScript it looks as the canvas paints it. +#[test] +fn conic_gradients_are_solid_wedges_at_both_levels() { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + for aspect in [1.0, -0.5] { + let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops.clone())); + g.geom = Some(vectorcraft_color::GradientGeom { start: Point::new(100.0, 70.0), end: Point::new(150.0, 70.0), aspect, focal: None }); + let paint = Paint::Gradient(Box::new(g)); + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 120.0)), paint, Paint::None, 0.0)]); + for o in [opts(&d), EpsOptions { level: Level::Two, ..opts(&d) }] { + let out = export(&d, &o, None, None).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("conic gradients are written as solid wedges")), "{:?}", out.warnings); + let page = page_of(&d, &o); + assert!(!page.contains("shfill"), "no shading stands in"); + assert_eq!(page.matches("closepath fill").count(), 360, "a wedge a degree"); + } + let out = export(&d, &opts(&d), None, None).unwrap(); + let back = import_with(&out.bytes, false).unwrap().document; + vectorcraft_testkit::raster::assert_similar( + &vectorcraft_testkit::raster::render_artboard(&d), + &vectorcraft_testkit::raster::render_artboard(&back), + 8.0, + 0.01, + ); + } +} + +/// PostScript has no diamond shading: a diamond is four axial shadings at Level 3 (stepped fills at +/// Level 2), each clipped to a quadrant of its frame, and read back from the PostScript it looks +/// as the canvas paints it, with no hairline between the quadrants. +#[test] +fn diamond_gradients_are_four_linear_gradients_clipped_to_quadrants() { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops)); + g.geom = Some(vectorcraft_color::GradientGeom { start: Point::new(100.0, 70.0), end: Point::new(140.0, 40.0), aspect: 0.6, focal: None }); + let paint = Paint::Gradient(Box::new(g)); + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 120.0)), paint, Paint::None, 0.0)]); + for (o, shadings) in [(opts(&d), 4), (EpsOptions { level: Level::Two, ..opts(&d) }, 0)] { + let out = export(&d, &o, None, None).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("diamond gradients are written as four linear gradients")), "{:?}", out.warnings); + let page = page_of(&d, &o); + assert_eq!(page.matches("shfill").count(), shadings); + assert_eq!(page.matches("closepath clip newpath").count(), 4, "a clip a quadrant"); + } + let out = export(&d, &opts(&d), None, None).unwrap(); + let back = import_with(&out.bytes, false).unwrap().document; + vectorcraft_testkit::raster::assert_similar( + &vectorcraft_testkit::raster::render_artboard(&d), + &vectorcraft_testkit::raster::render_artboard(&back), + 6.0, + 0.01, + ); +} + #[test] fn strokes_keep_their_caps_joins_and_dashes() { let d = doc_with(|d| { diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 667b39aad2..cd64fcbb50 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -239,6 +239,9 @@ struct Body { fn body(doc: &Document, o: &SaveOptions) -> Result { let version = o.version; let mut d = doc.without_edit_modes().into_owned(); + // Ruler guides are saved in the document's `guides` list, as before they were nodes, so every + // version reads them. + d.guides_to_saved(); // Older apps don't know placed documents: they get the art the objects show, with its // resources. Otherwise resources only exporting adds are never saved. if version < VERSION && d.has_placed() { @@ -591,6 +594,10 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result doc.raster_effects.add_around = doc.raster_effects.add_around.clamp(0.0, vectorcraft_doc::rastersettings::MAX_ADD_AROUND); let mut depth_notes = vec![]; doc.limit_depth_noting(&mut depth_notes); + // Untrusted: ruler guide nodes only directly in layers, above their art (after the depth limit: + // the walk recurses; before the canvas check, which takes a layer's first member as its + // clipping path). + doc.tidy_ruler_guides(); // Untrusted: nothing beyond the canvas, where no edit may leave anything (after the depth // limit: the walk recurses). A file whose artboards all lie there has no page to show (#3575). let had_artboards = !doc.artboards.is_empty(); @@ -602,6 +609,9 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result ))); } depth_notes.extend(beyond.note()); + // The saved ruler guides become nodes on their layers (after the guides beyond the canvas are + // dropped, and after `fix_next_id`: new ids start above the file's). + doc.guides_into_nodes(); // Untrusted: the type's sizes, leading, baseline shifts and scales, its indents and paragraph // spacing, and its tab stops, each within its range (after the depth limit: the walk recurses). doc.keep_type_values_in_range(); @@ -1203,6 +1213,66 @@ mod tests { assert_eq!(load(&bytes).unwrap().node_count(), n, "the real budget opens ordinary documents"); } + /// The saved ruler guides become objects when read, so each counts against the same budget. + #[test] + fn saved_ruler_guides_count_against_the_object_budget() { + let mut d = Document::new(100.0, 100.0); + let l = d.add_layer(None); + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap(); + for i in 0..50 { + d.add_ruler_guide(&vectorcraft_doc::Guide::new(i % 2 == 0, f64::from(i))); + } + let n = d.node_count() + d.ruler_guides().len(); + let bytes = save_with(&d, &SaveOptions { compress: true, ..SaveOptions::default() }).unwrap(); + let opened = load_file_within(&bytes, n, vectorcraft_doc::node::MAX_BUFFERED_VALUES).unwrap().doc; + assert_eq!(opened.ruler_guides().len(), 50, "a document of exactly the budget opens with its guides"); + let Err(FormatError::NotVectorcraft(why)) = load_file_within(&bytes, n - 1, vectorcraft_doc::node::MAX_BUFFERED_VALUES) else { + panic!("one guide past the budget must be refused") + }; + assert!(why.contains(&format!("more than {} objects", n - 1)), "{why}"); + } + + /// Ruler guide nodes a file holds out of place are put right as it is read: one below a layer's + /// art moves up to the layer's guides, and one in a group, beside the layers or in a symbol is + /// removed. Saving again writes no ruler guide node, which builds from before ruler guides + /// were nodes could not read. + #[test] + fn ruler_guide_nodes_out_of_place_in_a_file_are_put_right() { + let mut d = Document::new(100.0, 100.0); + let l = d.add_layer(None); + let (a, b, group) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id| Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.insert(Some(l), 0, path(a)).unwrap(); + d.insert(Some(l), usize::MAX, Node::group(group, vec![Arc::new(path(b))])).unwrap(); + let li = d.layers.iter().position(|x| x.id == l).unwrap(); + let mut v: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + let guide = |id: u64| serde_json::json!({"id": id, "kind": {"type": "rulerguide", "vertical": true, "pos": 5.0}}); + let kids = &mut v["document"]["layers"][li]["kind"]["children"]; + kids.as_array_mut().unwrap().insert(0, guide(50)); + kids[2]["kind"]["children"].as_array_mut().unwrap().push(guide(51)); + v["document"]["layers"].as_array_mut().unwrap().push(guide(52)); + let opened = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + let listed: Vec = opened.ruler_guides().iter().filter_map(|g| g.id).map(|id| id.0).collect(); + assert_eq!(listed, [50]); + let layer = opened.layers.iter().find(|x| x.id == l).unwrap(); + assert_eq!(layer.children().unwrap().iter().map(|c| c.id.0).collect::>(), [a.0, group.0, 50], "art first, then the guide"); + assert_eq!(opened.node(group).unwrap().children().unwrap().len(), 1, "the group keeps only its path"); + assert!(opened.layers.iter().all(|x| !x.is_ruler_guide())); + assert!(!String::from_utf8(save(&opened, false)).unwrap().contains("rulerguide")); + + // A ruler guide in a symbol's art is removed too. + let mut d = Document::new(100.0, 100.0); + let sym = d.alloc_id(); + let art = Node::group(sym, vec![Arc::new(path(d.alloc_id()))]); + d.symbols.push(vectorcraft_doc::Symbol { name: "S".into(), art: Arc::new(art), dynamic: false }); + let mut v: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + v["document"]["symbols"][0]["art"]["kind"]["children"].as_array_mut().unwrap().push(guide(60)); + let opened = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + assert_eq!(opened.symbols[0].art.children().unwrap().len(), 1); + assert!(!opened.symbols[0].art.children().unwrap().iter().any(|c| c.is_ruler_guide())); + } + /// #3587: a reordered file (its objects' fields before their `type`, as a JSON tool that /// sorts keys writes them) still opens; one whose fields before a `type` hold more values than /// the budget, such as a long array of numbers, is refused as they are read. @@ -1316,4 +1386,35 @@ mod tests { assert_eq!(base64_decode("QUI="), Some(vec![0x41, 0x42])); assert_eq!(base64_decode("QUJD"), Some(vec![0x41, 0x42, 0x43])); } + + /// A layer clipping by a path beyond the canvas is emptied on open and stops clipping, also + /// when the file puts a ruler guide before the clipping path: no other object becomes it. + #[test] + fn a_guide_before_a_clipping_path_beyond_the_canvas_does_not_change_the_clipping_path() { + let opened = |guide_first: bool| { + let mut d = Document::new(100.0, 100.0); + let rect = |d: &mut Document, y: f64| { + Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, y, 10.0, y + 10.0)), Appearance::default_art())) + }; + let (far, near) = (rect(&mut d, 1e17), rect(&mut d, 0.0)); + if let NodeKind::Layer { children, clip, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *children = vec![far, near]; + *clip = true; + } + // Saving writes ruler guides to the saved list: the guide node is put in the file. + let mut v: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + let guide = serde_json::json!({"id": 50, "kind": {"type": "rulerguide", "vertical": true, "pos": 5.0}}); + let kids = v["document"]["layers"][0]["kind"]["children"].as_array_mut().unwrap(); + if guide_first { + kids.insert(0, guide) + } else { + kids.push(guide) + } + let d = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + let NodeKind::Layer { children, clip, .. } = &d.layers[0].kind else { panic!("a layer") }; + (*clip, children.iter().map(|c| c.is_ruler_guide()).collect::>()) + }; + assert_eq!(opened(false), (false, vec![true]), "the clipping path and what it clipped go; the guide stays"); + assert_eq!(opened(true), opened(false)); + } } diff --git a/crates/format/tests/it/main.rs b/crates/format/tests/it/main.rs index a5f028c384..2272f42f72 100644 --- a/crates/format/tests/it/main.rs +++ b/crates/format/tests/it/main.rs @@ -3,6 +3,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod links; +mod native_guides; mod native_v3; mod native_v4; mod save_options; diff --git a/crates/format/tests/it/native_guides.rs b/crates/format/tests/it/native_guides.rs new file mode 100644 index 0000000000..614ceded63 --- /dev/null +++ b/crates/format/tests/it/native_guides.rs @@ -0,0 +1,146 @@ +//! Ruler guides in `.vectorcraft` files of every version: the saved `guides` list becomes ruler +//! guide nodes on their layers when a file opens, and is written back as the same list. + +use serde::Deserialize; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LayerColor, Node, NodeId}; +use vectorcraft_format::{MIN_VERSION, SaveOptions, VERSION, load, save_with}; +use vectorcraft_testkit::fixtures; + +fn json_of(bytes: &[u8]) -> Value { + serde_json::from_slice(bytes).unwrap() +} + +fn save_v(d: &Document, version: u32) -> Vec { + save_with(d, &SaveOptions { version, ..SaveOptions::default() }).unwrap() +} + +/// The document of a saved file without its guide list and its next id (giving guides ids +/// raises the next id). +fn without_guides(v: &Value) -> Value { + let mut d = v["document"].clone(); + let o = d.as_object_mut().unwrap(); + o.remove("guides"); + o.remove("next_id"); + d +} + +/// A document with art on two layers, a sublayer in the bottom one, and two artboards: +/// (document, bottom layer, sublayer, top layer, second artboard's id). +fn doc() -> (Document, NodeId, NodeId, NodeId, u32) { + let mut d = (*fixtures::rich_session().doc().unwrap().doc).clone(); + let bottom = d.layers[0].id; + let sub = d.alloc_id(); + d.insert(Some(bottom), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap(); + let top = d.add_layer(Some("Top")); + let mut ab = d.artboards[0].clone(); + ab.id = d.next_artboard_id(); + d.artboards.push(ab); + let board = d.artboards[1].id; + (d, bottom, sub, top, board) +} + +/// Each version's file with a guide on no layer, one on a sublayer, one on a layer that is gone, +/// and an artboard guide, as files written before ruler guides were nodes hold them: it opens +/// with the guides on their layers, saves the same lines with their layers and ids, and saving +/// what that file opens to gives the same `guides` list again. The rest of the document is saved +/// as it was. +#[test] +fn every_version_reads_and_writes_back_the_same_guides() { + let (d, bottom, sub, top, board) = doc(); + for version in MIN_VERSION..=VERSION { + let mut v = json_of(&save_v(&d, version)); + assert_eq!(v["version"], version); + let plain = without_guides(&v); + v["document"]["guides"] = json!([ + {"vertical": true, "pos": 12.5}, + {"vertical": false, "pos": 40.0, "layer": sub}, + {"vertical": true, "pos": 70.0, "layer": 99_999}, + {"vertical": false, "pos": 90.0, "layer": bottom, "artboard": board}, + ]); + let opened = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + let guides = opened.ruler_guides(); + let lines: Vec<_> = guides.iter().map(|g| (g.vertical, g.pos, g.artboard, g.layer)).collect(); + // On no layer and on a deleted layer: the top visible, unlocked layer. + assert_eq!( + lines, + [(true, 12.5, None, Some(top)), (false, 40.0, None, Some(sub)), (true, 70.0, None, Some(top)), (false, 90.0, Some(board), Some(bottom))], + "version {version}" + ); + for g in &guides { + let n = opened.node(g.id.unwrap()).unwrap(); + assert!(n.is_ruler_guide() && n.visible && !n.locked && n.name.is_none(), "version {version}"); + // Each sits at the top of its layer, above the art. + let kids = opened.node(g.layer.unwrap()).unwrap().children().unwrap(); + let first_guide = kids.iter().position(|c| c.is_ruler_guide()).unwrap(); + assert!(kids[first_guide..].iter().all(|c| c.is_ruler_guide()), "version {version}"); + } + + let once = json_of(&save_v(&opened, version)); + assert_eq!(once["version"], version); + let saved: Vec<_> = once["document"]["guides"] + .as_array() + .unwrap() + .iter() + .map(|g| (g["vertical"].clone(), g["pos"].clone(), g.get("artboard").cloned(), g["layer"].clone(), g["id"].is_u64())) + .collect(); + assert_eq!( + saved, + [ + (json!(true), json!(12.5), None, json!(top), true), + (json!(false), json!(40.0), None, json!(sub), true), + (json!(true), json!(70.0), None, json!(top), true), + (json!(false), json!(90.0), Some(json!(board)), json!(bottom), true), + ], + "version {version}" + ); + assert_eq!(without_guides(&once), plain, "version {version}: the rest of the document"); + + let reopened = load(&serde_json::to_vec(&once).unwrap()).unwrap(); + assert_eq!(reopened.ruler_guides(), guides, "version {version}: same ids, layers and lines"); + let twice = json_of(&save_v(&reopened, version)); + assert_eq!(twice["document"]["guides"], once["document"]["guides"], "version {version}"); + } +} + +/// The guide entry of a build from before ruler guides were nodes, field for field. +#[derive(Debug, PartialEq, Deserialize)] +struct OldGuide { + vertical: bool, + pos: f64, + #[serde(default)] + artboard: Option, + #[serde(default)] + layer: Option, +} + +/// An older build reads the guides a file now saves, the new fields (id, name, lock, visibility) +/// included, as the same lines on the same layers. +#[test] +fn an_older_guide_entry_reads_the_saved_guides() { + let (mut d, bottom, sub, _, board) = doc(); + let mut g = vectorcraft_doc::Guide::new(true, 15.0); + g.layer = Some(sub); + g.name = Some("Fold".into()); + g.locked = true; + g.hidden = true; + d.add_ruler_guide(&g); + d.add_ruler_guide(&vectorcraft_doc::Guide { layer: Some(bottom), artboard: Some(board), ..vectorcraft_doc::Guide::new(false, 25.0) }); + for version in MIN_VERSION..=VERSION { + let v = json_of(&save_v(&d, version)); + let entries = v["document"]["guides"].as_array().unwrap(); + assert_eq!(entries[0]["name"], "Fold", "the new fields are written"); + let old: Vec = serde_json::from_value(v["document"]["guides"].clone()).unwrap(); + assert_eq!( + old, + [ + OldGuide { vertical: true, pos: 15.0, artboard: None, layer: Some(sub) }, + OldGuide { vertical: false, pos: 25.0, artboard: Some(board), layer: Some(bottom) }, + ], + "version {version}" + ); + // And this build reads its own lock, visibility and name back. + let back = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + assert_eq!(back.ruler_guides(), d.ruler_guides(), "version {version}"); + } +} diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index 6a96fae79d..512025375e 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -293,13 +293,21 @@ fn artboard_guides_round_trip_and_canvas_guides_save_as_before() { use vectorcraft_doc::Guide; let mut d = Document::new(100.0, 100.0); let id = d.artboards[0].id; - d.guides = vec![Guide::new(true, 10.0), Guide { artboard: Some(id), ..Guide::new(false, 20.0) }]; + d.add_ruler_guide(&Guide::new(true, 10.0)); + d.add_ruler_guide(&Guide { artboard: Some(id), ..Guide::new(false, 20.0) }); let mut v = json_of(&save(&d, false)); - assert_eq!(v["document"]["guides"], json!([{"vertical": true, "pos": 10.0}, {"vertical": false, "pos": 20.0, "artboard": id}])); - assert_eq!(load(&save(&d, false)).unwrap().guides, d.guides); + let lines: Vec<_> = v["document"]["guides"] + .as_array() + .unwrap() + .iter() + .map(|g| json!({"vertical": g["vertical"], "pos": g["pos"], "artboard": g.get("artboard")})) + .collect(); + assert_eq!(lines, [json!({"vertical": true, "pos": 10.0, "artboard": null}), json!({"vertical": false, "pos": 20.0, "artboard": id})]); + assert_eq!(load(&save(&d, false)).unwrap().ruler_guides(), d.ruler_guides()); v["document"]["guides"] = json!([{"vertical": false, "pos": 20.0}]); let old = load(&serde_json::to_vec(&v).unwrap()).unwrap(); - assert_eq!(old.guides, [Guide::new(false, 20.0)]); + let old_lines: Vec<_> = old.ruler_guides().into_iter().map(|g| (g.vertical, g.pos, g.artboard)).collect(); + assert_eq!(old_lines, [(false, 20.0, None)]); } #[test] diff --git a/crates/geom/src/arc.rs b/crates/geom/src/arc.rs index c4fe640ae2..644dc44f6a 100644 --- a/crates/geom/src/arc.rs +++ b/crates/geom/src/arc.rs @@ -2,7 +2,7 @@ //! distance along it of the point nearest another (type on a path lays its glyphs out and the //! selection tools drag its brackets by distance along the path). -use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg, Point, Vec2}; +use kurbo::{Affine, ParamCurve, ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest, PathSeg, Point, Vec2}; use crate::PathData; @@ -76,6 +76,78 @@ impl ArcPath { pub fn fraction_at(&self, p: Point) -> Option { (self.len > 0.0).then(|| self.nearest(p)).flatten().map(|s| (s / self.len).clamp(0.0, 1.0)) } + + /// The distance along the path of the middle of its topmost points (the least y) where `xf` + /// draws it: the topmost point when there is one, the middle of a level stretch (a + /// rectangle's top edge), and when several points or stretches are topmost, the middle of the + /// shortest part of the path that holds them all. None for a path with no length, or a closed + /// path whose every point is topmost. + pub fn topmost(&self, xf: Affine) -> Option { + let drawn: Vec<(PathSeg, PathSeg, f64, f64)> = self.segs.iter().map(|&(s, c, l)| (s, xf * s, c, l)).collect(); + // The candidates for the least y in each segment: its ends and where it turns. + let turns = |d: &PathSeg| [0.0, 1.0].into_iter().chain(d.extrema()).collect::>(); + let mut bounds: Option = None; + let mut top = f64::INFINITY; + for (_, d, _, _) in &drawn { + let b = d.bounding_box(); + bounds = Some(bounds.map_or(b, |a| a.union(b))); + top = turns(d).into_iter().map(|t| d.eval(t).y).fold(top, f64::min); + } + let b = bounds?; + if !(top.is_finite() && b.width().is_finite() && b.height().is_finite()) { + return None; + } + // Points this close to the top count as topmost: a part of the drawn size, and no less than + // the rounding error of coordinates this far from the origin. + let tol = (1e-9 * (b.width() + b.height())).max(64.0 * f64::EPSILON * b.y0.abs().max(b.y1.abs())); + // Stretches this close along the path meet. + let near = 1e-9 * self.len; + // The topmost points as stretches of distance along the path, in order. + let mut runs: Vec<(f64, f64)> = vec![]; + for (s, d, c, l) in &drawn { + let db = d.bounding_box(); + if db.y1 - db.y0 <= tol && db.y0 <= top + tol { + runs.push((*c, c + l)); + continue; + } + for t in turns(d) { + if d.eval(t).y <= top + tol { + let at = c + s.subsegment(0.0..t).arclen(ACCURACY).min(*l); + runs.push((at, at)); + } + } + } + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + // Stretches that meet or overlap are one. + let mut merged: Vec<(f64, f64)> = vec![]; + for (a, z) in runs { + match merged.last_mut() { + Some(last) if a <= last.1 + near => last.1 = last.1.max(z), + _ => merged.push((a, z)), + } + } + let (first, last) = (*merged.first()?, *merged.last()?); + if !self.closed { + return Some((first.0 + last.1) * 0.5); + } + let len = self.len; + // Round a closed path, the shortest part holding every stretch leaves out the longest + // gap between two of them (the gap from the last round to the first included). + let wrap = first.0 + len - last.1; + let (mut gap, mut from, mut to) = (wrap, first.0, last.1); + for w in merged.windows(2) { + if let [a, b] = w + && b.0 - a.1 > gap + { + (gap, from, to) = (b.0 - a.1, b.0, a.1); + } + } + if gap <= near { + return None; + } + let run = (to - from).rem_euclid(len); + Some((from + run * 0.5).rem_euclid(len)) + } } #[cfg(test)] @@ -99,4 +171,64 @@ mod tests { assert!(sq.at(45.0).0.distance(sq.at(5.0).0) < 1e-6); assert!(ArcPath::new(&PathData::default()).is_empty()); } + + fn polyline(points: &[Point], closed: bool) -> PathData { + PathData::single(crate::SubPath::polyline(points, closed)) + } + + /// Where `topmost` puts the middle, drawn by `xf`. + fn top_point(a: &ArcPath, xf: Affine) -> Point { + xf * a.at(a.topmost(xf).unwrap()).0 + } + + #[test] + fn topmost_points_as_drawn() { + // A circle starts at 9 o'clock and runs clockwise (y down): its top is a quarter of the way round, its + // bottom three quarters. + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0))); + assert!((circle.topmost(Affine::IDENTITY).unwrap() - circle.len() * 0.25).abs() < 1e-6); + assert!((circle.topmost(Affine::FLIP_Y).unwrap() - circle.len() * 0.75).abs() < 1e-6); + // As the transform draws it: turned a quarter turn the other way, 3 o'clock is at the top. + let turned = Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(50.0, 50.0)); + assert!((circle.topmost(turned).unwrap() - circle.len() * 0.5).abs() < 1e-6); + // Turned part way, the top lies inside a segment. + let tilted = Affine::rotate_about(0.4, Point::new(50.0, 50.0)); + assert!(top_point(&circle, tilted).distance(Point::new(50.0, 0.0)) < 0.05, "{:?}", top_point(&circle, tilted)); + // An ellipse squashed and skewed by its transform. + let skewed = Affine::skew(0.5, 0.0) * Affine::scale_non_uniform(2.0, 0.5); + let p = top_point(&circle, skewed); + let lowest = (0..3600).map(|i| (skewed * circle.at(circle.len() * i as f64 / 3600.0).0).y).fold(f64::INFINITY, f64::min); + assert!((p.y - lowest).abs() < 1e-3, "{p:?} {lowest}"); + // A level top: the middle of the top edge, for a rectangle and a rounded rectangle. + for path in [shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)), shapes::rounded_rectangle(Rect::new(10.0, 20.0, 110.0, 70.0), 8.0)] { + let a = ArcPath::new(&path); + assert!(top_point(&a, Affine::IDENTITY).distance(Point::new(60.0, 20.0)) < 1e-6, "{:?}", top_point(&a, Affine::IDENTITY)); + assert!(top_point(&a, Affine::FLIP_Y).distance(Point::new(60.0, -70.0)) < 1e-6); + } + // Far from the origin the top is still the top edge's middle. + let square = ArcPath::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))); + let far = Affine::translate((1e12, 1e12)); + assert!(top_point(&square, far).distance(Point::new(1e12 + 50.0, 1e12)) < 1e-3, "{:?}", top_point(&square, far)); + // A level top across the path's start: the start in the middle of the top edge. + let across = ArcPath::new(&polyline( + &[Point::new(50.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0), Point::new(0.0, 50.0), Point::new(0.0, 0.0)], + true, + )); + assert!(top_point(&across, Affine::IDENTITY).distance(Point::new(50.0, 0.0)) < 1e-6); + // Two peaks: the middle of the shortest part that holds both, the dip between them. + let peaks = ArcPath::new(&polyline( + &[Point::new(0.0, 10.0), Point::new(2.0, 0.0), Point::new(4.0, 5.0), Point::new(6.0, 0.0), Point::new(8.0, 10.0)], + true, + )); + assert!(top_point(&peaks, Affine::IDENTITY).distance(Point::new(4.0, 5.0)) < 1e-6, "{:?}", top_point(&peaks, Affine::IDENTITY)); + // An open path: the middle of its topmost points too. + let open = ArcPath::new(&polyline(&[Point::new(0.0, 10.0), Point::new(5.0, 0.0), Point::new(10.0, 10.0)], false)); + assert!(top_point(&open, Affine::IDENTITY).distance(Point::new(5.0, 0.0)) < 1e-6); + // No top: a closed path that is level all round, and a path with no length. + let flat = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 10.0, 100.0, 10.0))); + assert!(!flat.is_empty() && flat.topmost(Affine::IDENTITY).is_none()); + assert!(ArcPath::new(&PathData::default()).topmost(Affine::IDENTITY).is_none()); + let point = ArcPath::new(&polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], true)); + assert!(point.topmost(Affine::IDENTITY).is_none()); + } } diff --git a/crates/js/Cargo.toml b/crates/js/Cargo.toml index 5848c1a914..c12871583a 100644 --- a/crates/js/Cargo.toml +++ b/crates/js/Cargo.toml @@ -11,7 +11,15 @@ workspace = true [dependencies] chrono = { workspace = true } -unicode-general-category = "1" +# Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license, +# which is not on the license allowlist, so the version is exact. +unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] } +# The seed of Math.random (interp.rs). +getrandom = "0.4" + +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] +# The browser's crypto.getRandomValues. +getrandom = { version = "0.4", features = ["wasm_js"] } [dev-dependencies] proptest = { workspace = true } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 5a4363108a..8d9ffc06c0 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -187,7 +187,8 @@ pub enum Expr { qualifier: Option, name: XmlNamePart, }, - /// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope. + /// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope + /// that holds it, and also an assignment, update or `delete` target. XmlScopeName(ExprId), /// `object..name`. XmlDescendants { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f7c21a8d8e..301b1235a4 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -466,6 +466,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; + interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); units.extend(HEAD.encode_utf16()); for (i, p) in parts.iter().enumerate() { @@ -554,6 +555,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult<()> { @@ -278,17 +279,20 @@ fn join_with(interp: &mut Interp, o: ObjId, separator: &Value, item: fn(&mut Int if len == 0 { return Ok(Value::str("")); } - let flat = sep.flat(); - let sep = &flat[..]; - // A result that cannot fit is refused before any element is read. - let least = (sep.len() as u64).saturating_mul(u64::from(len - 1)); - if least > (interp.limits.heap_bytes / 4) as u64 { - return Err(Abrupt::Limit(crate::LimitKind::Heap)); - } - interp.join_stack.push(o); - let r = join_elements(interp, o, len, sep, item); - interp.join_stack.pop(); - r + // The separator stays rooted for the whole join, so its flattened copy stays counted. + interp.rooted(&[Value::String(sep.clone())], |interp| { + let flat = flat_charged(interp, &sep)?; + let sep = &flat[..]; + // A result that cannot fit is refused before any element is read. + let least = (sep.len() as u64).saturating_mul(u64::from(len - 1)); + if least > (interp.limits.heap_bytes / 4) as u64 { + return Err(Abrupt::Limit(crate::LimitKind::Heap)); + } + interp.join_stack.push(o); + let r = join_elements(interp, o, len, sep, item); + interp.join_stack.pop(); + r + }) } fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn(&mut Interp, Value) -> JsResult>) -> JsResult { @@ -301,7 +305,10 @@ fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn( let Some(s) = item(interp, v)? else { continue }; out.push_repeated(interp, sep, k.saturating_sub(seps))?; seps = k; - out.push_units(interp, &s.flat())?; + interp.rooted(&[Value::String(s.clone())], |interp| { + let units = flat_charged(interp, &s)?; + out.push_units(interp, &units) + })?; } out.push_repeated(interp, sep, u64::from(len - 1).saturating_sub(seps))?; Ok(out.finish(interp)) @@ -472,7 +479,7 @@ fn unshift(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let count = args.len() as u64; - // With no arguments each element is still read and written back in place (steps 6 and 7). + // With no arguments each element is still read and written back in place (step 6). let maps = vec![Map::Shift(-1), Map::Shift(count as i64 - 1)]; let mut it = Indices::new(interp, o, 1, len + 1, false, maps)?; while let Some(k) = it.next(interp)? { diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 15ebbe734f..4ef9b82105 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -9,14 +9,18 @@ //! a script's own method: a getter, a function, a date, a regular expression, an error, a boxed //! primitive, an array with properties besides its elements, an object whose prototype is not //! `Object.prototype`, a property that is not enumerable or any other object that is not plain -//! data throws a `TypeError`, and so does an object that contains itself. A value nested deeper, with more entries or longer text than the +//! data throws a `TypeError`, and so does an object that contains itself. A literal makes an +//! extensible object whose properties are writable and configurable and an array whose `length` +//! is writable, so a property that is not writable or not configurable, an object or array that is +//! not extensible (after `Object.preventExtensions`, `Object.seal` or `Object.freeze`) and an +//! array with a read-only `length` throw a `TypeError` too. A value nested deeper, with more entries or longer text than the //! realm's [`crate::DataLimits`] allow throws a `RangeError`. Every value written takes fuel. use std::cell::{Cell, RefCell}; use std::rc::Rc; use super::{Builder, arg, method}; -use crate::heap::{Class, NativeFn, ObjId, Prop, key}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{ErrorType, Interp, JsResult}; use crate::value::{Value, array_index, index_key, number_to_str}; use crate::{ScriptItem, bytecode::Code}; @@ -289,10 +293,14 @@ impl Source { Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)), _ => None, }; + let fixed = shape.as_ref().and(fixed_state(o)); let Some(shape) = shape else { let what = format!("toSource: a {} cannot be written as source", interp.object(id)?.class.name()); return Err(interp.type_error(&what)); }; + if let Some(what) = fixed { + return Err(interp.type_error(what)); + } self.ancestors.push(id); let r = match shape { Err(length) => self.array(interp, id, length), @@ -347,6 +355,23 @@ const NOT_PLAIN_ARRAY: &str = "toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source"; const NOT_PLAIN_OBJECT: &str = "toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source"; +const NOT_EXTENSIBLE: &str = "toSource: a non-extensible object cannot be written as source"; +const READ_ONLY_LENGTH: &str = "toSource: an array with a read-only length cannot be written as source"; +const FIXED_PROPERTY: &str = "toSource: a property that is not writable or configurable cannot be written as source"; + +/// Why the literal for the array or plain object `o` would not make it again: `o` is not +/// extensible, its `length` is read-only, or one of its data properties is not writable or not +/// configurable. A literal makes each of these open. +fn fixed_state(o: &Object) -> Option<&'static str> { + if !o.extensible { + return Some(NOT_EXTENSIBLE); + } + if matches!(o.class, Class::Array { length_writable: false, .. }) { + return Some(READ_ONLY_LENGTH); + } + let open = WRITABLE | CONFIGURABLE; + o.props.iter().any(|(_, p)| matches!(p, Prop::Data { flags, .. } if flags & open != open)).then_some(FIXED_PROPERTY) +} /// The getter behind `item`; [`ScriptItem::Global`] is a value and has none. pub(crate) fn getter(item: ScriptItem) -> Option<(&'static str, NativeFn)> { diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 4375303fe0..364ec99696 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -13,6 +13,7 @@ use std::collections::HashSet; use super::{Builder, ELEMENT_BYTES, arg, data, key_of, length_of, method, new_array, new_string, to_integer}; use crate::heap::{Class, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key, string_bytes}; use crate::interp::{Desc, ErrorType, Hint, Interp, JsResult}; +use crate::string_builtins::flat_charged; use crate::value::{Str, Value, number_to_str}; pub(super) fn install(interp: &mut Interp) -> JsResult<()> { @@ -473,7 +474,7 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult s.gap = t.flat().iter().take(10).copied().collect(), + Value::String(t) => s.gap = flat_charged(interp, &t)?.iter().take(10).copied().collect(), _ => {} } Ok(s) @@ -632,7 +633,10 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul Value::Bool(b) => out.push_str(interp, if *b { "true" } else { "false" }), Value::Number(n) if n.is_finite() => out.push_units(interp, &number_to_str(*n).flat()), Value::Number(_) => out.push_str(interp, "null"), - Value::String(s) => write_quoted(interp, out, &s.flat()), + Value::String(s) => interp.rooted(std::slice::from_ref(v), |i| { + let units = flat_charged(i, s)?; + write_quoted(i, out, &units) + }), Value::Undefined | Value::Object(_) => Ok(()), } } diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index e0593d1dd7..0a70e80433 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -605,6 +605,21 @@ fn math_functions_follow_the_special_cases() { truth("var n = 0; Math.max({valueOf: function () { n++; return NaN; }}, {valueOf: function () { n++; return 1; }}); n === 2"); } +#[test] +fn math_random_is_seeded_from_the_os_random_source() { + // On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the + // same on every page load: the seed must come from the OS (the browser's crypto) instead. + let src = include_str!("interp.rs"); + let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") }; + let body = &src[start..]; + let body = &body[..body.find("\n}").unwrap_or(body.len())]; + assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source"); + // The OS value is the seed, made odd so it's never zero; a failed read still gives a seed. + assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41); + assert_eq!(crate::interp::random_seed_from(Ok(0)), 1); + assert_eq!(crate::interp::random_seed_from(Err(getrandom::Error::UNSUPPORTED)) & 1, 1); +} + // ---- JSON ---- #[test] diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 3092530d46..6992fd5606 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -160,8 +160,11 @@ pub(crate) enum Op { parts: u32, list: bool, }, - /// `name` → the value of the name on the nearest XML value in scope. + /// `name` → the value of the name on the nearest XML value in scope that holds it. XmlScopeGet, + /// `name` → `object name`: the nearest XML value in scope that holds the name, for an + /// assignment, update or `delete`. + XmlScopeRef, /// `object` → the filter's state. XmlFilterStart, /// `state` → `state item`, or jumps with `state` when the items are used up. @@ -170,8 +173,9 @@ pub(crate) enum Op { XmlFilterTest, /// `state` → the XMLList of the items kept. XmlFilterEnd, - /// `iterator name` → `iterator value`: the value under the name a `for each` got. - ForEachValue, + /// `iterator name x₁…xₙ` → `iterator name x₁…xₙ value`: the value under the name a `for each` + /// got, read after the `n` values its target pushed. + ForEachValue(u32), /// `value` → nothing: sets the default XML namespace of the running code. SetDefaultNamespace, } @@ -308,7 +312,8 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::XmlDescendants | Op::XmlFilterTest => e(2, 1), Op::XmlEscape(_) | Op::XmlScopeGet | Op::XmlFilterStart | Op::XmlFilterEnd => e(1, 1), Op::XmlLiteral { parts, .. } => e(parts, 1), - Op::ForEachValue => e(2, 2), + Op::XmlScopeRef => e(1, 2), + Op::ForEachValue(n) => e(n + 2, n + 3), Op::SetDefaultNamespace => e(1, 0), }) } diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index a7b2c1374c..61b9a7f318 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -4,7 +4,7 @@ use std::cmp::Ordering; -use unicode_general_category::{GeneralCategory as G, get_general_category}; +use unicode_properties::{GeneralCategory as G, UnicodeGeneralCategory}; /// A line terminator: LF, CR, U+2028 or U+2029 (section 7.3). pub fn is_line_terminator(c: u32) -> bool { @@ -20,7 +20,7 @@ pub fn is_whitespace(c: u32) -> bool { /// A character an identifier may start with: a Unicode `ID_Start` character, `$` or `_` /// (the Names and Keywords clause of current ECMA-262 editions). `ID_Start` is the letters (categories Lu, Ll, Lt, Lm, Lo and Nl) /// and `Other_ID_Start`, less `Pattern_Syntax` and `Pattern_White_Space` (Unicode Standard Annex -/// #31). The categories come from Unicode 16.0. `\u` escapes are decoded before this check. +/// #31). The categories come from Unicode 17.0. `\u` escapes are decoded before this check. pub fn is_id_start(c: u32) -> bool { match c { 0x24 | 0x5F => true, @@ -58,7 +58,7 @@ fn is_other_id_start(c: u32) -> bool { matches!(c, 0x1885 | 0x1886 | 0x2118 | 0x212E | 0x309B | 0x309C) } -/// `Other_ID_Continue` (Unicode PropList 16.0): characters kept in `ID_Continue` though their +/// `Other_ID_Continue` (Unicode PropList 17.0): characters kept in `ID_Continue` though their /// category is not a letter, mark, digit or connector. fn is_other_id_continue(c: u32) -> bool { matches!(c, 0xB7 | 0x387 | 0x1369..=0x1371 | 0x19DA | 0x200C | 0x200D | 0x30FB | 0xFF65) @@ -110,7 +110,7 @@ fn is_pattern_syntax(c: u32) -> bool { /// The Unicode general category of a code point; `None` for a lone surrogate. fn category(c: u32) -> Option { - char::from_u32(c).map(get_general_category) + char::from_u32(c).map(char::general_category) } /// The value of a hexadecimal digit. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 071e99a60e..3023e3b127 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -497,16 +497,21 @@ impl<'a> FnCompiler<'a> { let brk = self.new_label(); self.bind(head); self.jump(Op::ForInNext, brk); - if each { - self.emit(Op::ForEachValue); - } match target { ForInTarget::Var(d) => { let n = self.var_name(&d.name.name); + if each { + self.emit(Op::ForEachValue(0)); + } self.emit(Op::SetVar(n)); } + ForInTarget::Expr(e) if each => self.store_value_to(*e)?, ForInTarget::Expr(e) => self.store_key_to(*e)?, } + if each { + // The value; the name under it goes next. + self.emit(Op::Pop); + } self.emit(Op::Pop); self.loop_body(body, labels, brk, head)?; self.jump(Op::Jump, head); @@ -538,6 +543,11 @@ impl<'a> FnCompiler<'a> { self.emit(Op::Rot3); self.emit(Op::SetIndex); } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + self.emit(Op::Rot3); + self.emit(Op::SetIndex); + } _ => { self.expr(target)?; self.emit(Op::Pop); @@ -547,6 +557,46 @@ impl<'a> FnCompiler<'a> { Ok(()) } + /// Assigns the value under the name on top of the stack to a `for each` target expression, + /// leaving the name and then the value on top. The target is evaluated before the value is + /// read (ECMA-357 section 12.3). + fn store_value_to(&mut self, target: ExprId) -> CResult<()> { + let target = self.ast.unparenthesized(target); + self.at(self.ast.expr_span(target).start); + match self.ast.expr(target) { + Some(Expr::Ident(name)) => { + let n = self.var_name(name); + self.emit(Op::ForEachValue(0)); + self.emit(Op::SetVar(n)); + } + Some(Expr::Member { object, property }) => { + self.expr(*object)?; + self.emit(Op::ForEachValue(1)); + let n = self.name_key(key_of(&property.name)); + self.emit(Op::SetMember(n)); + } + Some(Expr::Index { object, index }) => { + self.expr(*object)?; + self.expr(*index)?; + self.emit(Op::ToKey); + self.emit(Op::ForEachValue(2)); + self.emit(Op::SetIndex); + } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + self.emit(Op::ForEachValue(2)); + self.emit(Op::SetIndex); + } + _ => { + self.expr(target)?; + self.emit(Op::Pop); + self.emit(Op::ForEachValue(0)); + self.throw_invalid_target(); + } + } + Ok(()) + } + fn throw_invalid_target(&mut self) { let s = self.string(&"invalid assignment target".encode_utf16().collect::>()); let depth = self.depth; @@ -854,6 +904,15 @@ impl<'a> FnCompiler<'a> { Ok(()) } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression + /// `id`, then the name, as an assignment, update or `delete` uses them. + fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { + self.expr(name)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::XmlScopeRef); + Ok(()) + } + fn xml_literal(&mut self, parts: &[XmlPart], list: bool) -> CResult<()> { for part in parts { match part { @@ -1096,6 +1155,10 @@ impl<'a> FnCompiler<'a> { self.expr(*index)?; self.emit(Op::DeleteIndex); } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(arg, *name)?; + self.emit(Op::DeleteIndex); + } _ => { self.expr(arg)?; self.emit(Op::Pop); @@ -1202,6 +1265,13 @@ impl<'a> FnCompiler<'a> { self.emit(Op::GetIndex); } } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + if op.is_some() { + self.emit(Op::Dup2); + self.emit(Op::GetIndex); + } + } _ => { self.expr(target)?; if op.is_none() { @@ -1222,7 +1292,7 @@ impl<'a> FnCompiler<'a> { let n = self.name_key(key_of(&property.name)); self.emit(Op::SetMember(n)); } - Some(Expr::Index { .. }) => self.emit(Op::SetIndex), + Some(Expr::Index { .. } | Expr::XmlScopeName(_)) => self.emit(Op::SetIndex), _ => self.throw_invalid_target(), } Ok(()) @@ -1246,6 +1316,10 @@ impl<'a> FnCompiler<'a> { self.expr(*index)?; self.emit(Op::IncIndex { prefix, dec }); } + Some(Expr::XmlScopeName(name)) => { + self.xml_scope_ref(target, *name)?; + self.emit(Op::IncIndex { prefix, dec }); + } _ => { self.expr(target)?; self.emit(Op::ToNumber); diff --git a/crates/js/src/extension_tests.rs b/crates/js/src/extension_tests.rs index 19a20ab5b8..8336643e4d 100644 --- a/crates/js/src/extension_tests.rs +++ b/crates/js/src/extension_tests.rs @@ -126,6 +126,45 @@ fn to_source_refuses_what_is_not_plain_data() { assert!(thrown(&mut r, "toSource({get g() { throw 'ran'; }})").starts_with("TypeError"), "the getter does not run"); } +#[test] +fn to_source_refuses_flags_and_extensibility_a_literal_does_not_make() { + let mut r = realm(); + let property = "TypeError: toSource: a property that is not writable or configurable cannot be written as source"; + let extensible = "TypeError: toSource: a non-extensible object cannot be written as source"; + let length = "TypeError: toSource: an array with a read-only length cannot be written as source"; + for (source, want) in [ + ("var o = {}; Object.defineProperty(o, 'a', {value: 1, enumerable: true, configurable: true}); toSource(o)", property), + ("var o = {}; Object.defineProperty(o, 'a', {value: 1, enumerable: true, writable: true}); toSource(o)", property), + ("var a = [1, 2]; Object.defineProperty(a, '1', {writable: false}); toSource(a)", property), + ("var a = [1, 2]; Object.defineProperty(a, '0', {configurable: false}); a.toSource()", property), + ("var o = {}; Object.defineProperty(o, 'a', {value: 1, enumerable: true}); toSource({x: [{b: o}]})", property), + ("toSource(Object.preventExtensions({}))", extensible), + ("toSource(Object.preventExtensions([]))", extensible), + ("toSource(Object.seal({a: 1}))", extensible), + ("toSource(Object.freeze({a: 1}))", extensible), + ("toSource(Object.seal([1]))", extensible), + ("toSource(Object.freeze([1]))", extensible), + ("toSource([1, {b: Object.freeze({})}])", extensible), + ("var a = []; Object.defineProperty(a, 'length', {writable: false}); toSource(a)", length), + ("var a = [1, , 3]; Object.defineProperty(a, 'length', {writable: false}); toSource({a: a})", length), + ] { + assert_eq!(thrown(&mut r, source), want, "{source}"); + } + // The refused states are ones the literal would lose: evaluated, it is open again. + let lost = "var o = Object.freeze({a: 1}); var w = eval('({\"a\":1})'); + [Object.isExtensible(o), Object.isExtensible(w), Object.getOwnPropertyDescriptor(w, 'a').writable].join()"; + assert_eq!(text(&mut r, lost), "false,true,true"); +} + +#[test] +fn to_source_writes_properties_defined_with_every_flag_on() { + let mut r = realm(); + let source = "var o = {}; Object.defineProperty(o, 'a', {value: 1, writable: true, enumerable: true, configurable: true}); + var a = [0]; Object.defineProperty(a, '0', {value: 2, writable: true, enumerable: true, configurable: true}); + toSource({o: o, a: a, e: {}, f: [], s: [1, , 3]})"; + assert_eq!(text(&mut r, source), r#"({"o":({"a":1}), "a":[2], "e":({}), "f":[], "s":[1, , 3]})"#); +} + #[test] fn to_source_of_a_string_with_many_escapes_throws_a_range_error_before_the_heap_limit() { let mut r = realm(); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs new file mode 100644 index 0000000000..cabf7c84aa --- /dev/null +++ b/crates/js/src/file_classes.rs @@ -0,0 +1,899 @@ +//! `File` and `Folder`, the classes the help pages +//! and +//! describe, as built-ins +//! whose file system work a host does ([`crate::Realm::define_file_classes`]). +//! +//! The constructors build their objects with and without `new`: `new File(path)` is always a +//! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the +//! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two +//! objects for one path are different objects. An object keeps its path in the host's platform +//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open` +//! and its line feed, in properties that are not enumerable; every name the getters give comes from +//! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's +//! `current`. +//! +//! A method whose host call fails sets `error` and returns `false`, `null` or an empty string. A +//! count or position that is not a finite number, a negative count and a seek mode other than 0, 1 +//! or 2 throw a `RangeError`; a method called on an object that is not a `File` or `Folder` throws +//! a `TypeError`. `getFiles` with a function calls it with each entry and keeps those it returns a +//! true value for; every entry takes fuel. + +use crate::HostItem; +use crate::builtins::{arg, constructor, data, method, native, put_at}; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; + +/// The objects of `File` and `Folder`, kept by the realm, and `Folder.current`. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + file_proto: ObjId, + folder_proto: ObjId, + host: ObjId, + current: Value, + /// The count of [`reset_current`] calls: a file is open only in the run that opened it. + run: f64, +} + +impl Classes { + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> [ObjId; 3] { + [self.file_proto, self.folder_proto, self.host] + } +} + +const PATH: &str = "__vcPath"; +const ERROR: &str = "__vcError"; +const HANDLE: &str = "__vcHandle"; +const RUN: &str = "__vcRun"; +const ENCODING: &str = "__vcEncoding"; +const LINE_FEED: &str = "__vcLineFeed"; + +/// The locations `Folder` has as properties, each read from the host's `locations` when it is read. +const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; + +fn classes(i: &Interp) -> JsResult { + i.files.clone().ok_or_else(|| Abrupt::Internal("File and Folder are not installed".into())) +} + +/// Calls the host function `name` with `args`. +fn host(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { + let c = classes(i)?; + let f = i.get_value(&Value::Object(c.host), &key(name))?; + i.call(&f, &Value::Undefined, args) +} + +/// The host's message `name`. +fn message(i: &mut Interp, name: &str) -> JsResult { + let c = classes(i)?; + let text = i.get_value(&Value::Object(c.host), &key("text"))?; + i.get_value(&text, &key(name)) +} + +/// The field `name` of a record the host gave: its own data property, `undefined` when it has none, +/// so that a property a script put on `Object.prototype` is not read as part of it. +fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult { + match v.as_object() { + Some(o) => slot(i, o, name), + None => Ok(Value::Undefined), + } +} + +/// The value of the own data property `name` of `o`, `undefined` when it has none. +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + if let Value::String(s) = &value { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; + } + i.define(o, key(name), Prop::Data { value, flags: HIDDEN }) +} + +/// The object `this` and its path, or a `TypeError` naming `what` when it is not a `File` or +/// `Folder`. +fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value)> { + if let Some(o) = this.as_object() + && let path @ Value::String(_) = slot(i, o, PATH)? + { + return Ok((o, path)); + } + Err(i.type_error(&format!("{what}: the object is not a File or a Folder"))) +} + +/// The path `x` names, and whether it is already in the platform's form: the path of a `File` or +/// `Folder`, or `String(x)`, which may hold URI escapes. +fn path_text(i: &mut Interp, x: &Value) -> JsResult<(Value, bool)> { + if let Some(o) = x.as_object() + && let path @ Value::String(_) = slot(i, o, PATH)? + { + return Ok((path, true)); + } + let s = i.to_str(x)?; + Ok((Value::String(s), false)) +} + +/// The host's `parse` of the path `x` names, from `Folder.current`. +fn parse(i: &mut Interp, x: &Value) -> JsResult { + let (text, platform) = path_text(i, x)?; + parse_text(i, text, platform) +} + +/// The host's `parse` of `text`, from `Folder.current`; its URI escapes are decoded unless it is +/// already a `platform` path. +fn parse_text(i: &mut Interp, text: Value, platform: bool) -> JsResult { + let current = classes(i)?.current; + host(i, "parse", &[text, current, Value::Bool(platform)]) +} + +fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult { + let (_, path) = this_path(i, this, what)?; + let p = parse_text(i, path, true)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, name)) +} + +/// A new object with prototype `proto` for the path `fs`, already in the platform's form. +fn instance(i: &mut Interp, proto: ObjId, fs: Value) -> JsResult { + let line_feed = host_value(i, "lineFeed")?; + i.rooted(&[fs.clone(), line_feed.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[Value::Object(o)], |i| { + set_slot(i, o, PATH, fs.clone())?; + set_slot(i, o, ERROR, Value::str(""))?; + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + set_slot(i, o, RUN, Value::Number(-1.0))?; + set_slot(i, o, ENCODING, Value::str(""))?; + set_slot(i, o, LINE_FEED, line_feed.clone())?; + Ok(Value::Object(o)) + }) + }) +} + +fn host_value(i: &mut Interp, name: &str) -> JsResult { + let c = classes(i)?; + i.get_value(&Value::Object(c.host), &key(name)) +} + +/// The host's `stat` of the object's path, or `None` after setting `error` when it failed. +fn stat(i: &mut Interp, this: &Value, what: &str) -> JsResult> { + let (o, path) = this_path(i, this, what)?; + let r = host(i, "stat", &[path])?; + i.rooted(std::slice::from_ref(&r), |i| { + let error = field(i, &r, "error")?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(None); + } + Ok(Some(r.clone())) + }) +} + +/// The field `name` of the object's `stat`, when it exists, or `missing`. +fn stat_field(i: &mut Interp, this: &Value, what: &str, name: &str, missing: Value) -> JsResult { + let Some(r) = stat(i, this, what)? else { return Ok(missing) }; + i.rooted(std::slice::from_ref(&r), |i| { + if !field(i, &r, "exists")?.truthy() && name != "exists" { + return Ok(missing); + } + field(i, &r, name) + }) +} + +/// The result of a host read: its `text`, or `failed` after setting `error`. +fn text_result(i: &mut Interp, o: ObjId, r: Value, failed: Value) -> JsResult { + i.rooted(std::slice::from_ref(&r), |i| { + let error = field(i, &r, "error")?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(failed); + } + field(i, &r, "text") + }) +} + +/// The id of the object's open file, or `None` after setting `error` when it has none. +fn opened(i: &mut Interp, o: ObjId) -> JsResult> { + if let Some(h) = is_open(i, o)? { + return Ok(Some(h)); + } + let m = message(i, "notOpen")?; + set_slot(i, o, ERROR, m)?; + Ok(None) +} + +/// The id of the object's open file, when this run opened it. +fn is_open(i: &Interp, o: ObjId) -> JsResult> { + let h = slot(i, o, HANDLE)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if n == classes(i)?.run); + Ok((this_run && matches!(h, Value::Number(n) if n >= 0.0)).then_some(h)) +} + +/// Closes the object's open file, if it has one. +fn close_open(i: &mut Interp, o: ObjId) -> JsResult<()> { + if let Some(h) = is_open(i, o)? { + host(i, "close", &[h])?; + } + set_slot(i, o, HANDLE, Value::Number(-1.0)) +} + +fn date(i: &mut Interp, ms: Value) -> JsResult { + let Value::Number(t) = ms else { return Ok(Value::Null) }; + i.reserve_heap(OBJECT_BYTES)?; + let proto = i.intrinsics.date_proto; + Ok(Value::Object(i.heap.alloc_object(Object::new(Class::Date(t), Some(proto))))) +} + +/// A count of characters: `None` for `undefined`, else a whole number 0 or more. +fn count(i: &mut Interp, v: &Value, what: &str) -> JsResult> { + if matches!(v, Value::Undefined) { + return Ok(None); + } + let n = i.to_number(v)?; + if !n.is_finite() || n < 0.0 { + return Err(i.throw(ErrorType::Range, &format!("{what}: the count must be a finite number, 0 or more"))); + } + Ok(Some(n.floor())) +} + +// ---- constructors ---- + +fn file_ctor(i: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + make(i, args, construct, true) +} + +fn folder_ctor(i: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + make(i, args, construct, false) +} + +/// `new File(path)`, `File(path)`, `new Folder(path)` or `Folder(path)`. +fn make(i: &mut Interp, args: &[Value], construct: bool, file: bool) -> JsResult { + let c = classes(i)?; + let (own, other) = if file { (c.file_proto, c.folder_proto) } else { (c.folder_proto, c.file_proto) }; + let (path, platform) = match arg(args, 0) { + Value::Undefined if file => (host(i, "tempName", &[])?, true), + Value::Undefined => (c.current.clone(), true), + v => (v, false), + }; + let fs = i.rooted(std::slice::from_ref(&path), |i| { + let p = if platform { parse_text(i, path.clone(), true)? } else { parse(i, &path)? }; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) + })?; + let proto = if construct { + own + } else { + let st = i.rooted(std::slice::from_ref(&fs), |i| host(i, "stat", std::slice::from_ref(&fs)))?; + let flip = i.rooted(&[fs.clone(), st.clone()], |i| { + let error = field(i, &st, "error")?; + let exists = field(i, &st, "exists")?.truthy(); + let dir = field(i, &st, "dir")?.truthy(); + Ok(matches!(error, Value::Undefined) && exists && dir == file) + })?; + if flip { other } else { own } + }; + instance(i, proto, fs) +} + +// ---- both classes ---- + +fn absolute_uri(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + parsed(i, &this, "absoluteURI", "uri") +} + +fn fs_name(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(this_path(i, &this, "fsName")?.1) +} + +fn relative_uri(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, path) = this_path(i, &this, "relativeURI")?; + let current = classes(i)?.current; + host(i, "relative", &[path, current]) +} + +fn name(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + parsed(i, &this, "name", "name") +} + +fn display_name(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + parsed(i, &this, "displayName", "display") +} + +fn path(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + parsed(i, &this, "path", "path") +} + +fn parent(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let up = parsed(i, &this, "parent", "parent")?; + if matches!(up, Value::Null | Value::Undefined) { + return Ok(Value::Null); + } + let proto = classes(i)?.folder_proto; + instance(i, proto, up) +} + +/// `exists`: whether the path names something of the object's own kind, a folder for a `Folder` +/// and anything else for a `File`. +fn exists(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let folder = classes(i)?.folder_proto; + let want_dir = match this.as_object() { + Some(o) => i.object(o)?.proto == Some(folder), + None => false, + }; + let Some(r) = stat(i, &this, "exists")? else { return Ok(Value::Bool(false)) }; + i.rooted(std::slice::from_ref(&r), |i| { + let dir = field(i, &r, "dir")?.truthy(); + Ok(Value::Bool(field(i, &r, "exists")?.truthy() && dir == want_dir)) + }) +} + +fn created(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let ms = stat_field(i, &this, "created", "created", Value::Null)?; + date(i, ms) +} + +fn modified(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let ms = stat_field(i, &this, "modified", "modified", Value::Null)?; + date(i, ms) +} + +fn alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let Some(r) = stat(i, &this, "alias")? else { return Ok(Value::Bool(false)) }; + let v = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "alias"))?; + Ok(Value::Bool(v.truthy())) +} + +fn get_error(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "error")?; + slot(i, o, ERROR) +} + +fn set_error(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "error")?; + let v = match arg(args, 0) { + Value::Undefined | Value::Null => Value::str(""), + v => Value::String(i.to_str(&v)?), + }; + set_slot(i, o, ERROR, v)?; + Ok(Value::Undefined) +} + +fn get_relative_uri(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, path) = this_path(i, &this, "getRelativeURI")?; + let base = match arg(args, 0) { + Value::Undefined => classes(i)?.current, + b => { + let p = i.rooted(std::slice::from_ref(&path), |i| parse(i, &b))?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))? + } + }; + host(i, "relative", &[path, base]) +} + +fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "changePath")?; + close_open(i, o)?; + let p = parse(i, &arg(args, 0))?; + let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; + set_slot(i, o, PATH, fs)?; + Ok(Value::Bool(true)) +} + +fn resolve(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "resolve")?; + let r = host(i, "resolve", &[path])?; + let (error, fs, dir) = i.rooted(std::slice::from_ref(&r), |i| Ok((field(i, &r, "error")?, field(i, &r, "fs")?, field(i, &r, "dir")?)))?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(Value::Null); + } + if !matches!(fs, Value::String(_)) { + return Ok(Value::Null); + } + let c = classes(i)?; + instance(i, if dir.truthy() { c.folder_proto } else { c.file_proto }, fs) +} + +fn execute(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "execute")?; + let r = host(i, "execute", &[path])?; + let error = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "error"))?; + set_slot(i, o, ERROR, error)?; + Ok(Value::Bool(false)) +} + +fn to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + parsed(i, &this, "toString", "uri") +} + +/// A method that writes: it sets `error` and returns `false`. +fn no_writes(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "write")?; + let m = message(i, "noWrites")?; + set_slot(i, o, ERROR, m)?; + Ok(Value::Bool(false)) +} + +/// A setter that writes: it sets `error` and changes nothing. +fn no_writes_setter(i: &mut Interp, this: Value, args: &[Value], construct: bool) -> JsResult { + no_writes(i, this, args, construct)?; + Ok(Value::Undefined) +} + +/// A dialog method: it sets `error` and returns `null`. +fn no_picker(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "dialog")?; + let m = message(i, "noPicker")?; + set_slot(i, o, ERROR, m)?; + Ok(Value::Null) +} + +fn null_static(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Null) +} + +fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { + let s = i.to_str(&arg(args, 0))?; + host(i, name, &[Value::String(s)]) +} + +fn encode(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + text_static(i, "encode", args) +} + +fn decode(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + text_static(i, "decode", args) +} + +fn encoding_available(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + text_static(i, "encodingAvailable", args) +} + +// ---- File ---- + +fn length(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let Some(r) = stat(i, &this, "length")? else { return Ok(Value::Number(0.0)) }; + i.rooted(std::slice::from_ref(&r), |i| { + let regular = field(i, &r, "exists")?.truthy() && field(i, &r, "file")?.truthy(); + if regular { field(i, &r, "length") } else { Ok(Value::Number(0.0)) } + }) +} + +fn hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Bool(stat_field(i, &this, "hidden", "hidden", Value::Bool(false))?.truthy())) +} + +fn readonly(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Bool(stat_field(i, &this, "readonly", "readonly", Value::Bool(false))?.truthy())) +} + +fn four_question_marks(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_path(i, &this, "creator")?; + Ok(Value::str("????")) +} + +fn eof(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "eof")?; + match is_open(i, o)? { + Some(h) => host(i, "eof", &[h]), + None => Ok(Value::Bool(true)), + } +} + +fn get_line_feed(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "lineFeed")?; + slot(i, o, LINE_FEED) +} + +fn set_line_feed(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "lineFeed")?; + let v = i.to_str(&arg(args, 0))?; + set_slot(i, o, LINE_FEED, Value::String(v))?; + Ok(Value::Undefined) +} + +fn get_encoding(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "encoding")?; + if let Some(h) = is_open(i, o)? { + return host(i, "encoding", &[h]); + } + Ok(match slot(i, o, ENCODING)? { + Value::String(s) if s.len() != 0 => Value::String(s), + _ => Value::str("UTF-8"), + }) +} + +fn set_encoding(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "encoding")?; + let v = Value::String(i.to_str(&arg(args, 0))?); + match is_open(i, o)? { + Some(h) => { + let r = i.rooted(std::slice::from_ref(&v), |i| host(i, "setEncoding", &[h, v.clone()]))?; + let error = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "error"))?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + } else { + set_slot(i, o, ENCODING, v)?; + } + } + None => set_slot(i, o, ENCODING, v)?, + } + Ok(Value::Undefined) +} + +fn open(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "open")?; + let mode = match arg(args, 0) { + Value::Undefined => "r".to_string(), + m => i.to_str(&m)?.to_rust_string().to_lowercase(), + }; + let refusal = match mode.as_str() { + "r" => None, + "w" | "e" | "a" => Some("noWrites"), + _ => Some("badMode"), + }; + if let Some(name) = refusal { + let m = message(i, name)?; + set_slot(i, o, ERROR, m)?; + return Ok(Value::Bool(false)); + } + close_open(i, o)?; + let encoding = slot(i, o, ENCODING)?; + let r = host(i, "open", &[path, encoding])?; + let (error, id) = i.rooted(std::slice::from_ref(&r), |i| Ok((field(i, &r, "error")?, field(i, &r, "id")?)))?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(Value::Bool(false)); + } + set_slot(i, o, HANDLE, id)?; + let run = classes(i)?.run; + set_slot(i, o, RUN, Value::Number(run))?; + Ok(Value::Bool(true)) +} + +fn close(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "close")?; + if opened(i, o)?.is_none() { + return Ok(Value::Bool(false)); + } + close_open(i, o)?; + Ok(Value::Bool(true)) +} + +fn read(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "read")?; + let n = count(i, &arg(args, 0), "File.read")?; + let Some(h) = opened(i, o)? else { return Ok(Value::str("")) }; + let r = host(i, "read", &[h, n.map_or(Value::Number(-1.0), Value::Number)])?; + text_result(i, o, r, Value::str("")) +} + +fn read_line(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "readln")?; + let Some(h) = opened(i, o)? else { return Ok(Value::str("")) }; + let r = host(i, "readln", &[h])?; + text_result(i, o, r, Value::str("")) +} + +fn read_char(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "readch")?; + let Some(h) = opened(i, o)? else { return Ok(Value::str("")) }; + let r = host(i, "readch", &[h])?; + text_result(i, o, r, Value::str("")) +} + +fn seek(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "seek")?; + let pos = i.to_number(&arg(args, 0))?; + if !pos.is_finite() { + return Err(i.throw(ErrorType::Range, "File.seek: the position must be a finite number")); + } + let mode = match arg(args, 1) { + Value::Undefined => 0.0, + m => i.to_number(&m)?, + }; + if mode != 0.0 && mode != 1.0 && mode != 2.0 { + return Err(i.throw(ErrorType::Range, "File.seek: the mode must be 0, 1 or 2")); + } + let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; + host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)]) +} + +fn tell(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "tell")?; + let Some(h) = opened(i, o)? else { return Ok(Value::Number(-1.0)) }; + host(i, "tell", &[h]) +} + +// ---- Folder ---- + +fn get_files(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "getFiles")?; + let mask = arg(args, 0); + let call = i.is_callable(&mask); + let pattern = if call || matches!(mask, Value::Undefined) { Value::str("*") } else { Value::String(i.to_str(&mask)?) }; + let r = host(i, "list", &[path, pattern])?; + i.rooted(&[r.clone(), mask.clone()], |i| { + let error = field(i, &r, "error")?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(Value::Null); + } + let entries = field(i, &r, "entries")?; + let length = i.get_value(&entries, &key("length"))?; + let n = i.to_number(&length)?; + i.reserve_heap(OBJECT_BYTES)?; + let proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto))); + i.rooted(&[Value::Object(out)], |i| { + let c = classes(i)?; + let mut kept = 0.0; + let mut at = 0.0; + while at < n { + i.use_fuel()?; + let e = i.get_value(&entries, &crate::value::number_to_str(at).flat())?; + let (fs, dir) = i.rooted(std::slice::from_ref(&e), |i| Ok((field(i, &e, "fs")?, field(i, &e, "dir")?.truthy())))?; + let item = instance(i, if dir { c.folder_proto } else { c.file_proto }, fs)?; + let keep = if call { + i.rooted(std::slice::from_ref(&item), |i| i.call(&mask, &Value::Undefined, std::slice::from_ref(&item)))?.truthy() + } else { + true + }; + if keep { + put_at(i, out, kept, item)?; + kept += 1.0; + } + at += 1.0; + } + Ok(Value::Object(out)) + }) + }) +} + +fn get_current(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let c = classes(i)?; + instance(i, c.folder_proto, c.current) +} + +fn set_current(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let p = parse(i, &arg(args, 0))?; + let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; + if let Some(c) = i.files.as_mut() { + c.current = fs; + } + Ok(Value::Undefined) +} + +/// `Folder.`: a new `Folder` for the host's location `place`, or `null`. +fn place(i: &mut Interp, place: &str) -> JsResult { + let all = host(i, "locations", &[])?; + let fs = i.rooted(std::slice::from_ref(&all), |i| field(i, &all, place))?; + if !matches!(fs, Value::String(_)) { + return Ok(Value::Null); + } + let proto = classes(i)?.folder_proto; + instance(i, proto, fs) +} + +macro_rules! places { + ($($f:ident => $name:literal),* $(,)?) => { + $(fn $f(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + place(i, $name) + })* + /// The getter of each of [`PLACES`], in its order. + const PLACE_GETTERS: [NativeFn; 10] = [$($f),*]; + }; +} + +places!( + app_data => "appData", + app_package => "appPackage", + common_files => "commonFiles", + desktop => "desktop", + my_documents => "myDocuments", + startup => "startup", + system => "system", + temp => "temp", + trash => "trash", + user_data => "userData", +); + +// ---- install ---- + +/// Defines the accessor `name` on `on`, not enumerable, as the help pages' objects have them. +fn accessor(i: &mut Interp, on: ObjId, name: &'static str, get: NativeFn, set: Option) -> JsResult<()> { + let g = native(i, name, get, 0, NativeKind::Plain, false)?; + i.rooted(&[Value::Object(g)], |i| { + let s = match set { + Some(f) => Some(native(i, name, f, 1, NativeKind::Plain, false)?), + None => None, + }; + i.define(on, key(name), Prop::Accessor { get: Some(g), set: s, flags: CONFIGURABLE }) + }) +} + +/// What `File` and `Folder` both have. +fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + accessor(i, proto, "absoluteURI", absolute_uri, None)?; + accessor(i, proto, "fullName", absolute_uri, None)?; + accessor(i, proto, "fsName", fs_name, None)?; + accessor(i, proto, "relativeURI", relative_uri, None)?; + accessor(i, proto, "name", name, None)?; + accessor(i, proto, "displayName", display_name, None)?; + accessor(i, proto, "path", path, None)?; + accessor(i, proto, "parent", parent, None)?; + accessor(i, proto, "exists", exists, None)?; + accessor(i, proto, "created", created, None)?; + accessor(i, proto, "modified", modified, None)?; + accessor(i, proto, "alias", alias, None)?; + accessor(i, proto, "error", get_error, Some(set_error))?; + method(i, proto, "toString", to_string, 0)?; + method(i, proto, "getRelativeURI", get_relative_uri, 1)?; + method(i, proto, "changePath", change_path, 1)?; + method(i, proto, "resolve", resolve, 0)?; + method(i, proto, "execute", execute, 0)?; + method(i, proto, "remove", no_writes, 0)?; + method(i, proto, "rename", no_writes, 1)?; + method(i, ctor, "encode", encode, 1)?; + method(i, ctor, "decode", decode, 1)?; + method(i, ctor, "isEncodingAvailable", encoding_available, 1)?; + let system = host_value(i, "system")?; + data(i, ctor, "fs", system, HIDDEN) +} + +fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + accessor(i, proto, "length", length, Some(no_writes_setter))?; + accessor(i, proto, "hidden", hidden, Some(no_writes_setter))?; + accessor(i, proto, "readonly", readonly, Some(no_writes_setter))?; + accessor(i, proto, "creator", four_question_marks, None)?; + accessor(i, proto, "type", four_question_marks, None)?; + accessor(i, proto, "eof", eof, None)?; + accessor(i, proto, "lineFeed", get_line_feed, Some(set_line_feed))?; + accessor(i, proto, "encoding", get_encoding, Some(set_encoding))?; + method(i, proto, "open", open, 1)?; + method(i, proto, "close", close, 0)?; + method(i, proto, "read", read, 1)?; + method(i, proto, "readln", read_line, 0)?; + method(i, proto, "readch", read_char, 0)?; + method(i, proto, "seek", seek, 2)?; + method(i, proto, "tell", tell, 0)?; + method(i, proto, "write", no_writes, 1)?; + method(i, proto, "writeln", no_writes, 1)?; + method(i, proto, "copy", no_writes, 1)?; + method(i, proto, "createAlias", no_writes, 1)?; + method(i, proto, "openDlg", no_picker, 0)?; + method(i, proto, "saveDlg", no_picker, 0)?; + method(i, ctor, "openDialog", null_static, 0)?; + method(i, ctor, "saveDialog", null_static, 0) +} + +fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getFiles", get_files, 1)?; + method(i, proto, "create", no_writes, 0)?; + method(i, proto, "selectDlg", no_picker, 0)?; + method(i, ctor, "selectDialog", null_static, 0)?; + accessor(i, ctor, "current", get_current, Some(set_current))?; + for (place, get) in PLACES.into_iter().zip(PLACE_GETTERS) { + accessor(i, ctor, place, get, None)?; + } + Ok(()) +} + +/// Sets `Folder.current` back to the host's `current`, when the realm has `File` and `Folder`, and +/// begins a new run, in which the files earlier runs opened are not open. +pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { + let Some(c) = i.files.as_mut() else { return Ok(()) }; + c.run += 1.0; + let start = host(i, "current", &[])?; + if let Some(c) = i.files.as_mut() { + c.current = start; + } + Ok(()) +} + +/// Adds `File` and `Folder` to the global object, their work done by the host functions in +/// `items` ([`crate::Realm::define_file_classes`]). +pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { + let host_obj = i.host_object("File", items)?; + let object_proto = i.intrinsics.object_proto; + i.rooted(&[Value::Object(host_obj)], |i| { + i.reserve_heap(2 * OBJECT_BYTES)?; + let file_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let folder_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.files = Some(Classes { file_proto, folder_proto, host: host_obj, current: Value::str(""), run: 0.0 }); + let start = host(i, "current", &[])?; + if let Some(c) = i.files.as_mut() { + c.current = start; + } + let file = native(i, "File", file_ctor, 1, NativeKind::Plain, true)?; + constructor(i, "File", file, file_proto)?; + let folder = native(i, "Folder", folder_ctor, 1, NativeKind::Plain, true)?; + constructor(i, "Folder", folder, folder_proto)?; + common(i, file, file_proto)?; + common(i, folder, folder_proto)?; + file_members(i, file, file_proto)?; + folder_members(i, folder, folder_proto) + }) +} + +#[cfg(test)] +mod tests { + use std::rc::Rc; + + use crate::{Data, HostItem, JsValue, Realm}; + + /// A host whose paths are `/` and a name, where `/d` is a folder holding `a` and `b` and every + /// other path is missing. + fn realm() -> Realm { + let f = |g: fn(&[Data]) -> Data| HostItem::Function(Rc::new(move |a: Vec| Ok(g(&a)))); + let text = |a: &[Data], i: usize| match a.get(i) { + Some(Data::String(s)) => s.clone(), + _ => String::new(), + }; + let obj = |fields: Vec<(&str, Data)>| Data::Object(fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect()); + let parse = move |a: &[Data]| { + let t = text(a, 0); + let fs = if t.starts_with('/') { t } else { format!("/{t}") }; + let name = fs.trim_start_matches('/').to_string(); + obj(vec![ + ("fs", Data::String(fs.clone())), + ("uri", Data::String(fs)), + ("name", Data::String(name.clone())), + ("display", Data::String(name)), + ("path", Data::String("/".into())), + ("parent", Data::String("/".into())), + ]) + }; + let messages = ["notOpen", "noWrites", "noPicker", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + let stat = move |a: Vec| -> Result { + let dir = text(&a, 0) == "/d"; + Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))])) + }; + let list = move |_: Vec| -> Result { + let e = |n: &str| obj(vec![("fs", Data::String(format!("/d/{n}"))), ("dir", Data::Bool(false))]); + Ok(obj(vec![("entries", Data::Array(vec![e("a"), e("b")]))])) + }; + let mut r = Realm::new(); + let items: Vec<(String, HostItem)> = vec![ + ("text".into(), HostItem::Object(messages.to_vec())), + ("system".into(), HostItem::Value(Data::String("Unix".into()))), + ("lineFeed".into(), HostItem::Value(Data::String("Unix".into()))), + ("current".into(), f(|_| Data::String("/".into()))), + ("parse".into(), HostItem::Function(Rc::new(move |a: Vec| Ok(parse(&a))))), + ("stat".into(), HostItem::Function(Rc::new(stat))), + ("list".into(), HostItem::Function(Rc::new(list))), + ("tempName".into(), f(|_| Data::String("/tmp1".into()))), + ("locations".into(), f(|_| Data::Object(vec![]))), + ]; + r.define_file_classes(items).unwrap(); + r + } + + #[test] + fn objects_keep_their_classes_through_collections() { + let mut r = realm(); + r.run("var kept = new File('x'); var listed = new Folder('d').getFiles(); File = null; Folder = null;").unwrap(); + r.collect_garbage(); + r.run("var many = []; for (var i = 0; i < 2000; i++) many.push(kept.parent);").unwrap(); + r.collect_garbage(); + let v = r.run( + "[kept.name, kept.fsName, listed.length, listed[1].name, kept.parent.getFiles(function (f) { return f.name === 'd/a'; }).length].join()", + ); + assert_eq!(v.unwrap(), JsValue::String("x,/x,2,d/b,1".into())); + } + + #[test] + fn the_constructor_picks_the_class_only_without_new() { + let mut r = realm(); + let v = r.run( + "var F = File, D = Folder; [F('d') instanceof D, new F('d') instanceof F, D('x') instanceof D, \ + typeof Object.keys(new F('x')).length, Object.keys(new F('x')).length].join()", + ); + assert_eq!(v.unwrap(), JsValue::String("true,true,true,number,0".into())); + let e = r.run("File.prototype.read.call({})").unwrap_err(); + assert!(e.message.contains("is not a File or a Folder"), "{e:?}"); + } +} diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4ec8f2c721..fbb5e4fc90 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -85,11 +85,13 @@ pub enum Arg { Bool, } -/// How the arguments of a host function are read. +/// How the arguments of a host function are read, and its result given. #[derive(Clone)] pub(crate) enum ArgRead { /// Each as [`Data`]. Data, + /// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value. + Frozen, /// Each as the string `String(value)` gives. Text, /// One by one as the list says; those past its end are not read. @@ -109,6 +111,9 @@ pub enum HostItem { Converted(Vec, HostFunction), /// A property whose value the function gives each time it is read. Getter(HostFunction), + /// A property whose value the function gives each time it is read, frozen as + /// [`HostItem::Value`] gives its value. + FrozenGetter(HostFunction), /// A property whose value `get` gives each time it is read, and that `set` is given each value /// assigned to it, as its one argument; an error from `set` is thrown to the script. Property { @@ -359,7 +364,7 @@ impl Interp { let result = f(data); self.can_wait.set(false); match result { - Ok(d) => self.write_data(d, 0, false), + Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; self.pause.set(true); @@ -390,13 +395,31 @@ impl Interp { Err(e) => return Err(self.host_error(e)?), }; let writes = strict_writes().unwrap_or_else(|| self.writes_mode()); - self.evaluated = self.evaluated.saturating_add(1); + self.evaluated = crate::realm::next_tag(self.evaluated); let tag = std::mem::replace(&mut self.source_tag, self.evaluated); - let code = self.encode_source(&source).and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)); + // UTF-8 takes at most 3 bytes for each UTF-16 code unit, so the fuel for a third of the + // bytes is taken before the source is encoded, and the rest after. A source within the + // source limit must fit in the heap whole before it is encoded; a longer one is refused as + // a syntax error when it is encoded. + let floor = source.len().div_ceil(3); + let fits = |interp: &mut Self| { + let units = source.encode_utf16().count(); + if interp.check_source_units(units).is_ok() { interp.reserve_heap(string_bytes(units)) } else { Ok(()) } + }; + let code = self.prepare_source(floor).and_then(|()| fits(self)).map(|()| { + let units = self.encode_source(&source); + let rest = match &units { + Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), + Err(_) => Ok(()), + }; + rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + }); + let code = code.and_then(|c| c); self.source_tag = tag; let r = match code { - Ok(code) => self.run_global(code, true), - Err(e) => Err(self.compile_error_to_abrupt(e)), + Ok(Ok(code)) => self.run_global(code, true), + Ok(Err(e)) => Err(self.compile_error_to_abrupt(e)), + Err(limit) => Err(limit), }; end(); r @@ -412,14 +435,14 @@ impl Interp { let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data) { + if !matches!(how, ArgRead::Data | ArgRead::Frozen) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -485,7 +508,7 @@ impl Interp { self.define(global, key(name), Prop::Data { value: Value::Object(o), flags: 0 }) } - fn host_object(&mut self, path: &str, items: Vec<(String, HostItem)>) -> JsResult { + pub(crate) fn host_object(&mut self, path: &str, items: Vec<(String, HostItem)>) -> JsResult { let o = self.new_object(); let mark = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); @@ -507,6 +530,7 @@ impl Interp { let prop = match item { HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE }, + HostItem::FrozenGetter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Frozen)), set: None, flags: ENUMERABLE }, HostItem::Property { get, set } => Prop::Accessor { get: Some(self.host_function(get, &full, ArgRead::Data)), set: Some(self.host_function(set, &full, ArgRead::Data)), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 48aaa96106..de252c6c64 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -58,6 +58,42 @@ fn state_survives_a_pause_and_a_collection_between_slices() { assert_eq!(finish(&mut r, 50).0.unwrap(), JsValue::Number(1500.0)); } +/// A paused run that is ended leaves no frames behind: the realm starts the next run with its +/// globals, as many times as it is ended. +#[test] +fn an_ended_run_leaves_the_realm_ready_for_the_next() { + let mut r = realm(u64::MAX); + for _ in 0..3 { + r.start("var kept = 'yes'; function deep(n) { return n ? deep(n - 1) : (function () { while (true) {} })(); } deep(50);").unwrap(); + assert_eq!(r.advance(500).unwrap(), Progress::Paused); + r.end(); + assert!(!r.is_running()); + } + assert!(r.interp().frames.is_empty() && r.interp().stack.is_empty()); + r.start("kept").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("yes".into())); + r.end(); +} + +/// Setting `Folder.current` back for the next run drops what only the last run's uncaught +/// exception held, so a full heap from that exception does not stop the next run. +#[test] +fn resetting_folder_current_drops_the_last_uncaught_exception() { + let mut r = realm(10_000_000); + let len = Rc::new(Cell::new(4)); + let n = len.clone(); + let current: HostFunction = Rc::new(move |_| Ok(Data::String("d".repeat(n.get())))); + r.define_file_classes(vec![("current".into(), HostItem::Function(current))]).unwrap(); + assert!(r.run("throw (function () { var a = []; for (var i = 0; i < 2000; i++) a.push('item ' + i); return a; })();").is_err()); + let interp = r.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes; + len.set(200); + assert_eq!(r.reset_folder_current(), Ok(())); + r.set_limits(Limits::default()); + assert_eq!(r.run("typeof Folder"), Ok(JsValue::String("function".into()))); +} + #[test] fn the_fuel_limit_covers_every_slice_together() { let mut r = realm(5_000); @@ -223,6 +259,18 @@ fn a_getter_is_read_each_time() { assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0)); } +/// A frozen getter gives a new value each time it is read, frozen to its leaves. +#[test] +fn a_frozen_getter_gives_a_frozen_value_each_time() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Ok(Data::Object(vec![("a".into(), Data::Array(vec![Data::Number(1.0)]))]))); + let g = f.clone(); + r.define_host_object("host", vec![("v".into(), HostItem::FrozenGetter(f)), ("open".into(), HostItem::Getter(g))]).unwrap(); + let source = "var v = host.v; v.b = 2; try { v.a.push(2); } catch (e) {} \ + [Object.isFrozen(v), Object.isFrozen(v.a), v.b === undefined, v.a.length, host.v === host.v, Object.isFrozen(host.open)].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true,true,true,1,false,false".into())); +} + #[test] fn a_text_function_takes_each_argument_as_string_gives_it() { let mut r = realm(1_000_000); @@ -323,6 +371,169 @@ fn an_error_says_where_in_the_source_it_was_raised() { assert_eq!(e.message, "TypeError: no"); } +/// An error a `finally` block passes on unchanged is reported where it was raised; one the block +/// throws itself, or a catch throws again, is reported at that new throw. Each finally block holds +/// a statement, so its end is not at the throw's position. +#[test] +fn an_error_that_passes_through_a_finally_block_says_where_it_was_raised() { + let mut r = realm(1_000_000); + let cases = [ + ("try {\n throw new Error('x');\n} finally {\n var z=1;\n}", (2, 3), "Error: x"), + ("try {\n null();\n} finally {\n var z=1;\n}", (2, 3), "TypeError: the value is not a function"), + ("try {\n throw 5;\n} finally {\n var z=1;\n}", (2, 3), "5"), + ("try {\n try { throw new Error('x'); } finally { var z=1; }\n} catch (e) { throw e; }", (3, 15), "Error: x"), + ("try {\n try { throw new Error('x'); } finally { var z=1; }\n} finally { var z=1; }", (2, 9), "Error: x"), + ("function f() {\n try { throw new Error('x'); } finally { var z=1; }\n}\nf();", (2, 9), "Error: x"), + ("try { throw new Error('x'); } catch (e) {\n throw e;\n}", (2, 3), "Error: x"), + ("try { throw new Error('x'); } finally {\n throw new Error('y');\n}", (2, 3), "Error: y"), + ("var e = new Error('x');\ntry {\n throw e;\n} finally {\n throw e;\n}", (5, 3), "Error: x"), + ("try {\n throw new Error('outer');\n} finally {\n try { throw new Error('inner'); } catch (e) {}\n}", (2, 3), "Error: outer"), + ("function g(){ try { throw new Error('inner'); } catch(e) {} }\ntry { throw new Error('outer'); } finally { g(); }", (2, 7), "Error: outer"), + ( + "for (var i = 0; i < 2000; i++) { try { throw 1; } finally { continue; } }\ntry {\n throw new Error('x');\n} finally {\n var z=1;\n}", + (3, 3), + "Error: x", + ), + ]; + for (source, (line, column), message) in cases { + let e = r.run(source).unwrap_err(); + assert_eq!((e.kind, e.line, e.column, e.message.as_str()), (RunErrorKind::Thrown, line, column, message), "{source}"); + } + let mut nested = String::new(); + for _ in 0..40 { + nested.push_str("try {\n"); + } + nested.push_str(" throw new Error('deep');\n"); + for _ in 0..40 { + nested.push_str("} finally { var z=1; }\n"); + } + let e = r.run(&nested).unwrap_err(); + assert_eq!((e.line, e.column), (41, 3), "forty finally blocks"); + for source in [ + "function f(){ try { throw new Error('x'); } finally { return 4; } }\nf();", + "while(true) { try { throw new Error('x'); } finally { break; } }\n7;", + "for(var i=0;i<1;i++){ try { throw new Error('x'); } finally { continue; } }\n7;", + ] { + assert!(r.run(source).is_ok(), "{source}"); + } +} + +#[test] +fn a_resumed_run_reports_an_error_that_passes_through_a_finally_block_where_it_was_raised() { + let mut r = realm(1_000_000); + r.start("try {\n throw new Error('x');\n} finally {\n var a=1;\n}").unwrap(); + let e = finish(&mut r, 1).0.unwrap_err(); + assert_eq!((e.kind, e.line, e.column), (RunErrorKind::Thrown, 2, 3)); +} + +#[test] +fn a_marked_host_error_that_passes_through_a_finally_block_says_where_it_was_raised() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Err(HostError::Marked { error: Box::new(HostError::Syntax("bad file".into())), mark: 7 })); + r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap(); + let e = r.run("try {\n host.f();\n} finally { var z=1; }").unwrap_err(); + assert_eq!((e.kind, e.line, e.column), (RunErrorKind::Thrown, 2, 3)); + assert_eq!(r.error_mark(), Some(7)); +} + +/// A realm with a 1 MiB heap, the size that the `finally` blocks of these tests collect garbage in. +fn small_heap_realm() -> Realm { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 200_000_000, heap_bytes: 1 << 20, ..Limits::default() }); + r +} + +/// Begins a run of `source` and advances it one instruction at a time until a `finally` block runs +/// for an exception whose throw site is saved. +fn start_until_a_throw_site_is_saved(r: &mut Realm, source: &str) { + r.start(source).unwrap(); + while r.interp().finally_sites.is_empty() { + assert_eq!(r.advance(1), Ok(Progress::Paused), "{source}"); + } +} + +/// The collections that a `finally` block's allocations cause under a small heap limit keep the +/// site its exception was raised at, and the run's end leaves no saved site behind. +#[test] +fn an_error_that_passes_through_a_finally_block_that_collects_garbage_says_where_it_was_raised() { + let mut r = small_heap_realm(); + let source = "try {\n throw new Error('original');\n} finally {\n for (var i = 0; i < 20000; i++) { var waste = [i, i + 1, i + 2]; }\n}"; + start_until_a_throw_site_is_saved(&mut r, source); + r.collect_garbage(); + let collections = r.interp().heap.collections; + let e = loop { + match r.advance(1_000) { + Ok(Progress::Paused) => assert_eq!(r.interp().finally_sites.len(), 1, "the site stays saved while the block runs"), + Ok(Progress::Done(v)) => panic!("the run ended with {v:?}"), + Err(e) => break e, + } + }; + assert!(r.interp().heap.collections > collections, "the block's allocations collect garbage"); + assert_eq!((e.kind, e.line, e.column, e.message.as_str()), (RunErrorKind::Thrown, 2, 3, "Error: original")); + assert!(r.interp().finally_sites.is_empty()); +} + +/// The code of a saved throw site stays live through a collection: direct `eval` code that +/// threw is not part of the code of any frame still running. +#[test] +fn a_saved_throw_site_keeps_its_code_live() { + let mut r = small_heap_realm(); + let source = "try {\n eval(\"var unused = 'padding padding padding padding';\\nthrow new Error('original');\");\n} finally {\n for (var i = 0; i < 2000; i++) { var waste = [i]; }\n}"; + start_until_a_throw_site_is_saved(&mut r, source); + let with_site = r.collect_garbage(); + let sites = std::mem::take(&mut r.interp().finally_sites); + let without_site = r.collect_garbage(); + r.interp().finally_sites = sites; + assert_eq!(r.collect_garbage(), with_site, "the saved site's code is counted again"); + assert!(with_site > without_site, "{with_site} <= {without_site}"); + let e = finish(&mut r, 1_000).0.unwrap_err(); + assert_eq!((e.kind, e.line, e.message.as_str()), (RunErrorKind::Thrown, 2, "Error: original")); + assert!(r.interp().finally_sites.is_empty()); +} + +/// A run that a host function stops inside a `finally` block leaves no saved throw site behind. +#[test] +fn a_run_stopped_in_a_finally_block_leaves_no_saved_throw_site() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Err(HostError::Abort("stopped".into()))); + r.define_host_object("host", vec![("abort".into(), HostItem::Function(f))]).unwrap(); + let e = r.run("try { throw new Error('original'); } finally { host.abort(); }").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped")); + assert!(r.interp().finally_sites.is_empty()); + assert_eq!(r.run("1").unwrap(), JsValue::Number(1.0)); + assert!(r.interp().finally_sites.is_empty()); +} + +/// A `finally` block that `break`, `continue` or `return` leaves drops the saved site of the +/// exception it ran for as it leaves, before the stack grows back over that site's slot. +#[test] +fn leaving_a_finally_block_early_drops_its_saved_throw_site() { + let mut r = realm(1_000_000); + let marked = Rc::new(Cell::new(false)); + let seen = marked.clone(); + let f: HostFunction = Rc::new(move |_| { + seen.set(true); + Ok(Data::Undefined) + }); + r.define_host_object("host", vec![("mark".into(), HostItem::Function(f))]).unwrap(); + for source in [ + "do { try { throw new Error('x'); } finally { break; } } while (false);\nhost.mark(); var a = [1, 2, 3];", + "for (var i = 0; i < 1; i++) { try { throw new Error('x'); } finally { continue; } }\nhost.mark(); var a = [1, 2, 3];", + "function f() { try { throw new Error('x'); } finally { return 1; } }\nf(); host.mark(); var a = [f, f, f];", + ] { + marked.set(false); + let mut saved = false; + r.start(source).unwrap(); + while r.advance(1).unwrap() == Progress::Paused { + saved |= !r.interp().finally_sites.is_empty(); + if marked.get() { + assert!(r.interp().finally_sites.is_empty(), "{source}"); + } + } + assert!(saved && marked.get(), "{source}"); + } +} + #[test] fn advancing_without_a_run_is_an_error() { let mut r = realm(1_000); @@ -408,6 +619,95 @@ fn a_converted_function_reads_each_argument_as_its_list_says() { assert_eq!(out, JsValue::String("function 1".into()), "a script may replace the function"); } +#[test] +fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() { + let mut r = realm(10_000_000); + let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + r.run("function late() { throw new Error('late'); }").unwrap(); + assert!(r.run("host.load()").is_err()); + assert_eq!(r.error_source(), 1, "the first source the evaluator gave in this run"); + assert!(r.run("\nlate()").is_err()); + assert_eq!(r.error_source(), UNKNOWN_SOURCE, "an earlier script defined late"); + assert!(r.run("\nthrow 1").is_err()); + assert_eq!(r.error_source(), 0); + assert!(r.run("host.load()").is_err()); + assert_eq!(r.error_source(), 1, "counted again from this run's script"); + assert!(r.run("var = 1").is_err()); + assert_eq!(r.error_source(), 0, "a syntax error is in the script"); +} + +#[test] +fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { + let mut r = realm(10_000_000); + let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet"); + r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap(); + let first = r.script_tag(); + assert_ne!(first, UNKNOWN_SOURCE); + assert!(r.run("\nlate()").is_err()); + let second = r.script_tag(); + assert!(second > first + 2, "the evaluator's two sources took the tags after the first script"); + assert_eq!((r.error_source(), r.error_tag()), (UNKNOWN_SOURCE, first), "late keeps its script's tag"); + assert!(r.run("inEval()").is_err()); + assert_eq!(r.error_tag(), first + 2, "the second source the evaluator gave in the first run"); + assert!(r.run("\nthrow 1").is_err()); + assert_eq!((r.error_source(), r.error_tag()), (0, r.script_tag())); + // Once the tags are used up, a source gets no tag rather than one an earlier source has. + r.set_last_tag(UNKNOWN_SOURCE - 3); + r.run("function nearEnd() { throw 1; }\nhost.load(); host.load(); host.load();").unwrap(); + assert_eq!(r.script_tag(), UNKNOWN_SOURCE - 2); + assert!(r.run("nearEnd()").is_err()); + assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "a script after the last tag"); + assert_eq!(r.error_tag(), UNKNOWN_SOURCE - 2); + assert!(r.run("inEval()").is_err()); + assert_eq!(r.error_tag(), UNKNOWN_SOURCE, "the third source came after the last tag"); + assert!(r.run("\nthrow 1").is_err()); + assert_eq!((r.error_source(), r.error_tag()), (UNKNOWN_SOURCE, UNKNOWN_SOURCE)); +} + +#[test] +fn an_evaluators_source_takes_fuel_before_it_is_parsed() { + // The evaluator gives 131,072 spaces and a number: far more code units than the fuel left. + let ends = Rc::new(Cell::new(0)); + let ended = ends.clone(); + let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17))))); + let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) }; + let mut r = realm(10_000); + r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); + let e = r.run("host.evaluate()").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert_eq!(ends.get(), 1, "the evaluator's end runs once"); + // This fuel covers a third of the source's bytes but not all of its code units. + r.set_limits(Limits { fuel: 60_000, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert_eq!(ends.get(), 2); + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()"), Ok(JsValue::Number(7.0))); + assert_eq!(ends.get(), 3); +} + +#[test] +fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() { + // A third of the source and the other two thirds each fit in the heap; the whole does not. + // The source does not parse, so a parse would throw a syntax error instead. + let n = (1 << 17) + 1; + let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1))))); + let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let mut r = realm(1_000_000); + r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); + r.interp().collect_for_room(); + let heap_bytes = r.interp().heap.bytes + crate::heap::string_bytes(n * 5 / 6); + r.set_limits(Limits { fuel: 1_000_000, heap_bytes, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Limit(LimitKind::Heap)); + // With room for the whole source, it is parsed. + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Thrown); +} + proptest::proptest! { /// A slice size does not change what a script computes. #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ed30993523..22a365b615 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -9,7 +9,8 @@ //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap //! limit, the frame limit, the re-entry limit and the interrupt flag each end the run with an -//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks. +//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks. Source +//! compiled during a run takes a unit of fuel for each code unit before it is parsed. //! //! Collection runs only between instructions. An operation that may run JavaScript in the middle //! keeps its operands on the operand stack until it is done, so everything it holds is reachable @@ -26,6 +27,7 @@ use crate::heap::{ ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; +use crate::string_builtins::flat_charged; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; use crate::{LimitKind, Limits, Options}; @@ -198,10 +200,18 @@ pub(crate) struct Interp { pub(crate) held_bytes: usize, /// Why installing the built-ins failed; a realm with this set runs no script. pub(crate) install_error: Option, + /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). + pub(crate) files: Option, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. pub(crate) held: Rc, + /// Bytes of the copies [`Self::get_own_property`] made flattening the rope of a String + /// object, which the heap's total adds before the next limit check. + flattened: std::cell::Cell, + /// Fuel for the units those copies took and the rope nodes it read in place, which the next + /// step takes. + pub(crate) flattened_fuel: std::cell::Cell, /// The global code's default XML namespace URI (ECMA-357 section 12.1). pub(crate) xml_default_uri: Key, /// Set by the host to end the current slice of a resumable run at the next safe point. @@ -230,6 +240,13 @@ pub(crate) struct Interp { /// runs. An entry whose slot no longer holds its exception belongs to a block that `break`, /// `continue` or `return` left, and [`Self::drop_left_finally_marks`] removes it. pub(crate) finally_marks: Vec<(ObjId, u32, usize)>, + /// Where the exceptions `finally` blocks are running for were raised, innermost last, each with + /// the stack slot that holds the exception while the block runs. The block's end throws the + /// exception on from that site. An entry whose slot is at or above the stack's length belongs to + /// a block that was left, and [`Self::drop_left_finally_sites`] removes it at each `Jump`, each + /// return and each collection. [`Self::unwind`] removes the entries at or above a handler's slot + /// before it adds one, so the slots rise and the list is never longer than the stack. + pub(crate) finally_sites: Vec<(ThrowSite, usize)>, /// The mark of the host error the last run ended with. pub(crate) error_mark: Option, /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. @@ -291,6 +308,12 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. const KEY_ENTRY_BYTES: usize = 32; +#[cfg(test)] +thread_local! { + /// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at. + pub(crate) static SITE_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The estimated bytes of the index names `0` to `len - 1` while `for-in` lists them. fn index_keys_bytes(len: usize) -> usize { let mut total = 0usize; @@ -305,13 +328,21 @@ fn index_keys_bytes(len: usize) -> usize { total } -/// A seed for `Math.random` that differs from realm to realm, from the standard library's -/// randomly keyed hasher; never zero. +/// A seed for `Math.random` that differs from realm to realm and from run to run, from the OS +/// random source (the browser's crypto on the web), or the standard library's randomly keyed +/// hasher when that fails; never zero. fn random_seed() -> u64 { + random_seed_from(getrandom::u64()) +} + +/// [`random_seed`] from what the OS random source returned. +pub(crate) fn random_seed_from(os: Result) -> u64 { use std::hash::{BuildHasher, Hasher}; - let mut h = std::collections::hash_map::RandomState::new().build_hasher(); - h.write_u64(0x9e37_79b9_7f4a_7c15); - h.finish() | 1 + os.unwrap_or_else(|_| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(0x9e37_79b9_7f4a_7c15); + h.finish() + }) | 1 } /// The estimated bytes of a binding or property named by `len` code units. @@ -423,8 +454,11 @@ impl Interp { join_stack: Vec::new(), held_bytes: 0, install_error: None, + files: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), + flattened: std::cell::Cell::new(0), + flattened_fuel: std::cell::Cell::new(0), xml_default_uri: Rc::from(Vec::new()), pause: Rc::default(), in_slice: false, @@ -437,6 +471,7 @@ impl Interp { error_tag: crate::realm::UNKNOWN_SOURCE, thrown_mark: None, finally_marks: Vec::new(), + finally_sites: Vec::new(), error_mark: None, strict_writes: false, }; @@ -543,6 +578,7 @@ impl Interp { fn tick(&mut self) -> JsResult<()> { self.use_fuel()?; + crate::regexp_vm::use_fuel_n(self, self.flattened_fuel.replace(0))?; self.settle_held(); if self.heap.bytes > self.gc_threshold { self.collect_garbage(); @@ -569,10 +605,12 @@ impl Interp { Ok(()) } - /// Takes the bytes that dropped [`HeldBytes`] released off the heap's total. + /// Takes the bytes that dropped [`HeldBytes`] released off the heap's total, and adds the + /// bytes of the ropes [`Self::get_own_property`] flattened. fn settle_held(&mut self) { let released = self.held.released.replace(0); - self.heap.bytes = self.heap.bytes.saturating_sub(released); + let flattened = self.flattened.replace(0); + self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened); } /// Collects garbage now and sets when the next collection runs. @@ -592,6 +630,22 @@ impl Interp { Ok(()) } + /// Prepares for parsing `units` code units of source at run time: takes a unit of fuel for + /// each code unit and checks that the source text fits in the heap, before any of it is + /// flattened, parsed or compiled. Running out of fuel uses up what was left. + pub(crate) fn prepare_source(&mut self, units: usize) -> JsResult<()> { + let fuel = u64::try_from(units).unwrap_or(u64::MAX); + if fuel > self.fuel { + self.fuel = 0; + return Err(Abrupt::Limit(LimitKind::Fuel)); + } + self.fuel -= fuel; + if self.interrupt.load(Ordering::Relaxed) { + return Err(Abrupt::Limit(LimitKind::Interrupted)); + } + self.reserve_heap(string_bytes(units)) + } + /// Removes the [`Self::finally_marks`] entries of `finally` blocks that `break`, `continue` or /// `return` left: those whose stack slot no longer holds their exception. fn drop_left_finally_marks(&mut self) { @@ -599,8 +653,22 @@ impl Interp { self.finally_marks.retain(|&(id, _, slot)| matches!(stack.get(slot), Some(Value::Object(o)) if *o == id)); } + /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of + /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. + fn drop_left_finally_sites(&mut self, len: usize) { + while let Some(&(_, slot)) = self.finally_sites.last() { + #[cfg(test)] + SITE_CHECKS.with(|c| c.set(c.get() + 1)); + if slot < len { + break; + } + self.finally_sites.pop(); + } + } + pub(crate) fn collect_garbage(&mut self) { self.drop_left_finally_marks(); + self.drop_left_finally_sites(self.stack.len()); let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); @@ -608,6 +676,7 @@ impl Interp { roots.values.push(&self.last_error); roots.values.push(&self.passing); roots.objects.extend(self.finally_marks.iter().map(|&(id, _, _)| id)); + roots.codes.extend(self.finally_sites.iter().map(|((code, _), _)| &**code)); for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); @@ -618,10 +687,12 @@ impl Interp { } roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); + roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); + self.flattened.set(0); self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()); } @@ -718,11 +789,15 @@ impl Interp { } self.stack.truncate(target_len); self.drop_left_finally_marks(); + self.drop_left_finally_sites(target_len); if let (Some(mark), false, Value::Object(id)) = (self.thrown_mark.take(), caught, &v) { self.finally_marks.push((*id, mark, target_len)); } self.stack.push(v); - self.throw_site = None; + let site = self.throw_site.take(); + if let (false, Some(site)) = (caught, site) { + self.finally_sites.push((site, target_len)); + } return Ok(()); } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; @@ -752,6 +827,8 @@ impl Interp { fn return_value(&mut self, v: Value) -> JsResult> { let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + // A `return` in a finally block leaves the block, and the value takes its exception's slot. + self.drop_left_finally_sites(frame.base); let v = match frame.construct { Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o), _ => v, @@ -838,7 +915,11 @@ impl Interp { Op::New(n) => self.op_new(n), Op::Binary(b) => self.op_binary(b), Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber => self.op_unary(op), - Op::Jump(t) => self.jump_to(t), + Op::Jump(t) => { + // `break` and `continue` leave a `finally` block by popping its exception and jumping. + self.drop_left_finally_sites(self.stack.len()); + self.jump_to(t) + } Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => self.op_branch(t, matches!(op, Op::JumpIfTrue(_)), false), Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => self.op_branch(t, matches!(op, Op::JumpIfTrueKeep(_)), true), Op::Throw => { @@ -875,11 +956,12 @@ impl Interp { Op::XmlEscape(kind) => self.op_xml_escape(kind), Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list), Op::XmlScopeGet => self.op_xml_scope_get(), + Op::XmlScopeRef => self.op_xml_scope_ref(), Op::XmlFilterStart => self.op_xml_filter_start(), Op::XmlFilterNext(t) => self.op_xml_filter_next(t), Op::XmlFilterTest => self.op_xml_filter_test(), Op::XmlFilterEnd => self.op_xml_filter_end(), - Op::ForEachValue => self.op_for_each_value(), + Op::ForEachValue(n) => self.op_for_each_value(n as usize), Op::SetDefaultNamespace => self.op_set_default_namespace(), Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), } @@ -945,6 +1027,11 @@ impl Interp { self.thrown_mark = self.finally_marks.get(i).map(|&(_, mark, _)| mark); self.finally_marks.truncate(i); } + let slot = self.stack.len(); + if let Some(i) = self.finally_sites.iter().rposition(|&(_, s)| s == slot) { + self.throw_site = self.finally_sites.get(i).map(|(site, _)| site.clone()); + self.finally_sites.truncate(i); + } return Err(Abrupt::Throw(v)); } let k = (kind - 2.0) as usize; @@ -1161,7 +1248,33 @@ impl Interp { if let Some(i) = array_index(k) && (i as usize) < s.len() { - let unit = s.flat().get(i as usize).copied().unwrap_or(0); + let unit = if s.is_rope() { + let owed = self.flattened_fuel.get(); + let flattened = self.flattened.get().saturating_add(string_bytes(s.len())); + if self.heap.bytes.saturating_add(flattened) > self.limits.heap_bytes { + // The copy does not fit without a collection, which needs `&mut self`: + // the unit is read along the rope instead, a unit of fuel per node. + let Some((unit, visited)) = s.unit_at(i as usize, self.fuel.saturating_sub(owed)) else { + return Err(Abrupt::Limit(LimitKind::Fuel)); + }; + self.flattened_fuel.set(owed.saturating_add(visited)); + unit + } else { + // Flattening copies the units. The run ends here when the fuel for + // the copy is not left; otherwise the next step takes it, and the + // next limit check adds the copy's bytes. + let fuel = owed.saturating_add((s.len() / crate::string_builtins::UNITS_PER_FUEL) as u64 + 1); + if fuel > self.fuel { + return Err(Abrupt::Limit(LimitKind::Fuel)); + } + self.flattened_fuel.set(fuel); + self.flattened.set(flattened); + s.flat().get(i as usize).copied() + } + } else { + s.flat().get(i as usize).copied() + } + .unwrap_or(0); return Ok(Some(Prop::Data { value: Value::String(Str::from_units(vec![unit])), flags: ENUMERABLE })); } } @@ -1238,7 +1351,7 @@ impl Interp { if let Some(i) = array_index(k) && (i as usize) < s.len() { - let unit = s.flat().get(i as usize).copied().unwrap_or(0); + let unit = flat_charged(self, s)?.get(i as usize).copied().unwrap_or(0); return Ok(Value::String(Str::from_units(vec![unit]))); } } @@ -2345,7 +2458,8 @@ impl Interp { }; let strict = self.strict(); self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; - let units = s.flat(); + self.prepare_source(s.len())?; + let units = self.flat_reserved(s)?; let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; @@ -2510,7 +2624,7 @@ impl Interp { Value::Null => 0.0, Value::Bool(b) => f64::from(u8::from(*b)), Value::Number(n) => *n, - Value::String(s) => string_to_number(&s.flat()), + Value::String(s) => string_to_number(&flat_charged(self, s)?), Value::Object(_) => { let p = self.to_primitive(v, Hint::Number)?; return self.to_number(&p); @@ -2544,19 +2658,28 @@ impl Interp { #[allow(clippy::wrong_self_convention)] pub(crate) fn to_key(&mut self, v: &Value) -> JsResult { match v { - Value::String(s) => { - let rope = s.is_rope(); - let flat = s.flat(); - if rope { - self.heap.bytes += string_bytes(flat.len()); - } - Ok(flat) - } + Value::String(s) => self.flat_reserved(s), Value::Number(n) if *n >= 0.0 && *n < 4_294_967_295.0 && n.fract() == 0.0 => Ok(index_key(*n as u32)), - _ => Ok(self.to_str(v)?.flat()), + _ => { + let s = self.to_str(v)?; + self.flat_reserved(&s) + } } } + /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that + /// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays + /// rooted while the copy is reserved; everything else the caller still needs must be + /// reachable from the roots. + fn flat_reserved(&mut self, s: &Str) -> JsResult { + if s.is_rope() { + let bytes = string_bytes(s.len()); + self.rooted(&[Value::String(s.clone())], |i| i.reserve_heap(bytes))?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + Ok(s.flat()) + } + /// ToObject (section 9.9). #[allow(clippy::wrong_self_convention)] pub(crate) fn to_object(&mut self, v: &Value) -> JsResult { @@ -2679,7 +2802,11 @@ impl Interp { (self.to_primitive(x, Hint::Number)?, py) }; if let (Value::String(a), Value::String(b)) = (&px, &py) { - return Ok(Some(*a.flat() < *b.flat())); + // Both stay rooted, so the first copy is still counted while the second is made. + return self.rooted(&[px.clone(), py.clone()], |i| { + let (a, b) = (flat_charged(i, a)?, flat_charged(i, b)?); + Ok(Some(*a < *b)) + }); } let nx = self.to_number(&px)?; let ny = self.to_number(&py)?; @@ -2704,7 +2831,9 @@ impl Interp { | (Value::String(_), Value::String(_)) | (Value::Bool(_), Value::Bool(_)) | (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)), - (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => return Ok(*n == string_to_number(&s.flat())), + (Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => { + return Ok(*n == string_to_number(&flat_charged(self, s)?)); + } (Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))), (_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))), (Value::Number(_) | Value::String(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?, diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d2a12b5fb0..93c487b378 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use proptest::prelude::*; use crate::bytecode::{Code, Handler, Op, Source, verify}; -use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; +use crate::{JsValue, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind}; fn run(src: &str) -> JsValue { match Realm::new().run(src) { @@ -357,6 +357,58 @@ fn function_source_text_counts_toward_the_heap() { assert_eq!(realm.run("(function f(a) { return a; }).toString()"), Ok(JsValue::String("function f(a) { return a; }".into()))); } +#[test] +fn a_function_that_returns_from_a_finally_block_does_not_keep_its_code() { + // The function's source holds a 256 Ki-unit comment. Its result stays on the stack while the + // second call runs, after the function was dropped. A collection then leaves its code out of + // the live total, as it does for a function whose finally block ran without an exception. + let live = |body: &str| { + let mut r = small(Limits::default()); + let src = format!( + "var s = 'x'; for (var i = 0; i < 18; i++) s += s;\n\ + var f = Function('/*' + s + '*/ try {{ {body} }} finally {{ return 0; }}'); s = null;\n\ + f() + (f = null, (function () {{ var a = 0; for (var i = 0; i < 50; i++) a += i; return a; }})())" + ); + if let Err(e) = r.start(&src) { + panic!("{e:?}"); + } + let mut bytes = None; + loop { + match r.advance(1) { + Ok(Progress::Paused) => { + let i = r.interp(); + if i.frames.len() == 2 && i.stack.len() > 1 { + i.collect_garbage(); + bytes = Some(i.heap.bytes); + } + } + Ok(Progress::Done(v)) => { + assert_eq!(v, JsValue::Number(1225.0)); + break; + } + Err(e) => panic!("{e:?}"), + } + } + let Some(bytes) = bytes else { panic!("the second call never paused") }; + bytes + }; + let (plain, thrown) = (live(""), live("throw 1;")); + assert!(thrown < plain + 4096, "{thrown} > {plain}"); +} + +#[test] +fn a_return_looks_only_at_the_finally_sites_of_its_own_frame() { + // 200 finally blocks run at once, each for its own exception, and the innermost calls a + // function 1,000 times. Each return looks at the last saved site only, not at all 200. + let src = "function g() { return 1; }\n\ + function f(n) { try { throw n; } finally { if (n) { f(n - 1); } else { for (var i = 0; i < 1000; i++) g(); } } }\n\ + try { f(199); } catch (e) { e; }"; + crate::interp::SITE_CHECKS.with(|c| c.set(0)); + assert_eq!(small(Limits::default()).run(src), Ok(JsValue::Number(0.0))); + let checks = crate::interp::SITE_CHECKS.with(std::cell::Cell::get); + assert!(checks < 10_000, "{checks} saved sites looked at"); +} + #[test] fn for_in_names_take_fuel_and_heap_under_later_limits() { // The first run, under the default limits, builds an object with many properties. Later runs @@ -448,6 +500,19 @@ fn declarations_take_fuel() { assert_eq!(limit(&mut realm, &format!("Function('var {vars};')();")), LimitKind::Fuel); } +#[test] +fn source_compiled_during_a_run_takes_fuel_before_it_is_parsed() { + // Doubling a string 17 times makes 131,072 spaces in about a hundred instructions, so only + // the compiled source can use up the fuel. + let build = "var s = ' '; for (var i = 0; i < 17; i++) s += s;"; + let mut realm = small(Limits { fuel: 10_000, ..Limits::default() }); + for call in ["eval(s)", "(0, eval)(s)", "Function(s)", "new Function('a', s)"] { + assert_eq!(limit(&mut realm, &format!("{build} {call};")), LimitKind::Fuel, "{call}"); + } + let mut realm = small(Limits { fuel: 1_000_000, ..Limits::default() }); + assert_eq!(realm.run(&format!("{build} eval(s + '1') + (0, eval)(s + '2') + Function(s + 'return 3')()")), Ok(JsValue::Number(6.0))); +} + #[test] fn a_lower_heap_limit_applies_to_what_is_already_live() { // A heap already past the new limit ends the next run. @@ -771,13 +836,14 @@ fn long_property_names_count_toward_the_heap_after_their_strings_are_collected() // Each name is a 16,385-unit buffer that only the object's key or the function's binding // holds once the string that made it is garbage, so about 32 of them fill the heap well before // the fuel runs out. In the second script the property lookup flattens a long string each - // time, so collections run. + // time, so collections run. Each eval there also takes fuel for its source, so that run has + // more fuel. let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 20_000, ..Limits::default() }); let src = "var s = 'x'; while (s.length < 10000) s += s; var o = {}; for (var i = 0; ; i++) o[s + i] = 1;"; assert_eq!(limit(&mut realm, src), LimitKind::Heap); let src = "var s = 'x'; while (s.length < 10000) s += s; \ (function () { for (var i = 0; ; i++) { eval('var ' + s + i + ' = 1'); ({})[s + i]; } })();"; - let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 20_000, ..Limits::default() }); + let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 5_000_000, ..Limits::default() }); assert_eq!(limit(&mut realm, src), LimitKind::Heap); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a8478aa65a..cad290f1af 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -41,9 +41,11 @@ //! With [`Options::e4x`], the parser also reads E4X (ECMA-357, second edition, December 2005): //! XML and XMLList literals, the `.@`, `..`, `::` and `.( )` operators, `for each … in` and //! `default xml namespace`; the realm then provides `XML`, `XMLList`, `Namespace`, `QName`, -//! `isXMLName` and `setDefaultXMLNamespace`. Without the option, the language and the built-ins are +//! `isXMLName` and `setDefaultXMLNamespace`, and XML and XMLList values have an `xpath` method that +//! evaluates an XPath 1.0 expression. Without the option, the language and the built-ins are //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and -//! serializing them use no native recursion and take fuel for each node. +//! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each +//! node. #![forbid(unsafe_code)] pub mod ast; @@ -53,6 +55,7 @@ mod chars; mod compiler; mod date_builtins; mod error; +mod file_classes; mod heap; mod host; mod interp; @@ -69,6 +72,7 @@ mod token; mod value; mod xml; mod xml_builtins; +mod xpath; pub use ast::{ AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property, diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 3c2ab3ed30..fa201c58ff 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -873,8 +873,9 @@ impl<'s> Parser<'s> { } /// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code - /// neither `eval` nor `arguments`), a property, or outside strict mode code a call (assigning - /// to its result fails at run time, as ECMA-262 2015 Annex B and web browsers have it). + /// neither `eval` nor `arguments`), a property, an E4X name standing alone (`@a`, `ns::a`; + /// ECMA-357 section 11.1), or outside strict mode code a call (assigning to its result fails + /// at run time, as ECMA-262 2015 Annex B and web browsers have it). fn check_target(&self, expr: ExprId, message: &str) -> Result<()> { let inner = self.ast.unparenthesized(expr); match self.ast.expr(inner) { @@ -884,7 +885,7 @@ impl<'s> Parser<'s> { } Ok(()) } - Some(Expr::Member { .. } | Expr::Index { .. }) => Ok(()), + Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()), Some(Expr::Call { .. }) if !self.ctx.strict => Ok(()), _ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)), } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 1c2bb6ecf1..077f3b19b6 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -14,7 +14,8 @@ use crate::{Options, SyntaxError}; /// cannot catch it, and their `finally` blocks do not run. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Limits { - /// Instructions a run may execute. + /// Instructions a run may execute. Source that `eval`, `Function` or a host evaluator + /// compiles during the run also takes one unit for each UTF-16 code unit, before it is parsed. pub fuel: u64, /// Estimated bytes the heap (objects, environments and the strings they hold) may reach /// after a collection. A string longer than a quarter of this many code units cannot be @@ -62,6 +63,12 @@ pub enum LimitKind { /// evaluator's: code that `eval` or `Function` compiled, or an error with no place. pub const UNKNOWN_SOURCE: u32 = u32::MAX; +/// The source tag after `tag`. Once the tags are used up, every later source gets +/// [`UNKNOWN_SOURCE`], so no two sources share a tag. +pub(crate) fn next_tag(tag: u32) -> u32 { + if tag >= UNKNOWN_SOURCE - 1 { UNKNOWN_SOURCE } else { tag + 1 } +} + /// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run /// it cannot pause. pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000; @@ -148,6 +155,12 @@ impl From for RunError { pub struct Realm { interp: Interp, unbroken_fuel: u64, + /// The source tag of the script the last [`Realm::run`] or [`Realm::start`] compiled. Each + /// script gets a new one, and the sources an evaluator gives during its run get the ones after + /// it, so code that an earlier script defined keeps a tag of its own. [`UNKNOWN_SOURCE`] + /// before the first script, for a script the realm did not compile, and once the tags are used + /// up. + script_tag: u32, } impl Default for Realm { @@ -165,7 +178,7 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE } } /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default @@ -221,11 +234,13 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); } interp.fuel = interp.limits.fuel; + interp.flattened_fuel.set(0); interp.source_units = 0; interp.throw_site = None; interp.last_thrown = Value::Undefined; @@ -235,15 +250,18 @@ impl Realm { interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); + interp.finally_sites.clear(); interp.error_mark = None; let strict = interp.options.strict; - interp.source_tag = 0; + interp.evaluated = next_tag(interp.evaluated); + self.script_tag = interp.evaluated; + interp.source_tag = self.script_tag; let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); interp.source_tag = UNKNOWN_SOURCE; match code { Ok(code) => Ok(code), Err(CompileError::Syntax(e)) => { - interp.error_tag = 0; + interp.error_tag = self.script_tag; Err(e.into()) } Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), @@ -258,6 +276,7 @@ impl Realm { let (line, column) = site.map_or((0, 0), |(code, pc)| code.line_column(pc)); interp.error_mark = interp.thrown_mark.take().filter(|_| matches!(result, Err(Abrupt::Throw(_) | Abrupt::Limit(LimitKind::Host)))); interp.finally_marks.clear(); + interp.finally_sites.clear(); interp.stack.clear(); interp.frames.clear(); interp.temp_roots.clear(); @@ -325,6 +344,15 @@ impl Realm { !self.interp.frames.is_empty() } + /// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's + /// result, as an interrupt would: its stacks are emptied, so the realm can start another run. + /// The globals the run set stay. + pub fn end(&mut self) { + if self.is_running() || self.interp.waiting { + let _ = self.outcome(Err(Abrupt::Limit(LimitKind::Interrupted))); + } + } + /// The flag a host function sets to end the current slice at the next point it can pause. pub fn pause_flag(&self) -> std::rc::Rc> { self.interp.pause.clone() @@ -367,13 +395,39 @@ impl Realm { self.interp.interrupt = interrupt.0.clone(); } - /// Which source the last error's `line` and `column` are in: 0 for the script given to + /// Which source the last error's `line` and `column` are in: 0 for the script last given to /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a - /// [`crate::HostItem::Evaluator`] gave in this realm, and [`UNKNOWN_SOURCE`] otherwise. + /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which + /// includes code from an earlier script and from the sources given during its run. pub fn error_source(&self) -> u32 { + match self.interp.error_tag { + UNKNOWN_SOURCE => UNKNOWN_SOURCE, + tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), + } + } + + /// The source tag of the code the last error's `line` and `column` are in, which stays the same + /// from run to run: each script given to [`Realm::run`] or [`Realm::start`] and each source a + /// [`crate::HostItem::Evaluator`] gives gets the next tag, so a function an earlier script + /// defined has its script's tag. [`UNKNOWN_SOURCE`] for code that `eval` or `Function` + /// compiled, an error with no place, and sources given once the tags are used up. + pub fn error_tag(&self) -> u32 { self.interp.error_tag } + /// The source tag ([`Realm::error_tag`]) of the script the last [`Realm::run`] or + /// [`Realm::start`] compiled; the `n`th source an evaluator gave during that run has this tag + /// plus `n`. [`UNKNOWN_SOURCE`] when that call compiled nothing. + pub fn script_tag(&self) -> u32 { + self.script_tag + } + + /// Tests: makes `tag` the last source tag given out. + #[cfg(test)] + pub(crate) fn set_last_tag(&mut self, tag: u32) { + self.interp.evaluated = tag; + } + /// The mark of the host error ([`crate::HostError::Marked`]) the last run ended with, when no /// `catch` clause took that error's exception on its way out; `None` otherwise. pub fn error_mark(&self) -> Option { @@ -400,6 +454,34 @@ impl Realm { } } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions + /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, + /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, + /// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system` + /// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and + /// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its + /// encoding and its line feed in properties that are not enumerable. + pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match crate::file_classes::install(&mut self.interp, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has + /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its + /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught + /// exception and `$.error` are dropped first, as [`Realm::start`] drops them, so memory that only + /// they held is free for the reset. + pub fn reset_folder_current(&mut self) -> Result<(), RunError> { + self.interp.last_thrown = Value::Undefined; + self.interp.last_error = Value::Null; + match crate::file_classes::reset_current(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the script extensions: the global `localize(object, ...values)`, which gives a /// localization object's text for the locale of [`Realm::localization`], the global /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, diff --git a/crates/js/src/string_builtins.rs b/crates/js/src/string_builtins.rs index b3758bdf54..eed08f96bd 100644 --- a/crates/js/src/string_builtins.rs +++ b/crates/js/src/string_builtins.rs @@ -98,7 +98,7 @@ fn check_string_room(interp: &mut Interp, len: usize) -> JsResult<()> { /// Pushes `item` onto `list`, first holding the bytes of the list's new capacity when it must /// grow. -fn push_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, item: T) -> JsResult<()> { +pub(crate) fn push_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, item: T) -> JsResult<()> { if list.len() == list.capacity() { let more = list.capacity().max(4); held.add(interp, more.saturating_mul(size_of::()))?; @@ -109,10 +109,11 @@ fn push_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, it } /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that copy's -/// bytes are reserved and added to the heap, and its units charged as fuel, first. +/// bytes are reserved and added to the heap, and its units charged as fuel, first. The rope stays +/// rooted while the copy is reserved, so what it holds is still counted. pub(crate) fn flat_charged(interp: &mut Interp, s: &Str) -> JsResult> { if s.is_rope() { - reserve_units(interp, s.len())?; + interp.rooted(&[Value::String(s.clone())], |interp| reserve_units(interp, s.len()))?; } Ok(s.flat()) } @@ -179,7 +180,7 @@ fn clamp(n: f64, len: usize) -> usize { /// The first index at `from` or after where `needle` occurs in `hay`. Every position tried takes /// fuel. -fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize) -> JsResult> { +pub(crate) fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize) -> JsResult> { if needle.len() > hay.len() { return Ok(None); } diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index 8c24b5d0bb..d2d4537439 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -424,6 +424,27 @@ fn identifiers_take_the_other_id_start_and_continue_characters() { } } +#[test] +fn identifiers_take_the_characters_unicode_17_assigned() { + // U+088F (a letter, Lo) starts a name; U+1ACF (a combining mark, Mn) may follow the first + // character but cannot start a name. Unicode 17.0 assigned both. + for (src, name) in [ + ("var \u{88F} = 1;", "\u{88F}"), + ("var \\u088F = 1;", "\u{88F}"), + (r"var \u{88F} = 1;", "\u{88F}"), + ("var _\u{1ACF} = 1;", "_\u{1ACF}"), + ("var _\\u1ACF = 1;", "_\u{1ACF}"), + (r"var _\u{1ACF} = 1;", "_\u{1ACF}"), + ] { + let p = ok(src); + let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") }; + assert_eq!(decls[0].name.name, name, "{src:?}"); + } + assert!(err("var \u{1ACF} = 1;").message.contains("unexpected character")); + assert!(err("var \\u1ACF = 1;").message.contains("identifier escape")); + assert!(err(r"var \u{1ACF} = 1;").message.contains("identifier escape")); +} + #[test] fn identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes() { // U+2E2F is a letter by category but Pattern_Syntax; U+2010, U+00B6 and U+2190 are @@ -480,12 +501,12 @@ fn no_pattern_syntax_or_white_space_character_is_an_identifier_character() { } #[test] -fn identifier_characters_are_unicode_16_id_start_and_id_continue() { +fn identifier_characters_are_unicode_17_id_start_and_id_continue() { use crate::chars::{is_id_part, is_id_start}; - use unicode_general_category::{GeneralCategory as G, get_general_category}; + use unicode_properties::{GeneralCategory as G, UnicodeGeneralCategory}; // Unicode Standard Annex #31: ID_Start is the categories Lu, Ll, Lt, Lm, Lo and Nl plus // Other_ID_Start; ID_Continue adds Mn, Mc, Nd, Pc and Other_ID_Continue; both leave out - // Pattern_Syntax and Pattern_White_Space. Other_ID_Start and Other_ID_Continue as PropList 16.0 + // Pattern_Syntax and Pattern_White_Space. Other_ID_Start and Other_ID_Continue as PropList 17.0 // lists them. let other_start = [0x1885..=0x1886, 0x2118..=0x2118, 0x212E..=0x212E, 0x309B..=0x309C]; let other_continue = [0xB7..=0xB7, 0x387..=0x387, 0x1369..=0x1371, 0x19DA..=0x19DA, 0x200C..=0x200D, 0x30FB..=0x30FB, 0xFF65..=0xFF65]; @@ -498,7 +519,7 @@ fn identifier_characters_are_unicode_16_id_start_and_id_continue() { let (mut id_starts, mut id_continues) = (0, 0); for c in (0..=0x10_FFFF_u32).filter(|c| !(0xD800..=0xDFFF).contains(c)) { let Some(ch) = char::from_u32(c) else { panic!("U+{c:04X}") }; - let g = get_general_category(ch); + let g = ch.general_category(); let letter = matches!(g, G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber); let id_start = (letter || other_start.iter().any(|r| r.contains(&c))) && !excluded[c as usize]; let continuing = matches!(g, G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation); @@ -509,8 +530,8 @@ fn identifier_characters_are_unicode_16_id_start_and_id_continue() { assert_eq!(is_id_start(c), id_start || c == 0x24 || c == 0x5F, "start U+{c:04X}"); assert_eq!(is_id_part(c), id_continue || c == 0x24, "part U+{c:04X}"); } - // The totals of ID_Start and ID_Continue in DerivedCoreProperties 16.0. - assert_eq!((id_starts, id_continues), (141_269, 144_541)); + // The totals of ID_Start and ID_Continue in DerivedCoreProperties 17.0. + assert_eq!((id_starts, id_continues), (145_916, 149_240)); } #[test] diff --git a/crates/js/src/text_tests.rs b/crates/js/src/text_tests.rs index c873bdaf59..01fc613cc3 100644 --- a/crates/js/src/text_tests.rs +++ b/crates/js/src/text_tests.rs @@ -309,6 +309,131 @@ fn flattening_a_rope_counts_against_the_heap() { } } +#[test] +fn operators_and_builtins_count_a_flattened_rope_against_the_heap() { + // Three ropes of about 524,288 units, each 1 MiB once flat, with a 3 MiB heap. + let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z';"; + let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() }; + let not_stopped: Vec<_> = + ["X < 'a'", "X == 1", "+X", "X[0]", "({})[{ toString: function () { return X; } }]", "JSON.stringify(0, null, X)", "[1].join(X)"] + .into_iter() + .filter(|read| { + let src = format!("{build} {}; {}; {}; 0", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u")); + let result = Realm::with_options(Options::default(), limits.clone()).run(&src); + !matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)) + }) + .collect(); + assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}"); +} + +#[test] +fn a_flattened_temporary_stays_counted_while_the_next_copy_is_made() { + // Ropes of 262,145 units, each about half the heap once flat: one fits, two don't. Each is + // made by a function, so nothing but the native code holds it while it is flattened. + let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; }"; + let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() }; + let run = |read: &str| Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0")); + assert!(run("f('a')[0]").is_ok(), "one flattened copy fits"); + let not_stopped: Vec<_> = [ + "({ valueOf: function () { return f('a'); } }) < ({ valueOf: function () { return f('b'); } })", + "JSON.stringify({ toJSON: function () { return f('a'); } })", + "[1, 2].join({ toString: function () { return f('a'); } })", + "[{ toString: function () { return f('a'); } }].join('')", + ] + .into_iter() + .filter(|read| !matches!(run(read), Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap))) + .collect(); + assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}"); +} + +#[test] +fn a_converted_rope_counts_what_it_holds_while_its_copy_is_made() { + // `mk` returns a rope whose left half is a flat string of about half the heap, held by + // nothing else. Its flattened copy is the other half, so the two don't fit together. + let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \ + function mk() { var a = f('a'); a[0]; return a + 'b'; }"; + let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() }; + let not_stopped: Vec<_> = [ + "+({ valueOf: mk })", + "({})[{ toString: mk }]", + "({ valueOf: mk }) == 1", + "++({ get x() { return mk(); } }).x", + "JSON.stringify(0, null, (function () { var o = new String(''); o.toString = mk; return o; })())", + ] + .into_iter() + .filter(|read| { + let result = Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0")); + !matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)) + }) + .collect(); + assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}"); +} + +#[test] +fn a_string_object_counts_its_flattened_rope_against_the_heap() { + // The same three ropes, each wrapped in a String object and read by index. + let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z'; \ + String.prototype.first = function () { return this[0]; };"; + let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() }; + // Wrapping alone reads no units, so it makes no copy. + let lengths = + Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} Object(s).length + new String(t).length + Object(u).length")); + assert_eq!(lengths, Ok(JsValue::Number(1_572_866.0))); + // Two copies fit. The third read finds no room for its copy and reads the unit along the + // rope, so the live heap stays within the limit. + for (read, expected) in [ + ("Object(X)[0]", "xxx"), + ("new String(X)[0]", "xxx"), + ("0 in Object(X)", "truetruetrue"), + ("Object(X).hasOwnProperty(0)", "truetruetrue"), + ("X.first()", "xxx"), + ("Object(X)[524288]", "undefinedyz"), + ] { + let src = format!("{build} '' + ({}) + ({}) + ({})", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u")); + let mut realm = Realm::with_options(Options::default(), limits.clone()); + assert_eq!(realm.run(&src), Ok(JsValue::String(expected.into())), "{read}"); + let interp = realm.interp(); + interp.collect_garbage(); + assert!(interp.heap.bytes <= limits.heap_bytes, "{read}: {} bytes live", interp.heap.bytes); + } + let wrapped = + Realm::with_options(Options::default(), Limits::default()).run(&format!("{build} Object(t)[524288] + new String(u)[524288] + t.first()")); + assert_eq!(wrapped, Ok(JsValue::String("yzx".into()))); +} + +#[test] +fn a_string_object_takes_fuel_for_the_rope_it_flattens() { + let limits = Limits { fuel: 40_000, ..Limits::default() }; + let build = "var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object(s).length"; + assert!(Realm::with_options(Options::default(), limits.clone()).run(build).is_ok()); + for read in ["Object(s)[0]", "0 in new String(s)"] { + let e = fail_with(Realm::with_options(Options::default(), limits.clone()), &format!("{build}; {read}")); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{read}: {e:?}"); + } + // A run that ends with an error right after the read leaves the next run its whole fuel. + let mut realm = Realm::with_options(Options::default(), Limits { fuel: 100_000, ..Limits::default() }); + let defined = realm.run("var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object.defineProperty(new String(s), 0, { value: 'a' })"); + assert!(matches!(defined, Err(ref e) if e.kind == RunErrorKind::Thrown), "{defined:?}"); + assert!(realm.run("for (var j = 0; j < 5000; j++) {} j").is_ok()); +} + +#[test] +fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() { + // `g` leaves a garbage string, so the heap is close to its limit when the rope receiver of a + // non-strict function is boxed. The callee and the argument object are off the stack by + // then, and must survive anything boxing the receiver does. + let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \ + function mk() { var a = f('a'); a[0]; return a + 'b'; } 0"; + let mut realm = Realm::with_options(Options::default(), Limits::default()); + assert_eq!(realm.run(build), Ok(JsValue::Number(0.0))); + let interp = realm.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + 2 * crate::heap::string_bytes(131_073) + (64 << 10); + interp.reset_gc_threshold(); + let src = "(function () { var g = f('g'); g[0]; })(); (function (o) { return o.x; }).call(mk(), { x: 1 })"; + assert_eq!(realm.run(src), Ok(JsValue::Number(1.0))); +} + #[test] fn compiling_a_pattern_counts_against_the_heap() { let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length"; diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index e164001ad9..a0fbcd4a53 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -163,6 +163,34 @@ impl Str { flat } + /// The code unit at `i` read along the rope without flattening it, visiting at most + /// `max_nodes` nodes: `None` when that is not enough, otherwise the unit (when `i` is in + /// range) and the number of nodes visited. + pub(crate) fn unit_at(&self, mut i: usize, max_nodes: u64) -> Option<(Option, u64)> { + let mut node = self.clone(); + let mut visited = 0u64; + loop { + visited += 1; + if visited > max_nodes { + return None; + } + let next = match &*node.0.borrow() { + Node::Flat(f) => return Some((f.get(i).copied(), visited)), + Node::Concat { left, right, .. } => { + let left_len = left.len(); + if i < left_len { + left.clone() + } else { + i -= left_len; + right.clone() + } + } + Node::Taken => return Some((None, visited)), + }; + node = next; + } + } + pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs index 9dc6d71f85..8d83162a50 100644 --- a/crates/js/src/xml.rs +++ b/crates/js/src/xml.rs @@ -175,6 +175,52 @@ fn is_attribute_run(units: &[u16]) -> bool { true } +/// Reads one pseudo-attribute of an XML declaration at `at`: white space, `name`, `=` with +/// optional white space around it, and a quoted value. Returns the offset after the closing +/// quote and the value. +fn decl_attribute<'a>(body: &'a [u16], at: usize, name: &str) -> Option<(usize, &'a [u16])> { + let start = skip_xml_space(body, at); + let name = parser_units(name); + if start == at || !body.get(start..)?.starts_with(&name) { + return None; + } + let eq = skip_xml_space(body, start + name.len()); + if body.get(eq) != Some(&EQ) { + return None; + } + let open = skip_xml_space(body, eq + 1); + let quote = body.get(open).copied().filter(|&q| q == DQUOTE || q == SQUOTE)?; + let len = body.get(open + 1..)?.iter().position(|&c| c == quote)?; + Some((open + len + 2, body.get(open + 1..open + 1 + len)?)) +} + +/// Whether `body`, the text between ``, is an XML declaration's version, optional +/// encoding, optional standalone flag and optional trailing white space (XML 1.0 productions 23 +/// to 26, 32, 80 and 81). +fn is_xml_decl_body(body: &[u16]) -> bool { + let is_digit = |c: &u16| (u16::from(b'0')..=u16::from(b'9')).contains(c); + let is_letter = |c: &u16| (u16::from(b'A')..=u16::from(b'Z')).contains(c) || (u16::from(b'a')..=u16::from(b'z')).contains(c); + let Some((mut at, version)) = decl_attribute(body, 0, "version") else { return false }; + let digits = version.strip_prefix(parser_units("1.").as_slice()).unwrap_or_default(); + if digits.is_empty() || !digits.iter().all(is_digit) { + return false; + } + if let Some((next, encoding)) = decl_attribute(body, at, "encoding") { + let Some((first, rest)) = encoding.split_first() else { return false }; + if !is_letter(first) || !rest.iter().all(|c| is_letter(c) || is_digit(c) || matches!(*c, 0x2D | 0x2E | 0x5F)) { + return false; + } + at = next; + } + if let Some((next, standalone)) = decl_attribute(body, at, "standalone") { + if standalone != parser_units("yes").as_slice() && standalone != parser_units("no").as_slice() { + return false; + } + at = next; + } + skip_xml_space(body, at) == body.len() +} + /// An XML name without a prefix (ECMA-357 section 13.1.2.1). pub(crate) fn is_ncname(units: &[u16]) -> bool { let Some((&first, rest)) = units.split_first() else { return false }; @@ -2305,8 +2351,30 @@ impl Interp { src.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|i| from + i) } + /// Takes fuel for `units` code units that the parser scanned, on top of the fuel of the step + /// that scanned them, so a short run costs nothing extra. + fn xml_scan_fuel(&mut self, units: usize) -> JsResult<()> { + self.xml_take_fuel(units / UNITS_PER_FUEL) + } + + /// The offset after the white space at `src[pos]`, taking fuel for its length. + fn skip_space(&mut self, src: &[u16], pos: usize) -> JsResult { + let end = skip_xml_space(src, pos); + self.xml_scan_fuel(end - pos)?; + Ok(end) + } + + /// The offset after the XML name at `src[pos]`, taking fuel for the units it scanned. fn read_name(&mut self, src: &[u16], pos: usize) -> JsResult { - scan_name(src, pos).ok_or_else(|| self.syntax("invalid XML name")) + if let Some(end) = scan_name(src, pos) { + self.xml_scan_fuel(end - pos)?; + return Ok(end); + } + if src.get(pos).copied().is_some_and(is_name_start) { + let scanned = src.get(pos..).unwrap_or_default().iter().skip(1).take_while(|&&c| is_name_part(c)).count(); + self.xml_scan_fuel(scanned + 1)?; + } + Err(self.syntax("invalid XML name")) } fn check_units(&mut self, src: &[u16], from: usize, to: usize) -> JsResult<()> { @@ -2390,9 +2458,7 @@ impl Interp { let mut raw_attrs: Vec<(usize, usize, Vec)> = Vec::new(); let closes = loop { let before = at; - while src.get(at).copied().is_some_and(is_xml_space) { - at += 1; - } + at = self.skip_space(src, at)?; match src.get(at).copied() { None => return Err(self.syntax("unterminated XML tag")), Some(SLASH) if src.get(at + 1) == Some(>) => { @@ -2407,26 +2473,22 @@ impl Interp { Some(_) => { self.use_fuel()?; let end = self.read_name(src, at)?; - let mut p = end; - while src.get(p).copied().is_some_and(is_xml_space) { - p += 1; - } + let p = self.skip_space(src, end)?; if src.get(p) != Some(&EQ) { return Err(self.syntax("expected '=' after an attribute name")); } - p += 1; - while src.get(p).copied().is_some_and(is_xml_space) { - p += 1; - } + let p = self.skip_space(src, p + 1)?; let quote = match src.get(p).copied() { Some(q @ (DQUOTE | SQUOTE)) => q, _ => return Err(self.syntax("expected a quoted attribute value")), }; let value_start = p + 1; let Some(value_end) = Self::find_from(src, value_start, &[quote]) else { + self.xml_text_fuel(src.len().saturating_sub(value_start))?; return Err(self.syntax("unterminated attribute value")); }; if src.get(value_start..value_end).is_some_and(|v| v.contains(<)) { + self.xml_text_fuel(value_end - value_start)?; return Err(self.syntax("'<' cannot appear in an attribute value")); } let mut value = Vec::new(); @@ -2528,10 +2590,7 @@ impl Interp { fn parse_close_tag(&mut self, src: &[u16], pos: usize, open: &mut Vec, names: &mut Vec<(usize, usize)>) -> JsResult { let name_start = pos + 2; let name_end = self.read_name(src, name_start)?; - let mut at = name_end; - while src.get(at).copied().is_some_and(is_xml_space) { - at += 1; - } + let at = self.skip_space(src, name_end)?; if src.get(at) != Some(>) { return Err(self.syntax("expected '>' at the end of a closing tag")); } @@ -2552,14 +2611,17 @@ impl Interp { held.add(self, string_bytes(source.len()).saturating_mul(2))?; let settings = self.xml_settings()?; let mut src = source; - let mut offset_start = 0; - while src.get(offset_start).copied().is_some_and(is_xml_space) { - offset_start += 1; - } + let offset_start = skip_xml_space(src, 0); if src.get(offset_start..).is_some_and(|r| r.starts_with(&parser_units("")) else { + self.xml_text_fuel(src.len())?; return Err(self.syntax("unterminated XML declaration")); }; + self.xml_text_fuel(end + 2)?; + self.check_units(src, offset_start, end)?; + if !is_xml_decl_body(src.get(offset_start + 5..end).unwrap_or_default()) { + return Err(self.syntax("invalid XML declaration")); + } src = src.get(end + 2..).unwrap_or_default(); } let mut pos = 0; @@ -2573,6 +2635,7 @@ impl Interp { let end = Self::find_from(src, pos, &[LT]).unwrap_or(src.len()); let section_end = parser_units("]]>"); if src.get(pos..end).is_some_and(|run| run.windows(3).any(|w| w == section_end)) { + self.xml_text_fuel(end - pos)?; return Err(self.syntax("']]>' cannot appear in XML text")); } self.decode_into(src, pos, end, &mut text, false)?; @@ -2582,6 +2645,7 @@ impl Interp { let rest = src.get(pos..).unwrap_or_default(); if rest.starts_with(&parser_units("")) else { + self.xml_text_fuel(src.len() - pos)?; return Err(self.syntax("unterminated CDATA section")); }; self.xml_text_fuel(end - pos)?; @@ -2593,12 +2657,13 @@ impl Interp { self.flush_text(&mut text, settings.ignore_whitespace, &open, &mut roots)?; if rest.starts_with(&parser_units("; (x.@p + x.comments()).xpath('.').length() === 0"); + truth("new XMLList().xpath('a').length() === 0 && new XMLList().xpath('z:a').length() === 0"); + truth("var l = <>; l.xpath('p:b').length() === 2"); + assert_eq!(thrown_name("var l = <>; l.xpath('p:b')"), "TypeError"); +} + +#[test] +fn xpath_expressions_of_any_depth_use_no_native_stack() { + let deep = format!("{}1{}", "(".repeat(100_000), ")".repeat(100_000)); + assert_eq!(thrown_name(&format!("().xpath('{deep}')")), "SyntaxError"); + let predicates = format!("{}{}", "a[".repeat(100_000), "]".repeat(100_000)); + assert_eq!(thrown_name(&format!("().xpath('{predicates}')")), "SyntaxError"); + let sum = format!("1{}", " + 1".repeat(100_000)); + truth(&format!("().xpath('self::*[{sum} = 100001]').length() === 1")); + let negated = format!("{}1", "-".repeat(100_001)); + truth(&format!("().xpath('self::*[{negated} = -1]').length() === 1")); + let union = format!("a{}", " | a".repeat(50_000)); + truth(&format!("().xpath('{union}').length() === 1")); + let mut shallow = Realm::with_options(Options { max_depth: 8, ..e4x() }, Limits::default()); + let seven = format!("{}1{}", "(".repeat(6), ")".repeat(6)); + assert_eq!(shallow.run(&format!("().xpath('self::*[{seven}]').length()")), Ok(JsValue::Number(1.0))); + let eight = format!("{}1{}", "(".repeat(8), ")".repeat(8)); + assert_eq!(shallow.run(&format!("try {{ ().xpath('{eight}') }} catch (e) {{ e.message }}")), Ok(JsValue::String("nesting too deep".into()))); +} + +#[test] +fn xpath_stops_at_the_fuel_and_heap_limits_leaving_the_tree() { + let setup = "var x = ; for (var i = 0; i < 6; i++) x.appendChild({i});"; + let check = "x.a.length() === 6 && x.a[5].b == '5' && x.*.length() === 6"; + assert!(fuel_stops(setup, "x.xpath('//b[. > 2]/preceding::*')", check) > 0); + assert!(heap_stops(setup, "x.xpath((SPARE, '//b[contains(concat(., ., .), \"3\")] | //a'))", check) > 0); + let mut r = realm(); + r.run("var x = ; for (var i = 0; i < 500; i++) x.appendChild();").unwrap(); + let interrupt = r.interrupt(); + r.define_function("stop", move |_| { + interrupt.set(); + Ok(JsValue::Undefined) + }); + assert_eq!(r.run("stop(); x.xpath('//a/following::a')").map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Interrupted))); +} + +#[test] +fn xpath_walks_of_deep_trees_and_long_lists_count_against_the_heap_limit() { + let deep = "var s = ''; for (var i = 0; i < 5000; i++) s += ''; s += ''; for (var i = 0; i < 5000; i++) s += ''; var x = new XML(s);"; + for (action, room) in [ + ("x.xpath('descendant::c').length()", JsValue::Number(0.0)), + ("x.xpath('self::*[string() = \"q\"]').length()", JsValue::Number(0.0)), + ("x.xpath('descendant::b | self::a').length()", JsValue::Number(2.0)), + ] { + for (spare, want) in [(20_000, Err(RunErrorKind::Limit(LimitKind::Heap))), (50_000_000, Ok(room.clone()))] { + let mut r = Realm::with_options(Options { max_depth: 1_000_000, ..e4x() }, Limits::default()); + let interp = r.interp(); + let global = interp.global; + assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok()); + r.run(deep).unwrap(); + assert_eq!(r.run(&format!("squeeze({spare}); {action}")).map_err(|e| e.kind), want, "{action} {spare}"); + } + } + let long = "var s = ''; for (var i = 0; i < 20000; i++) s += ''; var l = new XML(s + '').a;"; + assert_eq!(after_setup(long, "squeeze(50000); l.xpath('self::c').length()"), Err(RunErrorKind::Limit(LimitKind::Heap))); + assert_eq!(after_setup(long, "squeeze(50000000); l.xpath('self::c').length()"), Ok(JsValue::Number(0.0))); +} + +#[test] +fn xpath_reading_a_long_string_takes_fuel_for_its_length() { + let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; var x = ; for (var i = 0; i < 200; i++) x.appendChild(y);"; + for expr in ["a[string-length($s) = 1]", "a[starts-with($s, $s) = false()]", "a[$s = concat('', 'x')]", "a[number($s) = 1]", "a[. = $s]"] { + let mut r = realm(); + r.run(setup).unwrap(); + let src = format!("x.xpath({expr:?}, {{ s: s }}).length()"); + assert_eq!(r.run(&src), Ok(JsValue::Number(0.0)), "{expr}"); + r.set_limits(Limits { fuel: 2_000_000, ..Limits::default() }); + assert_eq!(r.run(&src).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)), "{expr}"); + } +} + +#[test] +fn xpath_string_functions_hold_the_bytes_they_build() { + let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; var d = '1'; for (var i = 0; i < 20; i++) d += d; var o = { s: s, d: d };"; + for (expr, spare) in [("translate('a', 'b', $s) = 'a'", 1_000_000), ("number($d) > 1", 500_000), ("substring($s, 1) != 'z'", 4_000_000)] { + let action = |spare: u32| format!("squeeze({spare}); ().xpath(\"self::*[{expr}]\", o).length()"); + assert_eq!(after_setup(setup, &action(spare)), Err(RunErrorKind::Limit(LimitKind::Heap)), "{expr}"); + assert_eq!(after_setup(setup, &action(100_000_000)), Ok(JsValue::Number(1.0)), "{expr}"); + } +} + +#[test] +fn xpath_string_variables_hold_the_bytes_of_their_flat_copy() { + // The setup ends with `0` so that its completion value does not flatten `s`. + let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; var o = { s: s }; 0;"; + let action = |spare: u32| format!("squeeze({spare}); ().xpath('self::*[$s]', o).length()"); + assert_eq!(after_setup(setup, &action(1_000_000)), Err(RunErrorKind::Limit(LimitKind::Heap))); + assert_eq!(after_setup(setup, &action(100_000_000)), Ok(JsValue::Number(1.0))); +} + +#[test] +fn xpath_substring_searches_take_fuel_for_every_position_tried() { + let setup = "var h = 'a'; for (var i = 0; i < 16; i++) h += h; var n = h.substring(0, 4095) + 'b'; var o = { h: h, n: n };"; + for expr in ["contains($h, $n)", "substring-before($h, $n) = ''", "substring-after($h, $n) = ''"] { + let mut r = realm(); + r.run(setup).unwrap(); + let src = format!("().xpath(\"self::*[{expr}]\", o).length()"); + let want = if expr.starts_with("contains") { 0.0 } else { 1.0 }; + assert_eq!(r.run(&src), Ok(JsValue::Number(want)), "{expr}"); + r.set_limits(Limits { fuel: 5_000_000, ..Limits::default() }); + assert_eq!(r.run(&src).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)), "{expr}"); + } +} + +#[test] +fn xpath_lang_takes_fuel_for_every_attribute_it_reads() { + let setup = "var s = '');"; + let mut r = realm(); + r.run(setup).unwrap(); + let src = "x.xpath('a[lang(\"en\")]').length()"; + assert_eq!(r.run(src), Ok(JsValue::Number(0.0))); + r.set_limits(Limits { fuel: 2_000_000, ..Limits::default() }); + assert_eq!(r.run(src).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel))); +} + +#[test] +fn xpath_on_a_large_tree_ends_within_the_default_limits() { + let setup = "var x = ; for (var i = 0; i < 3000; i++) x.appendChild();"; + truth(&format!("{setup} x.xpath('//a[@n = 2999]/b').length() === 1 && x.xpath('//b/..').length() === 3000")); + let mut r = realm(); + r.run("var x = ; for (var i = 0; i < 2000; i++) x.appendChild();").unwrap(); + r.set_limits(Limits { fuel: 2_000_000, ..Limits::default() }); + assert_eq!(r.run("x.xpath('//a/following::a')").map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel))); +} + +const XPATH_PIECES: &[&str] = &[ + "/", + "//", + "a", + "b", + "*", + "@", + "@*", + ".", + "..", + "[", + "]", + "(", + ")", + "1", + "'x'", + "$v", + "|", + "+", + "-", + "=", + "!=", + "<", + ">=", + " and ", + " or ", + " div ", + " mod ", + "child::", + "following::", + "preceding::", + "ancestor::", + "namespace::", + "node()", + "text()", + "count(", + "last()", + "position()", + "concat(", + "substring(", + ",", + "p:", + "p:*", + "xml:lang", + "::", + ":", + "'", + " ", +]; + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn random_xpath_expressions_select_nodes_or_throw(parts in proptest::collection::vec(0..XPATH_PIECES.len(), 0..30)) { + let expr: String = parts.iter().map(|&i| XPATH_PIECES[i]).collect(); + let quoted = format!("{expr:?}"); + let src = format!("var x = 23t; typeof XML.prototype.xpath === 'function' && x.a[0].xpath({quoted}, {{ v: 1 }}).length() >= 0"); + let mut r = limited(Limits { fuel: 200_000, heap_bytes: 4 << 20, frames: 200, reentry: 8 }); + match r.run(&src) { + Ok(v) => prop_assert_eq!(v, JsValue::Bool(true), "{}", expr), + Err(e) => prop_assert!(matches!(e.kind, RunErrorKind::Thrown | RunErrorKind::Limit(_)), "{expr:?}: {e:?}"), + } + } +} + // ---- generated input ---- const PIECES: &[&str] = &[ diff --git a/crates/js/src/xpath.rs b/crates/js/src/xpath.rs new file mode 100644 index 0000000000..30707e4de0 --- /dev/null +++ b/crates/js/src/xpath.rs @@ -0,0 +1,2377 @@ +//! `xpath` on XML and XMLList values: XPath 1.0 expressions +//! () evaluated on E4X trees. +//! +//! An expression is read into tokens, then into a syntax tree whose nodes live in one arena, and is +//! evaluated with an explicit task stack, so neither step uses native recursion. Brackets nest at +//! most [`crate::Options::max_depth`] deep. Every token, task and visited node takes fuel, and the +//! token, tree, node-set and string buffers are held against the heap limit while they live. +//! +//! `/` is a root node above the topmost node of the context node's tree. A node-set result is +//! returned as an XMLList of the selected nodes themselves, in document order with attributes +//! before children. The root node and namespace nodes can be selected and tested inside an +//! expression, but a result that holds one throws a `TypeError`, since E4X has no such value. The +//! tree keeps no DTD, so `id()` selects nothing. Prefixes in the expression are read from the +//! namespaces in scope on the context element, and `xml` is always bound. + +use std::collections::{HashMap, HashSet}; +use std::mem::replace; +use std::rc::Rc; + +use crate::builtins::arg; +use crate::error::TOO_DEEP; +use crate::heap::{Key, ObjId, XmlKind, XmlName, XmlNs, key}; +use crate::interp::{Abrupt, ErrorType, HeldBytes, Interp, JsResult}; +use crate::regexp_vm::use_fuel_n; +use crate::string_builtins::{self, charge_units, flat_charged, push_held}; +use crate::value::Value; +use crate::xml::{Xv, is_name_part, is_name_start, is_xml_space, valid_xml_units}; +use crate::xml_builtins::scope_of; + +const XML_URI: &str = "http://www.w3.org/XML/1998/namespace"; +const COLON: u16 = b':' as u16; +const STAR: u16 = b'*' as u16; +const SLASH: u16 = b'/' as u16; +const DOT: u16 = b'.' as u16; +const EQUALS: u16 = b'=' as u16; +const DASH: u16 = b'-' as u16; +/// The estimated bytes of a syntax tree node's own lists, beyond its slot in the arena. +const EXPR_BYTES: usize = 64; +/// The estimated bytes of one entry of a hash map or set the evaluator keeps. +const ENTRY_BYTES: usize = 64; + +fn empty() -> Key { + Rc::from(Vec::new()) +} + +fn syntax(interp: &mut Interp, message: &str) -> Abrupt { + interp.throw(ErrorType::Syntax, message) +} + +fn internal() -> Abrupt { + Abrupt::Internal("XPath evaluation state".into()) +} + +fn is_digit(c: u16) -> bool { + (0x30..=0x39).contains(&c) +} + +// ---- tokens ---- + +#[derive(Clone, Copy, PartialEq)] +enum Punct { + LParen, + RParen, + LBracket, + RBracket, + Dot, + DotDot, + At, + Comma, + ColonColon, + Slash, + SlashSlash, + Pipe, + Plus, + Minus, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, +} + +/// A token as the lexer reads it, before names and `*` are told apart by their position. +enum Raw { + Punct(Punct), + Star, + Name(Option, Key), + PrefixStar(Key), + Literal(Key), + Number(f64), + Var(Key), +} + +#[derive(Clone, Copy, PartialEq)] +enum Axis { + Ancestor, + AncestorOrSelf, + Attribute, + Child, + Descendant, + DescendantOrSelf, + Following, + FollowingSibling, + Namespace, + Parent, + Preceding, + PrecedingSibling, + Itself, +} + +const AXES: [(&str, Axis); 13] = [ + ("ancestor", Axis::Ancestor), + ("ancestor-or-self", Axis::AncestorOrSelf), + ("attribute", Axis::Attribute), + ("child", Axis::Child), + ("descendant", Axis::Descendant), + ("descendant-or-self", Axis::DescendantOrSelf), + ("following", Axis::Following), + ("following-sibling", Axis::FollowingSibling), + ("namespace", Axis::Namespace), + ("parent", Axis::Parent), + ("preceding", Axis::Preceding), + ("preceding-sibling", Axis::PrecedingSibling), + ("self", Axis::Itself), +]; + +impl Axis { + /// Whether the axis lists its nodes in reverse document order. + fn reverse(self) -> bool { + matches!(self, Axis::Ancestor | Axis::AncestorOrSelf | Axis::Preceding | Axis::PrecedingSibling) + } +} + +/// A node test. A prefix is resolved when the expression runs. +#[derive(Clone)] +enum Test { + Any, + Prefix(Key), + Name(Option, Key), + Node, + Text, + Comment, + Pi(Option), +} + +#[derive(Clone, Copy, PartialEq)] +enum Bin { + Or, + And, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + Add, + Sub, + Mul, + Div, + Mod, + Union, +} + +impl Bin { + fn precedence(self) -> u8 { + match self { + Bin::Or => 1, + Bin::And => 2, + Bin::Eq | Bin::Ne => 3, + Bin::Lt | Bin::Le | Bin::Gt | Bin::Ge => 4, + Bin::Add | Bin::Sub => 5, + Bin::Mul | Bin::Div | Bin::Mod => 6, + Bin::Union => 8, + } + } +} + +/// The precedence of unary minus: tighter than `*`, looser than `|`. +const NEG_PRECEDENCE: u8 = 7; + +#[derive(Clone, Copy, PartialEq)] +enum Func { + Last, + Position, + Count, + Id, + LocalName, + NamespaceUri, + Name, + String, + Concat, + StartsWith, + Contains, + SubstringBefore, + SubstringAfter, + Substring, + StringLength, + NormalizeSpace, + Translate, + Boolean, + Not, + True, + False, + Lang, + Number, + Sum, + Floor, + Ceiling, + Round, +} + +/// The core function library (XPath 1.0 section 4): each name, and its least and most arguments. +const FUNCS: [(&str, Func, usize, usize); 27] = [ + ("last", Func::Last, 0, 0), + ("position", Func::Position, 0, 0), + ("count", Func::Count, 1, 1), + ("id", Func::Id, 1, 1), + ("local-name", Func::LocalName, 0, 1), + ("namespace-uri", Func::NamespaceUri, 0, 1), + ("name", Func::Name, 0, 1), + ("string", Func::String, 0, 1), + ("concat", Func::Concat, 2, usize::MAX), + ("starts-with", Func::StartsWith, 2, 2), + ("contains", Func::Contains, 2, 2), + ("substring-before", Func::SubstringBefore, 2, 2), + ("substring-after", Func::SubstringAfter, 2, 2), + ("substring", Func::Substring, 2, 3), + ("string-length", Func::StringLength, 0, 1), + ("normalize-space", Func::NormalizeSpace, 0, 1), + ("translate", Func::Translate, 3, 3), + ("boolean", Func::Boolean, 1, 1), + ("not", Func::Not, 1, 1), + ("true", Func::True, 0, 0), + ("false", Func::False, 0, 0), + ("lang", Func::Lang, 1, 1), + ("number", Func::Number, 0, 1), + ("sum", Func::Sum, 1, 1), + ("floor", Func::Floor, 1, 1), + ("ceiling", Func::Ceiling, 1, 1), + ("round", Func::Round, 1, 1), +]; + +/// A token the parser reads: names and `*` with their roles decided (XPath 1.0 section 3.7). +enum Tok { + Punct(Punct), + Op(Bin), + Test(Test), + Axis(Axis), + Func(Func, &'static str), + Literal(Key), + Number(f64), + Var(Key), +} + +fn ncname_end(src: &[u16], at: usize) -> Option { + let first = *src.get(at)?; + if first == COLON || !is_name_start(first) { + return None; + } + let mut end = at + 1; + while src.get(end).is_some_and(|&c| c != COLON && is_name_part(c)) { + end += 1; + } + valid_xml_units(src.get(at..end)?).then_some(end) +} + +fn lex_name(src: &[u16], at: usize) -> Option<(Raw, usize)> { + let end = ncname_end(src, at)?; + let first: Key = Rc::from(src.get(at..end)?); + if src.get(end) != Some(&COLON) || src.get(end + 1) == Some(&COLON) { + return Some((Raw::Name(None, first), end)); + } + if src.get(end + 1) == Some(&STAR) { + return Some((Raw::PrefixStar(first), end + 2)); + } + let local_end = ncname_end(src, end + 1)?; + Some((Raw::Name(Some(first), Rc::from(src.get(end + 1..local_end)?)), local_end)) +} + +fn lex_number(src: &[u16], at: usize) -> Option<(Raw, usize)> { + let mut end = at; + while src.get(end).copied().is_some_and(is_digit) { + end += 1; + } + if src.get(end) == Some(&DOT) { + end += 1; + while src.get(end).copied().is_some_and(is_digit) { + end += 1; + } + } + let text = String::from_utf16(src.get(at..end)?).ok()?; + Some((Raw::Number(text.parse().ok()?), end)) +} + +fn lex_literal(src: &[u16], at: usize, quote: u16) -> Option<(Raw, usize)> { + let rest = src.get(at + 1..)?; + let len = rest.iter().position(|&c| c == quote)?; + Some((Raw::Literal(Rc::from(rest.get(..len)?)), at + len + 2)) +} + +fn lex_var(src: &[u16], at: usize) -> Option<(Raw, usize)> { + let (Raw::Name(..), end) = lex_name(src, at + 1)? else { return None }; + Some((Raw::Var(Rc::from(src.get(at + 1..end)?)), end)) +} + +/// The token that starts at `src[at]`, and the offset after it. +fn lex_one(src: &[u16], at: usize, c: u16) -> Option<(Raw, usize)> { + if c != COLON && is_name_start(c) { + return lex_name(src, at); + } + let next = src.get(at + 1).copied(); + let p = |p: Punct, n: usize| Some((Raw::Punct(p), at + n)); + match char::from_u32(u32::from(c))? { + '(' => p(Punct::LParen, 1), + ')' => p(Punct::RParen, 1), + '[' => p(Punct::LBracket, 1), + ']' => p(Punct::RBracket, 1), + '@' => p(Punct::At, 1), + ',' => p(Punct::Comma, 1), + '|' => p(Punct::Pipe, 1), + '+' => p(Punct::Plus, 1), + '-' => p(Punct::Minus, 1), + '=' => p(Punct::Eq, 1), + '*' => Some((Raw::Star, at + 1)), + '/' if next == Some(SLASH) => p(Punct::SlashSlash, 2), + '/' => p(Punct::Slash, 1), + ':' if next == Some(COLON) => p(Punct::ColonColon, 2), + '!' if next == Some(EQUALS) => p(Punct::Ne, 2), + '<' if next == Some(EQUALS) => p(Punct::Le, 2), + '<' => p(Punct::Lt, 1), + '>' if next == Some(EQUALS) => p(Punct::Ge, 2), + '>' => p(Punct::Gt, 1), + '.' if next == Some(DOT) => p(Punct::DotDot, 2), + '.' if next.is_some_and(is_digit) => lex_number(src, at), + '.' => p(Punct::Dot, 1), + '"' | '\'' => lex_literal(src, at, c), + '$' => lex_var(src, at), + _ if is_digit(c) => lex_number(src, at), + _ => None, + } +} + +fn lex(interp: &mut Interp, held: &mut HeldBytes, src: &[u16]) -> JsResult> { + let mut out = Vec::new(); + let mut at = 0; + loop { + while src.get(at).copied().is_some_and(is_xml_space) { + at += 1; + } + let Some(&c) = src.get(at) else { return Ok(out) }; + let Some((raw, end)) = lex_one(src, at, c) else { + return Err(syntax(interp, &format!("the XPath expression cannot be read at offset {at}"))); + }; + charge_units(interp, end - at)?; + push_held(interp, held, &mut out, raw)?; + at = end; + } +} + +fn units_are(units: &[u16], text: &str) -> bool { + units.iter().copied().eq(text.encode_utf16()) +} + +fn operator_name(name: &[u16]) -> Option { + [("and", Bin::And), ("or", Bin::Or), ("mod", Bin::Mod), ("div", Bin::Div)].into_iter().find(|(n, _)| units_are(name, n)).map(|(_, b)| b) +} + +fn punct_token(p: Punct) -> Tok { + match p { + Punct::Pipe => Tok::Op(Bin::Union), + Punct::Plus => Tok::Op(Bin::Add), + Punct::Minus => Tok::Op(Bin::Sub), + Punct::Eq => Tok::Op(Bin::Eq), + Punct::Ne => Tok::Op(Bin::Ne), + Punct::Lt => Tok::Op(Bin::Lt), + Punct::Le => Tok::Op(Bin::Le), + Punct::Gt => Tok::Op(Bin::Gt), + Punct::Ge => Tok::Op(Bin::Ge), + other => Tok::Punct(other), + } +} + +/// Whether a token at this point is an operator: there is a token before it, and it is not `@`, +/// `::`, `(`, `[`, `,` or an operator (XPath 1.0 section 3.7). +fn operator_position(last: Option<&Tok>) -> bool { + last.is_some_and(|t| { + !matches!( + t, + Tok::Punct(Punct::LParen | Punct::LBracket | Punct::At | Punct::Comma | Punct::Slash | Punct::SlashSlash) + | Tok::Op(_) + | Tok::Axis(_) + | Tok::Func(..) + ) + }) +} + +/// A name followed by `(`: a node type test, which also takes its `)`, or a function call. +/// Returns the token and how many raw tokens it takes. +fn call_or_node_type(interp: &mut Interp, prefix: Option<&Key>, name: &Key, after: &[Raw]) -> JsResult<(Tok, usize)> { + if prefix.is_none() { + let plain = [("node", Test::Node), ("text", Test::Text), ("comment", Test::Comment)].into_iter().find(|(n, _)| units_are(name, n)); + if let Some((_, test)) = plain { + return match after.first() { + Some(Raw::Punct(Punct::RParen)) => Ok((Tok::Test(test), 3)), + _ => Err(syntax(interp, "an XPath node type test takes no argument")), + }; + } + if units_are(name, "processing-instruction") { + return match after { + [Raw::Punct(Punct::RParen), ..] => Ok((Tok::Test(Test::Pi(None)), 3)), + [Raw::Literal(target), Raw::Punct(Punct::RParen), ..] => Ok((Tok::Test(Test::Pi(Some(target.clone()))), 4)), + _ => Err(syntax(interp, "processing-instruction() takes one string literal or none")), + }; + } + } + let found = FUNCS.iter().find(|(n, ..)| prefix.is_none() && units_are(name, n)); + match found { + Some(&(n, f, ..)) => Ok((Tok::Func(f, n), 2)), + None => { + let shown = String::from_utf16_lossy(name); + Err(interp.type_error(&format!("{shown} is not an XPath 1.0 function"))) + } + } +} + +fn classify(interp: &mut Interp, held: &mut HeldBytes, raw: &[Raw]) -> JsResult> { + let mut out: Vec = Vec::new(); + let mut at = 0; + while let Some(r) = raw.get(at) { + interp.use_fuel()?; + let operator = operator_position(out.last()); + let next = raw.get(at + 1); + let (tok, used) = match r { + Raw::Star if operator => (Tok::Op(Bin::Mul), 1), + Raw::Star => (Tok::Test(Test::Any), 1), + Raw::Name(None, n) if operator => match operator_name(n) { + Some(op) => (Tok::Op(op), 1), + None => return Err(syntax(interp, "an XPath operator is missing")), + }, + Raw::Name(p, n) if matches!(next, Some(Raw::Punct(Punct::LParen))) => { + call_or_node_type(interp, p.as_ref(), n, raw.get(at + 2..).unwrap_or_default())? + } + Raw::Name(p, n) if matches!(next, Some(Raw::Punct(Punct::ColonColon))) => { + let axis = AXES.iter().find(|(a, _)| p.is_none() && units_are(n, a)).map(|&(_, a)| a); + match axis { + Some(a) => (Tok::Axis(a), 2), + None => return Err(syntax(interp, &format!("{} is not an XPath axis", String::from_utf16_lossy(n)))), + } + } + Raw::Name(p, n) => (Tok::Test(Test::Name(p.clone(), n.clone())), 1), + Raw::PrefixStar(p) => (Tok::Test(Test::Prefix(p.clone())), 1), + Raw::Punct(Punct::ColonColon) => return Err(syntax(interp, "an XPath axis name is missing before ::")), + Raw::Punct(p) => (punct_token(*p), 1), + Raw::Literal(s) => (Tok::Literal(s.clone()), 1), + Raw::Number(n) => (Tok::Number(*n), 1), + Raw::Var(v) => (Tok::Var(v.clone()), 1), + }; + push_held(interp, held, &mut out, tok)?; + at += used; + } + Ok(out) +} + +// ---- the syntax tree ---- + +struct Step { + axis: Axis, + test: Test, + preds: Vec, +} + +enum Expr { + Bin(Bin, usize, usize), + Neg(usize), + Num(f64), + Lit(Key), + Var(usize), + Call(Func, Vec), + /// A location path, or a filter expression with its predicates, followed by steps. + Path { + filter: Option<(usize, Vec)>, + absolute: bool, + steps: Vec, + }, +} + +/// A parsed expression: the tree in its arena, its root, and the variables and prefixes it names. +struct Parsed { + exprs: Vec, + root: usize, + vars: Vec, + prefixes: Vec, + _held: HeldBytes, +} + +#[derive(Clone, Copy)] +enum Op { + Bin(Bin), + Neg, +} + +impl Op { + fn precedence(self) -> u8 { + match self { + Op::Bin(b) => b.precedence(), + Op::Neg => NEG_PRECEDENCE, + } + } +} + +/// A path expression being read. +#[derive(Default)] +struct Operand { + filter: Option<(usize, Vec)>, + absolute: bool, + steps: Vec, + /// The last step is `.` or `..`, which take no predicate. + abbreviated: bool, +} + +impl Operand { + fn bare_root(&self) -> bool { + self.absolute && self.steps.is_empty() && self.filter.is_none() + } +} + +enum FrameKind { + Top, + Group, + Pred, + Args(Func, &'static str, Vec), +} + +/// One bracket level: its operators and operands, read by operator precedence. +struct Frame { + kind: FrameKind, + ops: Vec, + vals: Vec, + operand: Option, +} + +impl Frame { + fn new(kind: FrameKind) -> Self { + Frame { kind, ops: Vec::new(), vals: Vec::new(), operand: None } + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Want { + Operand, + Step, + Test(Axis), + After, +} + +struct Parser<'i> { + interp: &'i mut Interp, + held: HeldBytes, + exprs: Vec, + vars: Vec, + var_index: HashMap, + prefixes: HashSet, + frames: Vec, + want: Want, +} + +impl Parser<'_> { + fn error(&mut self, message: &str) -> Abrupt { + syntax(self.interp, message) + } + + fn push_expr(&mut self, e: Expr) -> JsResult { + self.held.add(self.interp, EXPR_BYTES)?; + push_held(self.interp, &mut self.held, &mut self.exprs, e)?; + Ok(self.exprs.len() - 1) + } + + fn top(&mut self) -> JsResult<&mut Frame> { + self.frames.last_mut().ok_or_else(internal) + } + + fn operand(&mut self) -> JsResult<&mut Operand> { + self.top()?.operand.as_mut().ok_or_else(internal) + } + + fn open(&mut self, kind: FrameKind) -> JsResult<()> { + if self.frames.len() >= self.interp.options.max_depth { + return Err(self.error(TOO_DEEP)); + } + self.held.add(self.interp, size_of::())?; + self.frames.push(Frame::new(kind)); + self.want = Want::Operand; + Ok(()) + } + + fn token(&mut self, tok: Tok) -> JsResult<()> { + match self.want { + Want::Operand => self.operand_token(tok), + Want::Step => self.step_token(tok), + Want::Test(axis) => match tok { + Tok::Test(test) => self.push_step(axis, test, false), + _ => Err(self.error("an XPath node test is missing")), + }, + Want::After => self.after_token(tok), + } + } + + fn primary(&mut self, e: Expr) -> JsResult<()> { + let id = self.push_expr(e)?; + self.top()?.operand = Some(Operand { filter: Some((id, Vec::new())), ..Operand::default() }); + self.want = Want::After; + Ok(()) + } + + fn operand_token(&mut self, tok: Tok) -> JsResult<()> { + match tok { + Tok::Op(Bin::Sub) => { + self.top()?.ops.push(Op::Neg); + Ok(()) + } + Tok::Punct(Punct::Slash) => { + self.top()?.operand = Some(Operand { absolute: true, ..Operand::default() }); + self.want = Want::Step; + Ok(()) + } + Tok::Punct(Punct::SlashSlash) => { + self.top()?.operand = Some(Operand { absolute: true, ..Operand::default() }); + self.descendants_step() + } + Tok::Literal(s) => self.primary(Expr::Lit(s)), + Tok::Number(n) => self.primary(Expr::Num(n)), + Tok::Var(name) => { + let next = self.vars.len(); + let at = *self.var_index.entry(name.clone()).or_insert(next); + if at == next { + push_held(self.interp, &mut self.held, &mut self.vars, name)?; + } + self.primary(Expr::Var(at)) + } + Tok::Func(f, n) => self.open(FrameKind::Args(f, n, Vec::new())), + Tok::Punct(Punct::LParen) => self.open(FrameKind::Group), + Tok::Punct(Punct::RParen) if self.empty_call()? => self.close_paren(), + tok @ (Tok::Test(_) | Tok::Axis(_) | Tok::Punct(Punct::At | Punct::Dot | Punct::DotDot)) => { + self.top()?.operand = Some(Operand::default()); + self.step_token(tok) + } + _ => Err(self.error("an XPath operand is missing")), + } + } + + /// Whether the open bracket is a function call's, with nothing in it yet. + fn empty_call(&mut self) -> JsResult { + let f = self.top()?; + Ok(matches!(&f.kind, FrameKind::Args(_, _, args) if args.is_empty()) && f.ops.is_empty() && f.vals.is_empty() && f.operand.is_none()) + } + + fn descendants_step(&mut self) -> JsResult<()> { + self.operand()?.steps.push(Step { axis: Axis::DescendantOrSelf, test: Test::Node, preds: Vec::new() }); + self.want = Want::Step; + Ok(()) + } + + fn push_step(&mut self, axis: Axis, test: Test, abbreviated: bool) -> JsResult<()> { + if let Test::Prefix(p) | Test::Name(Some(p), _) = &test + && !self.prefixes.contains(p) + { + self.held.add(self.interp, ENTRY_BYTES)?; + self.prefixes.insert(p.clone()); + } + self.held.add(self.interp, size_of::())?; + let operand = self.operand()?; + operand.steps.push(Step { axis, test, preds: Vec::new() }); + operand.abbreviated = abbreviated; + self.want = Want::After; + Ok(()) + } + + fn step_token(&mut self, tok: Tok) -> JsResult<()> { + match tok { + Tok::Punct(Punct::Dot) => self.push_step(Axis::Itself, Test::Node, true), + Tok::Punct(Punct::DotDot) => self.push_step(Axis::Parent, Test::Node, true), + Tok::Punct(Punct::At) => { + self.want = Want::Test(Axis::Attribute); + Ok(()) + } + Tok::Axis(a) => { + self.want = Want::Test(a); + Ok(()) + } + Tok::Test(t) => self.push_step(Axis::Child, t, false), + tok if self.operand()?.bare_root() => { + self.want = Want::After; + self.after_token(tok) + } + _ => Err(self.error("an XPath step is missing")), + } + } + + fn after_token(&mut self, tok: Tok) -> JsResult<()> { + match tok { + Tok::Punct(p @ (Punct::LBracket | Punct::Slash | Punct::SlashSlash)) => { + let operand = self.operand()?; + let (bare, abbreviated) = (operand.bare_root(), operand.abbreviated); + if bare || (p == Punct::LBracket && abbreviated) { + return Err(self.error("an XPath predicate or step cannot follow here")); + } + match p { + Punct::LBracket => self.open(FrameKind::Pred), + Punct::Slash => { + self.want = Want::Step; + Ok(()) + } + _ => self.descendants_step(), + } + } + Tok::Op(b) => self.binary(b), + Tok::Punct(Punct::RParen) => self.close_paren(), + Tok::Punct(Punct::RBracket) => self.close_bracket(), + Tok::Punct(Punct::Comma) => self.next_argument(), + _ => Err(self.error("an XPath operator is missing")), + } + } + + fn finish_operand(&mut self, operand: Operand) -> JsResult { + match operand { + Operand { filter: Some((e, preds)), steps, .. } if preds.is_empty() && steps.is_empty() => Ok(e), + Operand { filter, absolute, steps, .. } => self.push_expr(Expr::Path { filter, absolute, steps }), + } + } + + fn reduce_one(&mut self, frame: &mut Frame) -> JsResult<()> { + let op = frame.ops.pop().ok_or_else(internal)?; + let rhs = frame.vals.pop().ok_or_else(internal)?; + let e = match op { + Op::Neg => Expr::Neg(rhs), + Op::Bin(b) => Expr::Bin(b, frame.vals.pop().ok_or_else(internal)?, rhs), + }; + let id = self.push_expr(e)?; + frame.vals.push(id); + Ok(()) + } + + fn binary(&mut self, b: Bin) -> JsResult<()> { + let mut frame = self.frames.pop().ok_or_else(internal)?; + let result = self.binary_in(&mut frame, b); + self.frames.push(frame); + result?; + self.want = Want::Operand; + Ok(()) + } + + fn binary_in(&mut self, frame: &mut Frame, b: Bin) -> JsResult<()> { + let operand = frame.operand.take().ok_or_else(internal)?; + let e = self.finish_operand(operand)?; + frame.vals.push(e); + while frame.ops.last().is_some_and(|op| op.precedence() >= b.precedence()) { + self.interp.use_fuel()?; + self.reduce_one(frame)?; + } + self.held.add(self.interp, 2 * size_of::())?; + frame.ops.push(Op::Bin(b)); + Ok(()) + } + + /// Ends the innermost bracket and returns its kind and expression. + fn close(&mut self) -> JsResult<(FrameKind, usize)> { + if self.frames.len() < 2 { + return Err(self.error("the XPath expression has an unmatched closing bracket")); + } + let mut frame = self.frames.pop().ok_or_else(internal)?; + let e = self.reduce(&mut frame)?; + Ok((frame.kind, e)) + } + + fn reduce(&mut self, frame: &mut Frame) -> JsResult { + let operand = frame.operand.take().ok_or_else(|| syntax(self.interp, "an XPath operand is missing"))?; + let e = self.finish_operand(operand)?; + frame.vals.push(e); + while !frame.ops.is_empty() { + self.interp.use_fuel()?; + self.reduce_one(frame)?; + } + match frame.vals.as_slice() { + [e] => Ok(*e), + _ => Err(internal()), + } + } + + fn close_paren(&mut self) -> JsResult<()> { + let (kind, e) = if self.top()?.operand.is_none() { + (self.frames.pop().ok_or_else(internal)?.kind, None) + } else { + let (kind, e) = self.close()?; + (kind, Some(e)) + }; + match kind { + FrameKind::Group => self.primary_id(e.ok_or_else(internal)?), + FrameKind::Args(f, name, mut args) => { + args.extend(e); + let (_, _, least, most) = FUNCS.iter().find(|(_, g, ..)| *g == f).copied().ok_or_else(internal)?; + if args.len() < least || args.len() > most { + return Err(self.interp.type_error(&format!("the XPath function {name} takes the wrong number of arguments"))); + } + let call = self.push_expr(Expr::Call(f, args))?; + self.primary_id(call) + } + _ => Err(self.error("the XPath expression has an unmatched )")), + } + } + + fn primary_id(&mut self, id: usize) -> JsResult<()> { + if self.frames.is_empty() { + return Err(self.error("the XPath expression has an unmatched )")); + } + self.top()?.operand = Some(Operand { filter: Some((id, Vec::new())), ..Operand::default() }); + self.want = Want::After; + Ok(()) + } + + fn close_bracket(&mut self) -> JsResult<()> { + let (kind, e) = self.close()?; + if !matches!(kind, FrameKind::Pred) { + return Err(self.error("the XPath expression has an unmatched ]")); + } + let operand = self.operand()?; + match (operand.steps.last_mut(), operand.filter.as_mut()) { + (Some(step), _) => step.preds.push(e), + (None, Some((_, preds))) => preds.push(e), + (None, None) => return Err(internal()), + } + self.want = Want::After; + Ok(()) + } + + fn next_argument(&mut self) -> JsResult<()> { + if !matches!(self.top()?.kind, FrameKind::Args(..)) || self.frames.len() < 2 { + return Err(self.error("a comma in an XPath expression must separate function arguments")); + } + let mut frame = self.frames.pop().ok_or_else(internal)?; + let e = self.reduce(&mut frame); + if let (Ok(e), FrameKind::Args(_, _, args)) = (&e, &mut frame.kind) { + args.push(*e); + } + frame.ops.clear(); + frame.vals.clear(); + self.frames.push(frame); + e?; + self.want = Want::Operand; + Ok(()) + } + + fn finish(mut self) -> JsResult { + let complete = self.want == Want::After || (self.want == Want::Step && self.operand()?.bare_root()); + if !complete || self.frames.len() != 1 { + return Err(self.error("the XPath expression ends early")); + } + let mut frame = self.frames.pop().ok_or_else(internal)?; + let root = self.reduce(&mut frame)?; + Ok(Parsed { exprs: self.exprs, root, vars: self.vars, prefixes: self.prefixes.into_iter().collect(), _held: self.held }) + } +} + +fn parse(interp: &mut Interp, src: &[u16]) -> JsResult { + let mut held = HeldBytes::new(interp); + let raw = lex(interp, &mut held, src)?; + let toks = classify(interp, &mut held, &raw)?; + drop(raw); + let mut p = Parser { + interp, + held, + exprs: Vec::new(), + vars: Vec::new(), + var_index: HashMap::new(), + prefixes: HashSet::new(), + frames: vec![Frame::new(FrameKind::Top)], + want: Want::Operand, + }; + for tok in toks { + p.interp.use_fuel()?; + p.token(tok)?; + } + p.finish() +} + +// ---- values ---- + +/// A node of the XPath data model. `Root` is the root above the topmost node it names, and `Ns` +/// is a namespace node of `owner`, at position `at` among its namespaces. +#[derive(Clone, PartialEq, Eq, Hash)] +enum XNode { + Root(ObjId), + Node(ObjId), + Ns { owner: ObjId, at: u32, prefix: Key, uri: Key }, +} + +#[derive(Clone, Copy, PartialEq)] +enum NodeKind { + Root, + Ns, + Xml(XmlKind), +} + +/// A list of nodes whose buffer is held against the heap limit. +struct Nodes { + list: Vec, + held: HeldBytes, +} + +impl Nodes { + fn new(interp: &Interp) -> Self { + Nodes { list: Vec::new(), held: HeldBytes::new(interp) } + } + + fn push(&mut self, interp: &mut Interp, n: XNode) -> JsResult<()> { + push_held(interp, &mut self.held, &mut self.list, n) + } +} + +/// A string value whose units are held against the heap limit when the evaluator built them. +struct Text { + units: Key, + _held: HeldBytes, +} + +impl Text { + fn plain(interp: &Interp, units: Key) -> Self { + Text { units, _held: HeldBytes::new(interp) } + } +} + +struct TextBuf { + units: Vec, + held: HeldBytes, +} + +impl TextBuf { + fn new(interp: &Interp) -> Self { + TextBuf { units: Vec::new(), held: HeldBytes::new(interp) } + } + + fn push(&mut self, interp: &mut Interp, more: &[u16]) -> JsResult<()> { + charge_units(interp, more.len())?; + let want = self.units.len().saturating_add(more.len()); + let cap = self.units.capacity(); + if want > cap { + let grown = want.max(cap.saturating_mul(2)).max(16); + self.held.add(interp, (grown - cap).saturating_mul(2))?; + self.units.reserve_exact(grown - self.units.len()); + } + self.units.extend_from_slice(more); + Ok(()) + } + + fn finish(self) -> Text { + Text { units: Rc::from(self.units), _held: self.held } + } +} + +enum Val { + Set(Nodes), + Bool(bool), + Num(f64), + Str(Text), +} + +/// A variable's value, read from the variables object before evaluation starts. +enum Bound { + Set(Vec), + Bool(bool), + Num(f64), + Str(Key), +} + +#[derive(Clone)] +struct Ctx { + node: XNode, + pos: usize, + size: usize, +} + +/// A location path being evaluated. Stage 0 applies the filter expression's predicates to the +/// filter's nodes; stage `s` applies step `s - 1` to each node of `inputs` in turn. +struct PathRun { + path: usize, + stage: usize, + inputs: Nodes, + ci: usize, + cur: Nodes, + pred: usize, + at: usize, + kept: Nodes, + waiting: bool, + out: Nodes, + seen: HashSet, + seen_held: HeldBytes, +} + +enum Task { + Eval(usize, Ctx), + Bin(Bin), + Neg, + Logic { and: bool, rhs: usize, ctx: Ctx }, + Bool, + Call(Func, usize, Ctx), + PathStart(usize), + Path(Box), +} + +fn to_bool(v: &Val) -> bool { + match v { + Val::Set(s) => !s.list.is_empty(), + Val::Bool(b) => *b, + Val::Num(n) => *n != 0.0 && !n.is_nan(), + Val::Str(t) => !t.units.is_empty(), + } +} + +/// The number a string stands for (XPath 1.0 section 4.4): optional white space, an optional +/// minus, digits with an optional fraction, optional white space; anything else is NaN. +fn str_num(interp: &mut Interp, units: &[u16]) -> JsResult { + let start = units.iter().position(|&c| !is_xml_space(c)).unwrap_or(units.len()); + let end = units.iter().rposition(|&c| !is_xml_space(c)).map_or(start, |e| e + 1); + let body = units.get(start..end).unwrap_or_default(); + let (negative, digits) = match body.split_first() { + Some((&DASH, rest)) => (true, rest), + _ => (false, body), + }; + let dots = digits.iter().filter(|&&c| c == DOT).count(); + if dots > 1 || !digits.iter().all(|&c| c == DOT || is_digit(c)) || !digits.iter().any(|&c| is_digit(c)) { + return Ok(f64::NAN); + } + let mut held = HeldBytes::new(interp); + held.add(interp, digits.len())?; + let text: String = digits.iter().map(|&c| char::from(c as u8)).collect(); + let n: f64 = text.parse().unwrap_or(f64::NAN); + Ok(if negative { -n } else { n }) +} + +/// A number as a string (XPath 1.0 section 4.2): integers without a decimal point, and no +/// exponent. +fn num_text(n: f64) -> String { + if n.is_nan() { + "NaN".into() + } else if n.is_infinite() { + if n > 0.0 { "Infinity".into() } else { "-Infinity".into() } + } else if n == 0.0 { + "0".into() + } else { + format!("{n}") + } +} + +/// `round` (XPath 1.0 section 4.4): the nearest integer, halves toward positive infinity, with +/// negative zero for values from -0.5 up to zero. +fn round(n: f64) -> f64 { + if !n.is_finite() || n == 0.0 { + return n; + } + let floor = n.floor(); + let r = if n - floor >= 0.5 { floor + 1.0 } else { floor }; + if r == 0.0 && n < 0.0 { -0.0 } else { r } +} + +fn compare_numbers(op: Bin, a: f64, b: f64) -> bool { + match op { + Bin::Eq => a == b, + Bin::Ne => a != b, + Bin::Lt => a < b, + Bin::Le => a <= b, + Bin::Gt => a > b, + _ => a >= b, + } +} + +fn flip(op: Bin) -> Bin { + match op { + Bin::Lt => Bin::Gt, + Bin::Le => Bin::Ge, + Bin::Gt => Bin::Lt, + Bin::Ge => Bin::Le, + other => other, + } +} + +fn code_points(units: &[u16]) -> Vec { + char::decode_utf16(units.iter().copied()).map(|r| r.map_or_else(|e| u32::from(e.unpaired_surrogate()), u32::from)).collect() +} + +fn push_point(out: &mut Vec, p: u32) { + match char::from_u32(p) { + Some(c) => { + let mut buf = [0u16; 2]; + out.extend_from_slice(c.encode_utf16(&mut buf)); + } + None => out.extend(u16::try_from(p).ok()), + } +} + +fn lower(c: u16) -> u16 { + if (0x41..=0x5A).contains(&c) { c + 0x20 } else { c } +} + +fn same_ignoring_case(a: &[u16], b: &[u16]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(&x, &y)| lower(x) == lower(y)) +} + +fn name_uri(name: &XmlName) -> &[u16] { + name.uri.as_deref().unwrap_or_default() +} + +fn kind_of(interp: &Interp, n: &XNode) -> JsResult { + Ok(match n { + XNode::Root(_) => NodeKind::Root, + XNode::Ns { .. } => NodeKind::Ns, + XNode::Node(x) => NodeKind::Xml(interp.xml_kind(*x)?), + }) +} + +fn parent_of(interp: &Interp, n: &XNode) -> JsResult> { + Ok(match n { + XNode::Root(_) => None, + XNode::Node(x) => Some(interp.xml_node(*x)?.parent.map_or(XNode::Root(*x), XNode::Node)), + XNode::Ns { owner, .. } => Some(XNode::Node(*owner)), + }) +} + +/// The parent of `x` and the position of `x` among its children, when `x` is a child. +fn child_position(interp: &mut Interp, x: ObjId) -> JsResult> { + let node = interp.xml_node(x)?; + let Some(p) = node.parent.filter(|_| node.kind != XmlKind::Attribute) else { return Ok(None) }; + let len = interp.xml_node(p)?.children.len(); + for i in 0..len { + interp.use_fuel()?; + if interp.xml_node(p)?.children.get(i) == Some(&x) { + return Ok(Some((p, i))); + } + } + Ok(None) +} + +fn top_of(interp: &mut Interp, mut x: ObjId) -> JsResult { + while let Some(p) = interp.xml_node(x)?.parent { + interp.use_fuel()?; + x = p; + } + Ok(x) +} + +/// The XPath expression evaluator for one call: the parsed expression, the variables, the +/// prefixes resolved for the current context element, and the document order of the trees met. +struct Ev<'p> { + parsed: &'p Parsed, + bound: Vec, + uris: HashMap, + order: HashMap, + root_order: HashMap, + next: u64, + held: HeldBytes, + tasks: Vec, + vals: Vec, +} + +impl<'p> Ev<'p> { + fn new(interp: &mut Interp, parsed: &'p Parsed, bound: Vec) -> JsResult { + let mut ev = Ev { + parsed, + bound: Vec::new(), + uris: HashMap::new(), + order: HashMap::new(), + root_order: HashMap::new(), + next: 0, + held: HeldBytes::new(interp), + tasks: Vec::new(), + vals: Vec::new(), + }; + for b in bound { + let b = match b { + Bound::Set(list) => { + let mut nodes = Nodes::new(interp); + for n in list { + nodes.push(interp, n)?; + } + let sorted = ev.sort(interp, nodes)?; + ev.held.add(interp, sorted.list.len().saturating_mul(size_of::()))?; + Bound::Set(sorted.list) + } + other => other, + }; + ev.bound.push(b); + } + Ok(ev) + } + + // ---- document order ---- + + fn put_order(&mut self, interp: &mut Interp, x: ObjId) -> JsResult<()> { + self.held.add(interp, ENTRY_BYTES)?; + self.order.insert(x, self.next); + self.next += 1; + Ok(()) + } + + /// Numbers the tree under `top` in document order: the root, then each node followed by its + /// attributes and then its children. + fn number_tree(&mut self, interp: &mut Interp, top: ObjId) -> JsResult<()> { + if self.root_order.contains_key(&top) { + return Ok(()); + } + self.held.add(interp, ENTRY_BYTES)?; + self.root_order.insert(top, self.next); + self.next += 1; + self.number_node(interp, top)?; + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (top, 0usize))?; + while let Some(&(x, at)) = stack.last() { + interp.use_fuel()?; + let Some(c) = interp.xml_node(x)?.children.get(at).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + self.number_node(interp, c)?; + push_held(interp, &mut held, &mut stack, (c, 0))?; + } + Ok(()) + } + + fn number_node(&mut self, interp: &mut Interp, x: ObjId) -> JsResult<()> { + self.put_order(interp, x)?; + let count = interp.xml_node(x)?.attrs.len(); + for i in 0..count { + interp.use_fuel()?; + if let Some(a) = interp.xml_node(x)?.attrs.get(i).copied() { + self.put_order(interp, a)?; + } + } + Ok(()) + } + + fn order_of(&mut self, interp: &mut Interp, n: &XNode) -> JsResult<(u64, u32)> { + match n { + XNode::Root(t) => { + self.number_tree(interp, *t)?; + Ok((self.root_order.get(t).copied().ok_or_else(internal)?, 0)) + } + XNode::Node(x) => { + if !self.order.contains_key(x) { + let top = top_of(interp, *x)?; + self.number_tree(interp, top)?; + } + Ok((self.order.get(x).copied().ok_or_else(internal)?, 0)) + } + XNode::Ns { owner, at, .. } => { + let (o, _) = self.order_of(interp, &XNode::Node(*owner))?; + Ok((o, at.saturating_add(1))) + } + } + } + + /// The nodes in document order, without repeats. + fn sort(&mut self, interp: &mut Interp, set: Nodes) -> JsResult { + if set.list.len() < 2 { + return Ok(set); + } + let n = set.list.len() as u64; + let mut held = HeldBytes::new(interp); + let mut keyed = Vec::new(); + for x in set.list { + let k = self.order_of(interp, &x)?; + push_held(interp, &mut held, &mut keyed, (k, x))?; + } + use_fuel_n(interp, n.saturating_mul(u64::from(n.ilog2()) + 1) / 8 + 1)?; + keyed.sort_by_key(|(k, _)| *k); + keyed.dedup_by_key(|(k, _)| *k); + let mut out = Nodes::new(interp); + for (_, x) in keyed { + out.push(interp, x)?; + } + Ok(out) + } + + // ---- axes and node tests ---- + + fn prefix_uri(&self, p: &Key) -> JsResult<&Key> { + self.uris.get(p).ok_or_else(internal) + } + + fn matches(&self, interp: &Interp, axis: Axis, test: &Test, n: &XNode) -> JsResult { + let kind = kind_of(interp, n)?; + let principal = match axis { + Axis::Attribute => NodeKind::Xml(XmlKind::Attribute), + Axis::Namespace => NodeKind::Ns, + _ => NodeKind::Xml(XmlKind::Element), + }; + let name = match n { + XNode::Node(x) => interp.xml_node(*x)?.name.as_ref(), + _ => None, + }; + Ok(match test { + Test::Node => true, + Test::Text => kind == NodeKind::Xml(XmlKind::Text), + Test::Comment => kind == NodeKind::Xml(XmlKind::Comment), + Test::Pi(target) => kind == NodeKind::Xml(XmlKind::Pi) && target.as_ref().is_none_or(|t| name.is_some_and(|q| q.local == *t)), + Test::Any => kind == principal, + Test::Prefix(p) => { + let uri = self.prefix_uri(p)?; + kind == principal && name.is_some_and(|q| name_uri(q) == &**uri) + } + Test::Name(p, local) => kind == principal && self.name_matches(n, name, p.as_ref(), local)?, + }) + } + + fn name_matches(&self, n: &XNode, name: Option<&XmlName>, prefix: Option<&Key>, local: &Key) -> JsResult { + if let XNode::Ns { prefix: ns_prefix, .. } = n { + return Ok(prefix.is_none() && ns_prefix == local); + } + let Some(q) = name else { return Ok(false) }; + let uri: &[u16] = match prefix { + Some(p) => self.prefix_uri(p)?, + None => &[], + }; + Ok(q.local == *local && name_uri(q) == uri) + } + + fn add(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: XNode) -> JsResult<()> { + interp.use_fuel()?; + if self.matches(interp, axis, test, &n)? { + out.push(interp, n)?; + } + Ok(()) + } + + /// Adds `x` and the nodes under it, in document order. + fn subtree(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, x: ObjId) -> JsResult<()> { + self.add(interp, out, axis, test, XNode::Node(x))?; + self.under(interp, out, axis, test, x) + } + + /// Adds the nodes under `x`, in document order. + fn under(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, x: ObjId) -> JsResult<()> { + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (x, 0usize))?; + while let Some(&(p, at)) = stack.last() { + let Some(c) = interp.xml_node(p)?.children.get(at).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + self.add(interp, out, axis, test, XNode::Node(c))?; + push_held(interp, &mut held, &mut stack, (c, 0))?; + } + Ok(()) + } + + fn descendants(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + match n { + XNode::Root(t) => self.subtree(interp, out, axis, test, *t), + XNode::Node(x) => self.under(interp, out, axis, test, *x), + XNode::Ns { .. } => Ok(()), + } + } + + fn children(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let x = match n { + XNode::Root(t) => return self.add(interp, out, axis, test, XNode::Node(*t)), + XNode::Node(x) => *x, + XNode::Ns { .. } => return Ok(()), + }; + let count = interp.xml_node(x)?.children.len(); + for i in 0..count { + if let Some(c) = interp.xml_node(x)?.children.get(i).copied() { + self.add(interp, out, axis, test, XNode::Node(c))?; + } + } + Ok(()) + } + + fn ancestors(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let mut cur = parent_of(interp, n)?; + while let Some(p) = cur { + cur = parent_of(interp, &p)?; + self.add(interp, out, axis, test, p)?; + } + Ok(()) + } + + fn siblings(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let XNode::Node(x) = n else { return Ok(()) }; + let Some((p, at)) = child_position(interp, *x)? else { return Ok(()) }; + let count = interp.xml_node(p)?.children.len(); + let range: Box> = if axis == Axis::FollowingSibling { Box::new(at + 1..count) } else { Box::new((0..at).rev()) }; + for i in range { + if let Some(c) = interp.xml_node(p)?.children.get(i).copied() { + self.add(interp, out, axis, test, XNode::Node(c))?; + } + } + Ok(()) + } + + /// The node the following and preceding axes start from: an attribute's or a namespace + /// node's element, or the node itself. The flag is true for the first two. + fn start_of(interp: &Interp, n: &XNode) -> JsResult> { + Ok(match n { + XNode::Root(_) => None, + XNode::Ns { owner, .. } => Some((*owner, true)), + XNode::Node(x) => match interp.xml_node(*x)?.parent { + Some(p) if interp.xml_kind(*x)? == XmlKind::Attribute => Some((p, true)), + _ => Some((*x, false)), + }, + }) + } + + fn following(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let Some((mut cur, owned)) = Self::start_of(interp, n)? else { return Ok(()) }; + if owned { + self.under(interp, out, axis, test, cur)?; + } + while let Some((p, at)) = child_position(interp, cur)? { + let count = interp.xml_node(p)?.children.len(); + for i in at + 1..count { + if let Some(s) = interp.xml_node(p)?.children.get(i).copied() { + self.subtree(interp, out, axis, test, s)?; + } + } + cur = p; + } + Ok(()) + } + + fn preceding(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let Some((mut cur, _)) = Self::start_of(interp, n)? else { return Ok(()) }; + while let Some((p, at)) = child_position(interp, cur)? { + for i in (0..at).rev() { + let Some(s) = interp.xml_node(p)?.children.get(i).copied() else { continue }; + let mut part = Nodes::new(interp); + self.subtree(interp, &mut part, axis, test, s)?; + for x in part.list.into_iter().rev() { + out.push(interp, x)?; + } + } + cur = p; + } + Ok(()) + } + + fn attributes(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let XNode::Node(x) = n else { return Ok(()) }; + if interp.xml_kind(*x)? != XmlKind::Element { + return Ok(()); + } + let count = interp.xml_node(*x)?.attrs.len(); + for i in 0..count { + if let Some(a) = interp.xml_node(*x)?.attrs.get(i).copied() { + self.add(interp, out, axis, test, XNode::Node(a))?; + } + } + Ok(()) + } + + fn namespaces(&self, interp: &mut Interp, out: &mut Nodes, axis: Axis, test: &Test, n: &XNode) -> JsResult<()> { + let XNode::Node(x) = n else { return Ok(()) }; + if interp.xml_kind(*x)? != XmlKind::Element { + return Ok(()); + } + let xml = key("xml"); + let mut at = 0u32; + let mut has_xml = false; + for ns in scope_of(interp, Some(*x))? { + let Some(prefix) = ns.prefix else { continue }; + if prefix.is_empty() && ns.uri.is_empty() { + continue; + } + has_xml |= prefix == xml; + self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix, uri: ns.uri })?; + at += 1; + } + if !has_xml { + self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix: xml, uri: key(XML_URI) })?; + } + Ok(()) + } + + /// The nodes `axis` reaches from `n` that pass `test`, nearest first. + fn axis(&self, interp: &mut Interp, axis: Axis, test: &Test, n: &XNode) -> JsResult { + let mut out = Nodes::new(interp); + match axis { + Axis::Itself => self.add(interp, &mut out, axis, test, n.clone())?, + Axis::Child => self.children(interp, &mut out, axis, test, n)?, + Axis::Descendant => self.descendants(interp, &mut out, axis, test, n)?, + Axis::DescendantOrSelf => { + self.add(interp, &mut out, axis, test, n.clone())?; + self.descendants(interp, &mut out, axis, test, n)?; + } + Axis::Parent => { + if let Some(p) = parent_of(interp, n)? { + self.add(interp, &mut out, axis, test, p)?; + } + } + Axis::Ancestor => self.ancestors(interp, &mut out, axis, test, n)?, + Axis::AncestorOrSelf => { + self.add(interp, &mut out, axis, test, n.clone())?; + self.ancestors(interp, &mut out, axis, test, n)?; + } + Axis::FollowingSibling | Axis::PrecedingSibling => self.siblings(interp, &mut out, axis, test, n)?, + Axis::Following => self.following(interp, &mut out, axis, test, n)?, + Axis::Preceding => self.preceding(interp, &mut out, axis, test, n)?, + Axis::Attribute => self.attributes(interp, &mut out, axis, test, n)?, + Axis::Namespace => self.namespaces(interp, &mut out, axis, test, n)?, + } + Ok(out) + } + + // ---- string values and conversions ---- + + /// The string-value of a node (XPath 1.0 section 5): the text under an element or the root, + /// the value of any other node, and a namespace node's URI. + fn string_value(&mut self, interp: &mut Interp, n: &XNode) -> JsResult { + let x = match n { + XNode::Ns { uri, .. } => return Ok(Text::plain(interp, uri.clone())), + XNode::Root(t) => *t, + XNode::Node(x) => *x, + }; + let kind = interp.xml_kind(x)?; + if kind == XmlKind::Element { + return self.text_under(interp, x); + } + if matches!(n, XNode::Root(_)) && kind != XmlKind::Text { + return Ok(Text::plain(interp, empty())); + } + let value = interp.xml_node(x)?.value.clone(); + let units = flat_charged(interp, &value)?; + charge_units(interp, units.len())?; + Ok(Text::plain(interp, units)) + } + + fn text_under(&mut self, interp: &mut Interp, x: ObjId) -> JsResult { + let mut buf = TextBuf::new(interp); + let mut held = HeldBytes::new(interp); + let mut stack = Vec::new(); + push_held(interp, &mut held, &mut stack, (x, 0usize))?; + while let Some(&(p, at)) = stack.last() { + interp.use_fuel()?; + let Some(c) = interp.xml_node(p)?.children.get(at).copied() else { + stack.pop(); + continue; + }; + if let Some(frame) = stack.last_mut() { + frame.1 += 1; + } + match interp.xml_kind(c)? { + XmlKind::Text => { + let value = interp.xml_node(c)?.value.clone(); + let units = flat_charged(interp, &value)?; + buf.push(interp, &units)?; + } + XmlKind::Element => push_held(interp, &mut held, &mut stack, (c, 0))?, + _ => {} + } + } + Ok(buf.finish()) + } + + fn text_of(&mut self, interp: &mut Interp, v: Val) -> JsResult { + match v { + Val::Set(s) => match s.list.first() { + Some(n) => self.string_value(interp, n), + None => Ok(Text::plain(interp, empty())), + }, + Val::Bool(b) => Ok(Text::plain(interp, key(if b { "true" } else { "false" }))), + Val::Num(n) => Ok(Text::plain(interp, key(&num_text(n)))), + Val::Str(t) => { + // The caller reads the units, so they take fuel each time a value is used. + charge_units(interp, t.units.len())?; + Ok(t) + } + } + } + + /// The number a node's string-value stands for. + fn node_number(&mut self, interp: &mut Interp, n: &XNode) -> JsResult { + let t = self.string_value(interp, n)?; + str_num(interp, &t.units) + } + + fn number_of(&mut self, interp: &mut Interp, v: Val) -> JsResult { + match v { + Val::Num(n) => Ok(n), + Val::Bool(b) => Ok(f64::from(u8::from(b))), + other => { + let t = self.text_of(interp, other)?; + str_num(interp, &t.units) + } + } + } + + // ---- comparisons and operators ---- + + fn compare(&mut self, interp: &mut Interp, op: Bin, a: Val, b: Val) -> JsResult { + match (a, b) { + (Val::Set(x), Val::Set(y)) => self.compare_sets(interp, op, &x, &y), + (Val::Set(x), other) => self.compare_set(interp, op, &x, other), + (other, Val::Set(y)) => self.compare_set(interp, flip(op), &y, other), + (x, y) => self.compare_values(interp, op, x, y), + } + } + + fn compare_values(&mut self, interp: &mut Interp, op: Bin, a: Val, b: Val) -> JsResult { + if !matches!(op, Bin::Eq | Bin::Ne) { + let (x, y) = (self.number_of(interp, a)?, self.number_of(interp, b)?); + return Ok(compare_numbers(op, x, y)); + } + let equal = if matches!(a, Val::Bool(_)) || matches!(b, Val::Bool(_)) { + to_bool(&a) == to_bool(&b) + } else if matches!(a, Val::Num(_)) || matches!(b, Val::Num(_)) { + let (x, y) = (self.number_of(interp, a)?, self.number_of(interp, b)?); + return Ok(compare_numbers(op, x, y)); + } else { + self.text_of(interp, a)?.units == self.text_of(interp, b)?.units + }; + Ok(equal == (op == Bin::Eq)) + } + + /// Compares each node of `set` with `other`, which is not a node-set; `set` is on the left. + fn compare_set(&mut self, interp: &mut Interp, op: Bin, set: &Nodes, other: Val) -> JsResult { + if let Val::Str(t) = &other { + charge_units(interp, t.units.len())?; + } + let n = match other { + Val::Bool(b) => return self.compare_values(interp, op, Val::Bool(!set.list.is_empty()), Val::Bool(b)), + Val::Str(t) if matches!(op, Bin::Eq | Bin::Ne) => { + for node in &set.list { + if (self.string_value(interp, node)?.units == t.units) == (op == Bin::Eq) { + return Ok(true); + } + } + return Ok(false); + } + Val::Str(t) => str_num(interp, &t.units)?, + Val::Num(n) => n, + Val::Set(_) => return Err(internal()), + }; + for node in &set.list { + let v = self.node_number(interp, node)?; + if compare_numbers(op, v, n) { + return Ok(true); + } + } + Ok(false) + } + + fn strings_of(&mut self, interp: &mut Interp, held: &mut HeldBytes, set: &Nodes) -> JsResult> { + let mut out = HashSet::new(); + for node in &set.list { + let t = self.string_value(interp, node)?; + held.add(interp, ENTRY_BYTES.saturating_add(t.units.len().saturating_mul(2)))?; + out.insert(t.units); + } + Ok(out) + } + + /// The smallest and largest numbers the nodes' string-values stand for, leaving out NaN. + fn number_range(&mut self, interp: &mut Interp, set: &Nodes) -> JsResult> { + let mut range: Option<(f64, f64)> = None; + for node in &set.list { + let v = self.node_number(interp, node)?; + if !v.is_nan() { + range = Some(range.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); + } + } + Ok(range) + } + + fn compare_sets(&mut self, interp: &mut Interp, op: Bin, a: &Nodes, b: &Nodes) -> JsResult { + if a.list.is_empty() || b.list.is_empty() { + return Ok(false); + } + if matches!(op, Bin::Eq | Bin::Ne) { + let mut held = HeldBytes::new(interp); + let right = self.strings_of(interp, &mut held, b)?; + for node in &a.list { + let s = self.string_value(interp, node)?; + let found = if op == Bin::Eq { right.contains(&s.units) } else { right.len() > 1 || !right.contains(&s.units) }; + if found { + return Ok(true); + } + } + return Ok(false); + } + let (Some((a_lo, a_hi)), Some((b_lo, b_hi))) = (self.number_range(interp, a)?, self.number_range(interp, b)?) else { return Ok(false) }; + Ok(match op { + Bin::Lt | Bin::Le => compare_numbers(op, a_lo, b_hi), + _ => compare_numbers(op, a_hi, b_lo), + }) + } + + fn binary(&mut self, interp: &mut Interp, op: Bin, a: Val, b: Val) -> JsResult { + match op { + Bin::Union => { + let (Val::Set(mut x), Val::Set(y)) = (a, b) else { + return Err(interp.type_error("both sides of an XPath | must select nodes")); + }; + if x.list.is_empty() { + return Ok(Val::Set(y)); + } + for n in y.list { + x.push(interp, n)?; + } + Ok(Val::Set(self.sort(interp, x)?)) + } + Bin::Add | Bin::Sub | Bin::Mul | Bin::Div | Bin::Mod => { + let (x, y) = (self.number_of(interp, a)?, self.number_of(interp, b)?); + Ok(Val::Num(match op { + Bin::Add => x + y, + Bin::Sub => x - y, + Bin::Mul => x * y, + Bin::Div => x / y, + _ => x % y, + })) + } + Bin::Or | Bin::And => Err(internal()), + _ => Ok(Val::Bool(self.compare(interp, op, a, b)?)), + } + } + + // ---- functions ---- + + fn set_arg(interp: &mut Interp, v: Option, name: &str) -> JsResult { + match v { + Some(Val::Set(s)) => Ok(s), + _ => Err(interp.type_error(&format!("the XPath function {name} needs a node-set"))), + } + } + + fn text_arg(&mut self, interp: &mut Interp, v: Option, ctx: &Ctx) -> JsResult { + match v { + Some(v) => self.text_of(interp, v), + None => self.string_value(interp, &ctx.node), + } + } + + fn number_arg(&mut self, interp: &mut Interp, v: Option) -> JsResult { + let v = v.ok_or_else(internal)?; + self.number_of(interp, v) + } + + fn call(&mut self, interp: &mut Interp, f: Func, args: Vec, ctx: &Ctx) -> JsResult { + let mut args = args.into_iter(); + Ok(match f { + Func::Last => Val::Num(ctx.size as f64), + Func::Position => Val::Num(ctx.pos as f64), + Func::Count => Val::Num(Self::set_arg(interp, args.next(), "count")?.list.len() as f64), + Func::Id => Val::Set(Nodes::new(interp)), + Func::LocalName | Func::NamespaceUri | Func::Name => Val::Str(self.name_function(interp, f, args.next(), ctx)?), + Func::Sum => { + let set = Self::set_arg(interp, args.next(), "sum")?; + let mut total = 0.0; + for n in &set.list { + total += self.node_number(interp, n)?; + } + Val::Num(total) + } + Func::Boolean => Val::Bool(to_bool(&args.next().ok_or_else(internal)?)), + Func::Not => Val::Bool(!to_bool(&args.next().ok_or_else(internal)?)), + Func::True => Val::Bool(true), + Func::False => Val::Bool(false), + Func::Lang => { + let wanted = self.text_arg(interp, args.next(), ctx)?; + Val::Bool(self.lang(interp, &ctx.node, &wanted.units)?) + } + Func::Number => match args.next() { + Some(v) => Val::Num(self.number_of(interp, v)?), + None => Val::Num(self.node_number(interp, &ctx.node)?), + }, + Func::Floor => Val::Num(self.number_arg(interp, args.next())?.floor()), + Func::Ceiling => Val::Num(self.number_arg(interp, args.next())?.ceil()), + Func::Round => Val::Num(round(self.number_arg(interp, args.next())?)), + _ => return self.string_function(interp, f, args.collect(), ctx), + }) + } + + fn string_function(&mut self, interp: &mut Interp, f: Func, args: Vec, ctx: &Ctx) -> JsResult { + let mut texts = Vec::new(); + let mut held = HeldBytes::new(interp); + for v in args { + let t = self.text_of(interp, v)?; + push_held(interp, &mut held, &mut texts, t)?; + } + if texts.is_empty() && matches!(f, Func::String | Func::StringLength | Func::NormalizeSpace) { + texts.push(self.string_value(interp, &ctx.node)?); + } + if f == Func::String { + return Ok(Val::Str(texts.into_iter().next().ok_or_else(internal)?)); + } + let units = |at: usize| texts.get(at).map(|t| &*t.units).unwrap_or_default(); + Ok(match f { + Func::StringLength => Val::Num(char::decode_utf16(units(0).iter().copied()).count() as f64), + Func::StartsWith => Val::Bool(units(0).starts_with(units(1))), + Func::Contains => Val::Bool(find(interp, units(0), units(1))?.is_some()), + Func::SubstringBefore => { + let at = find(interp, units(0), units(1))?; + Val::Str(self.slice(interp, at.and_then(|i| units(0).get(..i)).unwrap_or_default())?) + } + Func::SubstringAfter => { + let at = find(interp, units(0), units(1))?; + Val::Str(self.slice(interp, at.and_then(|i| units(0).get(i + units(1).len()..)).unwrap_or_default())?) + } + Func::Concat => { + let mut buf = TextBuf::new(interp); + for t in &texts { + buf.push(interp, &t.units)?; + } + Val::Str(buf.finish()) + } + Func::NormalizeSpace => Val::Str(normalize_space(interp, units(0))?), + Func::Translate => Val::Str(translate(interp, units(0), units(1), units(2))?), + _ => return Err(internal()), + }) + } + + fn slice(&mut self, interp: &mut Interp, units: &[u16]) -> JsResult { + let mut buf = TextBuf::new(interp); + buf.push(interp, units)?; + Ok(buf.finish()) + } + + fn substring(&mut self, interp: &mut Interp, args: Vec) -> JsResult { + let mut args = args.into_iter(); + let text = self.text_of(interp, args.next().ok_or_else(internal)?)?; + let start = round(self.number_arg(interp, args.next())?); + let end = match args.next() { + Some(len) => start + round(self.number_of(interp, len)?), + None => f64::INFINITY, + }; + charge_units(interp, text.units.len())?; + let mut held = HeldBytes::new(interp); + // The code points take 4 bytes each, and the result up to twice its 2-byte units. + held.add(interp, text.units.len().saturating_mul(8))?; + let mut out = Vec::new(); + for (i, p) in code_points(&text.units).into_iter().enumerate() { + let position = (i + 1) as f64; + if position >= start && position < end { + push_point(&mut out, p); + } + } + Ok(Val::Str(Text { units: Rc::from(out), _held: held })) + } + + fn name_function(&mut self, interp: &mut Interp, f: Func, arg: Option, ctx: &Ctx) -> JsResult { + let node = match arg { + None => Some(ctx.node.clone()), + Some(Val::Set(s)) => s.list.into_iter().next(), + Some(_) => return Err(interp.type_error("the XPath name functions need a node-set")), + }; + let units = match node { + None | Some(XNode::Root(_)) => empty(), + Some(XNode::Ns { prefix, .. }) => { + if f == Func::NamespaceUri { + empty() + } else { + prefix + } + } + Some(XNode::Node(x)) => node_name(interp, f, x)?, + }; + Ok(Text::plain(interp, units)) + } + + /// Whether the context node's language, from the nearest `xml:lang` attribute on it or an + /// ancestor, is `wanted` or a sublanguage of it, ignoring case. + fn lang(&mut self, interp: &mut Interp, n: &XNode, wanted: &[u16]) -> JsResult { + let mut cur = match n { + XNode::Root(_) => None, + XNode::Node(x) => Some(*x), + XNode::Ns { owner, .. } => Some(*owner), + }; + let xml = key(XML_URI); + while let Some(x) = cur { + interp.use_fuel()?; + let node = interp.xml_node(x)?; + let parent = node.parent; + let count = node.attrs.len(); + for i in 0..count { + interp.use_fuel()?; + let Some(a) = interp.xml_node(x)?.attrs.get(i).copied() else { break }; + let attr = interp.xml_node(a)?; + if attr.name.as_ref().is_some_and(|q| name_uri(q) == &*xml && units_are(&q.local, "lang")) { + let value = attr.value.clone(); + let value = flat_charged(interp, &value)?; + let head = value.get(..wanted.len()).unwrap_or_default(); + return Ok(same_ignoring_case(head, wanted) && (value.len() == wanted.len() || value.get(wanted.len()) == Some(&DASH))); + } + } + cur = parent; + } + Ok(false) + } + + // ---- running ---- + + fn task(&mut self, interp: &mut Interp, t: Task) -> JsResult<()> { + push_held(interp, &mut self.held, &mut self.tasks, t) + } + + fn val(&mut self, interp: &mut Interp, v: Val) -> JsResult<()> { + push_held(interp, &mut self.held, &mut self.vals, v) + } + + fn pop(&mut self) -> JsResult { + self.vals.pop().ok_or_else(internal) + } + + fn root_of(interp: &mut Interp, n: &XNode) -> JsResult { + Ok(match n { + XNode::Root(t) => XNode::Root(*t), + XNode::Node(x) => XNode::Root(top_of(interp, *x)?), + XNode::Ns { owner, .. } => XNode::Root(top_of(interp, *owner)?), + }) + } + + fn bound_value(&mut self, interp: &mut Interp, at: usize) -> JsResult { + Ok(match self.bound.get(at).ok_or_else(internal)? { + Bound::Bool(b) => Val::Bool(*b), + Bound::Num(n) => Val::Num(*n), + Bound::Str(s) => Val::Str(Text::plain(interp, s.clone())), + Bound::Set(list) => { + let list = list.clone(); + let mut nodes = Nodes::new(interp); + nodes.held.add(interp, list.len().saturating_mul(size_of::()))?; + nodes.list = list; + Val::Set(nodes) + } + }) + } + + fn eval(&mut self, interp: &mut Interp, e: usize, ctx: Ctx) -> JsResult<()> { + let parsed = self.parsed; + match parsed.exprs.get(e).ok_or_else(internal)? { + Expr::Num(n) => self.val(interp, Val::Num(*n)), + Expr::Lit(s) => { + let t = Text::plain(interp, s.clone()); + self.val(interp, Val::Str(t)) + } + Expr::Var(at) => { + let v = self.bound_value(interp, *at)?; + self.val(interp, v) + } + Expr::Neg(a) => { + self.task(interp, Task::Neg)?; + self.task(interp, Task::Eval(*a, ctx)) + } + Expr::Bin(op @ (Bin::And | Bin::Or), a, b) => { + self.task(interp, Task::Logic { and: *op == Bin::And, rhs: *b, ctx: ctx.clone() })?; + self.task(interp, Task::Eval(*a, ctx)) + } + Expr::Bin(op, a, b) => { + self.task(interp, Task::Bin(*op))?; + self.task(interp, Task::Eval(*b, ctx.clone()))?; + self.task(interp, Task::Eval(*a, ctx)) + } + Expr::Call(f, args) => { + self.task(interp, Task::Call(*f, args.len(), ctx.clone()))?; + for a in args.iter().rev() { + self.task(interp, Task::Eval(*a, ctx.clone()))?; + } + Ok(()) + } + Expr::Path { filter: Some((primary, _)), .. } => { + self.task(interp, Task::PathStart(e))?; + self.task(interp, Task::Eval(*primary, ctx)) + } + Expr::Path { filter: None, absolute, steps } => { + let start = if *absolute { Self::root_of(interp, &ctx.node)? } else { ctx.node }; + let mut inputs = Nodes::new(interp); + inputs.push(interp, start)?; + if steps.is_empty() { + return self.val(interp, Val::Set(inputs)); + } + let first = self.step_axis(interp, e, 1, &inputs.list.first().cloned().ok_or_else(internal)?)?; + let run = self.new_run(interp, e, 1, inputs, first); + self.run_path(interp, Box::new(run)) + } + } + } + + fn new_run(&self, interp: &Interp, path: usize, stage: usize, inputs: Nodes, cur: Nodes) -> PathRun { + PathRun { + path, + stage, + inputs, + ci: 0, + cur, + pred: 0, + at: 0, + kept: Nodes::new(interp), + waiting: false, + out: Nodes::new(interp), + seen: HashSet::new(), + seen_held: HeldBytes::new(interp), + } + } + + fn step(&mut self, interp: &mut Interp, t: Task) -> JsResult<()> { + match t { + Task::Eval(e, ctx) => self.eval(interp, e, ctx), + Task::Bin(op) => { + let b = self.pop()?; + let a = self.pop()?; + let v = self.binary(interp, op, a, b)?; + self.val(interp, v) + } + Task::Neg => { + let a = self.pop()?; + let n = self.number_of(interp, a)?; + self.val(interp, Val::Num(-n)) + } + Task::Logic { and, rhs, ctx } => { + let left = to_bool(&self.pop()?); + if left != and { + return self.val(interp, Val::Bool(left)); + } + self.task(interp, Task::Bool)?; + self.task(interp, Task::Eval(rhs, ctx)) + } + Task::Bool => { + let v = to_bool(&self.pop()?); + self.val(interp, Val::Bool(v)) + } + Task::Call(f, n, ctx) => { + let args = self.vals.split_off(self.vals.len().checked_sub(n).ok_or_else(internal)?); + let v = if f == Func::Substring { self.substring(interp, args)? } else { self.call(interp, f, args, &ctx)? }; + self.val(interp, v) + } + Task::PathStart(e) => { + let Val::Set(set) = self.pop()? else { + return Err(interp.type_error("an XPath predicate or step follows a value that is not a node-set")); + }; + let run = self.new_run(interp, e, 0, Nodes::new(interp), set); + self.run_path(interp, Box::new(run)) + } + Task::Path(run) => self.run_path(interp, run), + } + } + + /// The predicates of a path's stage, and its step for a stage after the filter's. + fn stage_of(&self, path: usize, stage: usize) -> JsResult<(&'p [usize], Option<&'p Step>)> { + let parsed = self.parsed; + let Some(Expr::Path { filter, steps, .. }) = parsed.exprs.get(path) else { return Err(internal()) }; + match stage.checked_sub(1) { + None => Ok((filter.as_ref().map(|(_, p)| p.as_slice()).unwrap_or_default(), None)), + Some(s) => { + let step = steps.get(s).ok_or_else(internal)?; + Ok((&step.preds, Some(step))) + } + } + } + + fn step_axis(&self, interp: &mut Interp, path: usize, stage: usize, n: &XNode) -> JsResult { + let (_, step) = self.stage_of(path, stage)?; + let step = step.ok_or_else(internal)?; + self.axis(interp, step.axis, &step.test, n) + } + + /// Runs a path until a predicate needs evaluating, which it schedules before itself, or until + /// the path's node-set is complete, which it pushes. + fn run_path(&mut self, interp: &mut Interp, mut r: Box) -> JsResult<()> { + loop { + interp.use_fuel()?; + if r.waiting { + r.waiting = false; + let v = self.pop()?; + let keep = match v { + Val::Num(n) => n == (r.at + 1) as f64, + other => to_bool(&other), + }; + if keep && let Some(n) = r.cur.list.get(r.at).cloned() { + r.kept.push(interp, n)?; + } + r.at += 1; + } + let (preds, _) = self.stage_of(r.path, r.stage)?; + if let Some(&pred) = preds.get(r.pred) { + if let Some(node) = r.cur.list.get(r.at).cloned() { + let ctx = Ctx { node, pos: r.at + 1, size: r.cur.list.len() }; + r.waiting = true; + self.task(interp, Task::Path(r))?; + return self.task(interp, Task::Eval(pred, ctx)); + } + r.cur = replace(&mut r.kept, Nodes::new(interp)); + r.pred += 1; + r.at = 0; + continue; + } + if !self.next_context(interp, &mut r)? { + return Ok(()); + } + } + } + + /// Adds the current context's nodes to the stage's result and moves to the next context or + /// stage. Returns false when the path is complete and its node-set has been pushed. + fn next_context(&mut self, interp: &mut Interp, r: &mut PathRun) -> JsResult { + let cur = replace(&mut r.cur, Nodes::new(interp)); + if r.inputs.list.len() > 1 { + for n in cur.list { + if !r.seen.contains(&n) { + r.seen_held.add(interp, ENTRY_BYTES)?; + r.seen.insert(n.clone()); + r.out.push(interp, n)?; + } + } + } else { + r.out = cur; + } + r.ci += 1; + if let Some(n) = r.inputs.list.get(r.ci).cloned() { + r.cur = self.step_axis(interp, r.path, r.stage, &n)?; + r.pred = 0; + r.at = 0; + return Ok(true); + } + let out = replace(&mut r.out, Nodes::new(interp)); + let (_, step) = self.stage_of(r.path, r.stage)?; + let done = if r.inputs.list.len() > 1 { + self.sort(interp, out)? + } else if step.is_some_and(|s| s.axis.reverse()) { + let mut out = out; + out.list.reverse(); + out + } else { + out + }; + r.seen.clear(); + r.seen_held = HeldBytes::new(interp); + r.stage += 1; + let more = self.stage_of(r.path, r.stage).is_ok(); + let Some(first) = done.list.first().cloned().filter(|_| more) else { + self.val(interp, Val::Set(done))?; + return Ok(false); + }; + r.inputs = done; + r.ci = 0; + r.cur = self.step_axis(interp, r.path, r.stage, &first)?; + r.pred = 0; + r.at = 0; + Ok(true) + } + + fn run(&mut self, interp: &mut Interp, e: usize, ctx: Ctx) -> JsResult { + self.tasks.clear(); + self.vals.clear(); + self.task(interp, Task::Eval(e, ctx))?; + while let Some(t) = self.tasks.pop() { + interp.use_fuel()?; + self.step(interp, t)?; + } + let v = self.pop()?; + if !self.vals.is_empty() { + return Err(internal()); + } + Ok(v) + } + + /// Binds the expression's prefixes to the namespaces in scope on `x`. + fn resolve_prefixes(&mut self, interp: &mut Interp, x: ObjId) -> JsResult<()> { + self.uris.clear(); + if self.parsed.prefixes.is_empty() { + return Ok(()); + } + let scope = scope_of(interp, Some(x))?; + let parsed = self.parsed; + for p in &parsed.prefixes { + let uri = if units_are(p, "xml") { + key(XML_URI) + } else { + match scope.iter().find(|ns| ns.prefix.as_ref() == Some(p)) { + Some(ns) if !ns.uri.is_empty() => ns.uri.clone(), + _ => { + let shown = String::from_utf16_lossy(p); + return Err(interp.type_error(&format!("the XPath prefix {shown} is not bound to a namespace"))); + } + } + }; + self.held.add(interp, ENTRY_BYTES)?; + self.uris.insert(p.clone(), uri); + } + Ok(()) + } + + /// The nodes the expression selects with `x` as the context node. + fn select(&mut self, interp: &mut Interp, x: ObjId) -> JsResult> { + self.resolve_prefixes(interp, x)?; + let root = self.parsed.root; + let Val::Set(set) = self.run(interp, root, Ctx { node: XNode::Node(x), pos: 1, size: 1 })? else { + return Err(interp.type_error("the XPath expression does not evaluate to a node-set")); + }; + let mut out = Vec::new(); + let mut held = HeldBytes::new(interp); + for n in set.list { + match n { + XNode::Node(id) => push_held(interp, &mut held, &mut out, id)?, + XNode::Root(_) => return Err(interp.type_error("the XPath expression selects the root node, which is not an XML value")), + XNode::Ns { .. } => return Err(interp.type_error("the XPath expression selects a namespace node, which is not an XML value")), + } + } + Ok(out) + } +} + +fn node_name(interp: &mut Interp, f: Func, x: ObjId) -> JsResult { + let node = interp.xml_node(x)?; + let (kind, parent) = (node.kind, node.parent); + let Some(name) = node.name.clone() else { return Ok(empty()) }; + match (f, kind) { + (_, XmlKind::Text | XmlKind::Comment) => Ok(empty()), + (Func::NamespaceUri, XmlKind::Pi) => Ok(empty()), + (Func::NamespaceUri, _) => Ok(Rc::from(name_uri(&name))), + (Func::LocalName, _) | (_, XmlKind::Pi) => Ok(name.local), + _ => qualified_name(interp, x, parent, &name, kind == XmlKind::Attribute), + } +} + +/// An element's or attribute's name as a QName, with a prefix declared for its namespace. +fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option, name: &XmlName, attribute: bool) -> JsResult { + let uri = name_uri(name); + if uri.is_empty() { + return Ok(name.local.clone()); + } + let prefix = if units_are(uri, XML_URI) { + key("xml") + } else { + match &name.prefix { + Some(p) if !(attribute && p.is_empty()) => p.clone(), + _ => { + let scope = scope_of(interp, if attribute { parent } else { Some(x) })?; + let usable = |ns: &XmlNs| *ns.uri == *uri && ns.prefix.as_ref().is_some_and(|p| !(attribute && p.is_empty())); + scope.into_iter().find(usable).and_then(|ns| ns.prefix).unwrap_or_else(empty) + } + } + }; + if prefix.is_empty() { + return Ok(name.local.clone()); + } + let mut units = prefix.to_vec(); + units.push(COLON); + units.extend_from_slice(&name.local); + Ok(Rc::from(units)) +} + +/// The first index where `needle` occurs in `hay`. Every position tried takes fuel. +fn find(interp: &mut Interp, hay: &[u16], needle: &[u16]) -> JsResult> { + string_builtins::find(interp, hay, needle, 0) +} + +fn normalize_space(interp: &mut Interp, units: &[u16]) -> JsResult { + let mut buf = TextBuf::new(interp); + for word in units.split(|&c| is_xml_space(c)).filter(|w| !w.is_empty()) { + if !buf.units.is_empty() { + buf.push(interp, &[0x20])?; + } + buf.push(interp, word)?; + } + Ok(buf.finish()) +} + +fn translate(interp: &mut Interp, units: &[u16], from: &[u16], to: &[u16]) -> JsResult { + charge_units(interp, units.len() + from.len() + to.len())?; + let mut held = HeldBytes::new(interp); + held.add(interp, from.len().saturating_add(units.len()).saturating_add(to.len()).saturating_mul(ENTRY_BYTES))?; + let to = code_points(to); + let mut map: HashMap> = HashMap::new(); + for (i, p) in code_points(from).into_iter().enumerate() { + map.entry(p).or_insert_with(|| to.get(i).copied()); + } + let mut out = Vec::new(); + for p in code_points(units) { + match map.get(&p) { + Some(Some(t)) => push_point(&mut out, *t), + Some(None) => {} + None => push_point(&mut out, p), + } + } + Ok(Text { units: Rc::from(out), _held: held }) +} + +/// Reads the variables the expression names from `variables`. +fn bind(interp: &mut Interp, held: &mut HeldBytes, parsed: &Parsed, variables: &Value) -> JsResult> { + let mut out = Vec::new(); + for name in &parsed.vars { + let v = match variables { + Value::Object(o) if interp.has_property(*o, name)? => interp.get_from(*o, name, variables)?, + _ => Value::Undefined, + }; + if matches!(v, Value::Undefined) { + let shown = String::from_utf16_lossy(name); + return Err(interp.type_error(&format!("the XPath variable ${shown} is not bound"))); + } + interp.temp_roots.push(v.clone()); + let b = match (interp.classify(&v), &v) { + (Xv::Node(n), _) => Bound::Set(vec![XNode::Node(n)]), + (Xv::List(l), _) => { + // A later getter may change the list, so its items are held as roots themselves. + let count = interp.xml_list(l)?.items.len(); + held.add(interp, count.saturating_mul(size_of::() + size_of::() + size_of::()))?; + let items = interp.xml_list(l)?.items.clone(); + interp.temp_roots.extend(items.iter().map(|&n| Value::Object(n))); + Bound::Set(items.into_iter().map(XNode::Node).collect()) + } + (Xv::Other, Value::Bool(b)) => Bound::Bool(*b), + (Xv::Other, Value::Number(n)) => Bound::Num(*n), + (Xv::Other, _) => { + let s = interp.to_str(&v)?; + Bound::Str(flat_charged(interp, &s)?) + } + }; + push_held(interp, held, &mut out, b)?; + } + Ok(out) +} + +/// The nodes an expression runs on: the XML value itself, or each element of an XMLList. +fn contexts(interp: &mut Interp, held: &mut HeldBytes, this: &Value) -> JsResult> { + match interp.classify(this) { + Xv::Node(n) => Ok(vec![n]), + Xv::List(l) => { + let count = interp.xml_list(l)?.items.len(); + let mut out = Vec::new(); + for i in 0..count { + interp.use_fuel()?; + let Some(item) = interp.xml_list(l)?.items.get(i).copied() else { break }; + if interp.xml_kind(item)? == XmlKind::Element { + push_held(interp, held, &mut out, item)?; + } + } + Ok(out) + } + Xv::Other => Err(interp.type_error("the method needs an XML value")), + } +} + +/// `xpath(expression[, variables])`: the nodes the XPath 1.0 `expression` selects with this XML +/// value as the context node, or, for an XMLList, with each of its elements in turn, as one +/// XMLList. Each property of `variables` binds the variable of its name. +pub(crate) fn xpath(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if matches!(interp.classify(&this), Xv::Other) { + return Err(interp.type_error("the method needs an XML value")); + } + let Value::String(source) = arg(args, 0) else { + return Err(interp.type_error("xpath needs the expression as a string")); + }; + let variables = arg(args, 1); + if !matches!(variables, Value::Undefined | Value::Object(_)) { + return Err(interp.type_error("xpath needs its variables as an object")); + } + interp.rooted(&[this.clone(), variables.clone()], |i| { + let units = flat_charged(i, &source)?; + let parsed = parse(i, &units)?; + let mut held = HeldBytes::new(i); + let bound = bind(i, &mut held, &parsed, &variables)?; + let items = contexts(i, &mut held, &this)?; + let out = i.new_xml_list(None, None)?; + i.xml_keep(out); + let mut ev = Ev::new(i, &parsed, bound)?; + for item in items { + for id in ev.select(i, item)? { + i.list_push(out, id)?; + } + } + Ok(Value::Object(out)) + }) +} diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 00e914ddba..69c7b5ba0e 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -56,6 +56,24 @@ fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> { p.get(k).and_then(Value::as_str) } +/// An optional param read with `read`: none when it is omitted or null, else an error naming the +/// key when `read` gets nothing from its value. +fn opt(p: &Value, k: &str, read: impl Fn(&Value) -> Option, what: &str) -> Result, String> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => read(v).map(Some).ok_or_else(|| format!("`{k}` must be {what}")), + } +} + +fn opt_bool(p: &Value, k: &str) -> Result, String> { + opt(p, k, Value::as_bool, "true or false") +} + +/// A pointer packet's `mods`: none when omitted or null, else an object of booleans. +fn packet_mods(p: &Value) -> Result, String> { + opt(p, "mods", |m| m.as_object().and_then(|_| serde_json::from_value(m.clone()).ok()), "an object of true or false values") +} + pub(crate) fn pointer_kind(k: &str) -> Option { Some(match k { "down" => PointerKind::Down, @@ -210,28 +228,30 @@ 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 base = packet_mods(p)?.unwrap_or_default(); let default = PointerEvent::json_backquote(p, false)?; let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::, _>>()?; + // Every event is read before any is sent, so a malformed packet sends none of them. + let read = events + .iter() + .zip(held) + .map(|(e, backquote)| { + let mods = packet_mods(e)?.unwrap_or(base); + 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)"))?; + PointerEvent::json_check(e)?; + if s(e, "space") == Some("screen") { + return Err("screen-space pointer events need the desktop app; use document coordinates".to_string()); + } + 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`")?; + Ok((e, kind, Point::new(x, y), mods, backquote)) + }) + .collect::, String>>()?; self.ensure_document(); let mut requests = vec![]; - 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") { - return Err("screen-space pointer events need the desktop app; use document coordinates".into()); - } - 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 ev = PointerEvent { - kind, - pos: Point::new(x, y), - mods, - backquote, - pressure: PointerEvent::json_pressure(e), - pen: PointerEvent::json_pen(e), - }; + for (e, kind, pos, mods, backquote) in read { + let ev = PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen: PointerEvent::json_pen(e) }; let reqs = self.session.pointer(&ev, self.view).map_err(|e| e.to_string())?; self.apply_ui_requests(reqs, &mut requests)?; // With no frames to show the highlight or apply an edit in later, each event waits for @@ -253,8 +273,8 @@ impl Headless { fn key(&mut self, p: &Value) -> Result { let key = s(p, "key").ok_or("missing `key`")?; - let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false); - let mods = Mods { shift: b("shift"), alt: b("alt"), cmd: b("cmd"), ctrl: b("ctrl"), ..Mods::default() }; + let b = |n: &str| opt_bool(p, n).map(|on| on.unwrap_or(false)); + let mods = Mods { shift: b("shift")?, alt: b("alt")?, cmd: b("cmd")?, ctrl: b("ctrl")?, ..Mods::default() }; // A letter reaches the tool only when the tool claims it without Cmd, Ctrl or Alt (E while // a selection marquee is dragged); otherwise it is a shortcut. let mut tk = tool_key(key); @@ -296,16 +316,18 @@ impl Headless { } fn render(&mut self, p: &Value) -> Result { + let idx = opt(p, "artboard", |v| v.as_u64().and_then(|i| usize::try_from(i).ok()), "a whole number of 0 or more")?.unwrap_or(0); + let scale = opt(p, "scale", Value::as_f64, "a number")?.unwrap_or(1.0).clamp(0.01, 16.0); + let trace_views = opt_bool(p, "traceViews")? == Some(true); + let data = opt_bool(p, "data")? == Some(true); let st = self.session.active().ok_or("no document")?; let doc = st.doc.clone(); - let idx = p.get("artboard").and_then(Value::as_u64).unwrap_or(0) as usize; let r = doc.artboards.get(idx).map(|a| a.rect).ok_or("no such artboard")?; - let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(0.01, 16.0); vectorcraft_render::raster_size(r, scale)?; // Rendered with the options of a PNG export on white, so its pixels are the exported file's. // `traceViews: true` draws Image Trace objects as their View shows them, as the canvas does. let mut opts = RasterExportOptions { background: Some([255; 3]), ..Default::default() }.render_options(RasterFormat::Png); - opts.trace_views = p.get("traceViews").and_then(Value::as_bool) == Some(true); + opts.trace_views = trace_views; let img = self.renderer.render_region_with(&doc, r, scale, &opts); // A cancelled render stops drawing: the picture is not whole and is not written. vectorcraft_engine::cancel::check().map_err(|e| e.to_string())?; @@ -317,7 +339,7 @@ impl Headless { vectorcraft_format::write_atomic(std::path::Path::new(path), &png).map_err(|e| format!("write {path}: {e}"))?; out["path"] = json!(path); // `data: true` asks for the image as well as the file. - if p.get("data").and_then(Value::as_bool) == Some(true) { + if data { out["pngBase64"] = json!(vectorcraft_format::base64_encode(&png)); } } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index d7de8dd7fb..ffb6fcb93e 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1452,6 +1452,44 @@ fn headless_backend_methods() { assert!(h.call("ui.resize", json!({})).is_err()); } +/// The headless key, pointer and screenshot calls refuse a value of the wrong type and change +/// nothing; omitting it or giving null keeps its default. +#[test] +fn headless_methods_refuse_params_of_the_wrong_type() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 200}})).unwrap(); + h.call("ui.tool.select", json!({"tool": "rectangle"})).unwrap(); + let before = h.call("document.json", json!({})).unwrap(); + let drag = |mods: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60, "mods": mods}, {"kind": "up", "x": 60, "y": 60}]}); + let after_rect = |last: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60}, {"kind": "up", "x": 60, "y": 60}, last]}); + for (method, params, key) in [ + ("ui.render", json!({"artboard": "0"}), "artboard"), + ("ui.render", json!({"scale": "2"}), "scale"), + ("ui.render", json!({"traceViews": 1}), "traceViews"), + ("ui.screenshot", json!({"data": "yes", "path": "x.png"}), "data"), + ("ui.key", json!({"key": "Delete", "shift": "true"}), "shift"), + ("ui.pointer", drag(json!({"shift": "yes"})), "mods"), + ("ui.pointer", json!({"mods": 1, "events": []}), "mods"), + ("ui.pointer", drag(json!([true])), "mods"), + // A whole rectangle comes before the malformed event, and none of it is drawn. + ("ui.pointer", after_rect(json!({"kind": "move", "x": "bad", "y": 0})), "x"), + ("ui.pointer", after_rect(json!({"kind": "wiggle", "x": 0, "y": 0})), "wiggle"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "pressure": "bad"})), "pressure"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "holdMs": true})), "holdMs"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "tiltX": "5"})), "tiltX"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "rotation": [0]})), "rotation"), + ("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "space": "screeen"})), "space"), + ] { + let e = h.call(method, params.clone()).unwrap_err(); + assert!(e.contains(&format!("`{key}`")), "{method} {params}: {e}"); + } + assert_eq!(h.call("document.json", json!({})).unwrap(), before, "a refused call changes nothing"); + let r = h.call("ui.render", json!({"artboard": null, "scale": null, "traceViews": null})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(300), Some(200))); + h.call("ui.pointer", drag(Value::Null)).unwrap(); + assert_ne!(h.call("document.json", json!({})).unwrap(), before, "null mods keep the packet's"); +} + // ---------- workflow tools ---------- fn id_of(result: &Value) -> u64 { @@ -1966,6 +2004,10 @@ fn drawing_gestures_snap_to_smart_guides() { let b = &made["bounds"]; [&b["x"], &b["y"], &b["width"], &b["height"]].map(|v| v.as_f64().unwrap()) }; + // The rectangle drawn first stays selected, and the press lands on its box's corner handle, + // which would scale it instead of drawing. + let r = call(&mut s, 30, "run_command", json!({"command": "select.none", "params": {}})); + assert_eq!(r["isError"], false, "{r}"); let events = json!([{"kind": "move", "x": 202, "y": 203}, {"kind": "down", "x": 202, "y": 203}, {"kind": "drag", "x": 330, "y": 341}, {"kind": "up", "x": 330, "y": 341}]); assert_eq!(bounds(&mut s, 3, events, "rectangle"), [200.0, 200.0, 130.0, 141.0]); let r = call(&mut s, 5, "run_command", json!({"command": "select.none", "params": {}})); diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index 00ff3a2d77..54baeeb0c3 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -77,6 +77,7 @@ fn export_tool_lists_engine_formats_and_options() { "eps", "emf", "wmf", + "hpgl", "tga", "psd" ]) diff --git a/crates/mcp/src/tests/pen.rs b/crates/mcp/src/tests/pen.rs index ae89a3b484..570b79496f 100644 --- a/crates/mcp/src/tests/pen.rs +++ b/crates/mcp/src/tests/pen.rs @@ -46,7 +46,8 @@ fn cmd_with_the_pen_edits_the_path_being_drawn() { assert_eq!(paths(&h).iter().map(Vec::len).collect::>(), [3], "the same path, three anchors"); } -/// #501: a drag out of the first anchor closes the path, shaping the closing curve. +/// #501: a drag out of the first anchor closes the path, shaping the closing curve. #6634: the first +/// anchor was placed by a click, so it stays a corner and the first segment keeps its shape. #[test] fn a_drag_from_the_first_anchor_closes_the_path() { let mut h = Headless::new(); @@ -62,5 +63,6 @@ fn a_drag_from_the_first_anchor_closes_the_path() { d.walk(|n| closed.extend(n.path_data().map(|p| p.is_closed()))); assert_eq!(closed, [true], "one path, closed"); let first = paths(&h)[0][0]; - assert_eq!((first.h_in, first.h_out), (vectorcraft_geom::Point::new(40.0, 348.0), vectorcraft_geom::Point::new(160.0, 252.0))); + assert_eq!((first.h_in, first.h_out), (vectorcraft_geom::Point::new(40.0, 348.0), vectorcraft_geom::Point::new(100.0, 300.0))); + assert_eq!(first.kind, vectorcraft_geom::AnchorKind::Corner); } diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 2480f4ad69..d4d69c945f 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -259,7 +259,7 @@ pub fn tool_definitions() -> Vec { "radius1": num("Star outer radius"), "radius2": num("Star inner radius"), "points": {"type": "integer", "minimum": 3, "description": "Star points (default 5)"}, - "rotation": num("Rotation in degrees (polygon/star)"), + "rotation": num("Rotation in degrees clockwise about the centre (rectangle/ellipse: 0 upright; polygon/star: 0 a corner or point straight up)"), "x1": num("Line start x"), "y1": num("Line start y"), "x2": num("Line end x"), @@ -393,14 +393,14 @@ pub fn tool_definitions() -> Vec { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( 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 (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)"), + "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, WMF and HP-GL: one, or one file each with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"}, @@ -471,12 +471,12 @@ pub fn tool_definitions() -> Vec { "ids": {"type": "array", "items": {"type": "integer"}}, "dx": num("Move right"), "dy": num("Move down"), - "rotate": num("Rotation in degrees"), + "rotate": num("Rotation in degrees counter-clockwise"), "scale": num("Uniform scale in %"), "scaleX": num("Horizontal scale in %"), "scaleY": num("Vertical scale in %"), "reflect": {"type": "string", "enum": ["vertical", "horizontal"]}, - "shear": num("Shear angle in degrees (horizontal axis)"), + "shear": num("Shear angle in degrees (horizontal axis: positive moves the top to the right, turning the vertical edges clockwise)"), "origin": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "copy": {"type": "boolean"}, }), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index e15244580d..b07964b225 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -471,6 +471,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{edge: \"top\"|\"bottom\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do; kept with the workspace; another edge is an error and changes nothing; returns {edge}", ), + ( + "window.control.options", + "Control Bar Options", + "", + "{group: \"snapping\"|\"anchors\"|\"toolOptions\"|\"objectOptions\"|\"imageOptions\"|\"fillStroke\"|\"opacity\"|\"graphicStyle\"|\"character\"|\"paragraph\"|\"verticalAlignment\"|\"alignDistribute\"|\"transform\"|\"artboardOptions\"|\"documentOptions\", visible?: bool} turn a group of the Control bar's options on (true), off (false) or toggle it (omitted), as the bar's panel menu does; a group that is off stays out of the bar even while its tool or object is selected, and one that is on shows only while the selection or the tool calls for it; every group starts on; kept with the workspace; another group or a `visible` that is not true or false is an error and changes nothing; returns {group, visible}", + ), ("window.toolbar", "Tools", "", "{}"), ( "window.toolbarColumns", @@ -628,6 +634,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{collapsed?: bool} collapse every expanded dock column to icons (true), expand the outer dock column, Properties | Layers | Libraries (false), or toggle the outer column (omitted), as the double arrow at the top of the dock does; returns the new state", ), + ( + "window.learn", + "Learn", + "", + "{show?: bool} show (true), hide (false) or toggle (omitted or null) the Learn panel, as Window › Learn and the app bar's Explore tutorials button do; any other value is an error and changes nothing; returns whether the panel shows", + ), + ( + "learn.list", + "List Tutorials", + "", + "{} the Learn panel's skills in the order its Skills tab lists them: {skills: [{id, title, tutorials: [{id, title, steps: number of steps}]}]}", + ), + ( + "learn.show", + "Show Tutorial", + "", + "{tutorial: id (see learn.list)} show the Learn panel on its Skills tab with that tutorial's numbered steps, as choosing its skill and then the tutorial does; a missing, non-string or unknown id is an error and changes nothing; returns {skill, tutorial, title, steps: [text]}", + ), ("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"), ( "window.workspace", @@ -742,6 +766,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open the Safe Mode dialog (dialog `safeMode`): whether VectorCraft is in Safe Mode, and the disabled plug-ins, each with Enable on Re-launch (engine: plugin.setEnabled). Closing it leaves Safe Mode as it is; Safe Mode is chosen at launch (--safe-mode, or the choice after a launch that stopped while a plug-in was loading, dialog `pluginStopped`)", ), + ( + "help.copyTroubleshootingInfo", + "Copy Troubleshooting Info", + "", + "{} put text for a bug report on the clipboard: the version, and in the desktop app the platform, the window system, the graphics processor, the commands and frame times of the last few frames, and the hang reports of this session and the session before (no document contents or file paths) → {chars}", + ), ("app.quit", "Quit VectorCraft", "Cmd+Q", "{}"), ( "ui.swatchOptions", @@ -803,6 +833,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} clear the settings of the section shown, Basic Character Formats, Advanced Character Formats, Character Color or OpenType Features, in the open Character Style Options or New Character Style dialog; available only on those sections", ), + ( + "ui.paraStyleOptions", + "Paragraph Style Options", + "", + "{name} open Paragraph Style Options (dialog `paraStyleOptions`, sections General, Basic Paragraph Formats, Composition, Hyphenation and Justification); OK runs paraStyle.edit with name, to and sparse attrs in one undo step; Cancel restores a live preview", + ), + ( + "ui.paraStyleOptions.resetPanel", + "Reset Panel", + "", + "{} clear the settings of the section shown, Basic Paragraph Formats, Composition, Hyphenation or Justification, in the open Paragraph Style Options or New Paragraph Style dialog; available only on those sections", + ), ( "ui.newCharStyle", "New Character Style…", @@ -813,7 +855,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newParaStyle", "New Paragraph Style…", "", - "{} open New Paragraph Style (dialog `newTextStyle`, field `name`, filled in with the name paraStyle.new {} would give the style), what Alt-clicking the Paragraph Styles panel's New button opens; OK runs paraStyle.new with the name and the paragraph of the Type tool's selection (else the selected type) as it was when the dialog opened; Cancel adds no style", + "{} open New Paragraph Style (dialog `newTextStyle`, field `name`, filled in with the name paraStyle.new {} would give the style), what Alt-clicking the Paragraph Styles panel's New button opens; the dialog also has the sections of Paragraph Style Options, filled in from the paragraph of the Type tool's selection (else the selected type) as it was when the dialog opened; OK runs paraStyle.new with the name and those attrs; Cancel adds no style", ), ( "ui.symbolOptions", @@ -1194,7 +1236,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPanel", "Color Panel Options", "", - "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), and Show Options (true) or Hide Options (false); both are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options) → {mode (null: none picked yet), options, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", + "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool, recentColors?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), Show Options (true) or Hide Options (false), and check (true) or uncheck (false) Show Recent Colors, which shows or hides the panel's Recent Colors row (applied colors still join the list while it is hidden; the Swatches panel keeps its row); all three are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options, ui.color_show_recent_colors) → {mode (null: none picked yet), options, recentColors, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", ), ( "ui.savePdfDialog", @@ -1377,7 +1419,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.action.insertStop", "Insert Stop", "", - "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, or no action and no recording is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, no action and no recording, or a stop that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), + ( + "ui.action.insertMenuItem", + "Insert Menu Item", + "", + "{set?: index, action?: index, step?: index, command, params?: object} insert the command of a menu item as a step, without running it; the step plays as choosing the item runs it. command and params (default {}) must be those of a menu item that can be a step: one that runs an engine command, whose label does not end with \"…\", outside the VectorCraft, File, Window and Help menus, and that is not Undo, Redo, a Paste, a batch (command.batch), a preference (prefs.*) or action (action.*) command, an Object › Align item, Image Trace's Make or Make and Expand, Pattern's Make or Edit Pattern, a saved selection, saved view or recent font item, or a plug-in's item. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A command and params that no such menu item has, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Menu Item… (dialog `actionInsertMenuItem` with find, command, params, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", ), ( "ui.action.continue", @@ -1462,7 +1510,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "css.exportFile", "Export CSS…", "", - "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first)}", + "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first and how many there are, and hovering the message lists up to 30 of them, fewer when the window is small, with how many were left out)}", ), ( "file.print", @@ -1493,25 +1541,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", ), ( "ui.installPlugin", "Install Plug-in…", "", - "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), ( "plugin.cancelRuns", "Cancel Plug-in Run", "", - "{} stop every heavy filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", + "{} stop every filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", ), ( "plugin.hideRuns", "Continue in Background", "", - "{} close the progress window of the heavy filters running in the background; they go on, shown in the status bar → {hidden: n}", + "{} close the progress window of the filters running in the background; they go on, shown in the status bar → {hidden: n}", ), ( "imageTrace.cancelRuns", diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index fefd8a200c..a0e95498c3 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -141,6 +141,28 @@ fn channel(v: u32, mask: u32) -> u8 { ((x * 255 + max / 2) / max.max(1)).min(255) as u8 } +/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`), +/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG +/// whose chunks don't read to the end, are returned as they are. +fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { + const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; + if !bytes.starts_with(SIGNATURE) { + return bytes.into(); + } + let mut out = SIGNATURE.to_vec(); + let mut at = SIGNATURE.len(); + while at < bytes.len() { + let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() }; + let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize; + let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() }; + if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") { + out.extend_from_slice(&bytes[at..end]); + } + at = end; + } + out.into() +} + /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); @@ -175,12 +197,15 @@ pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> R }; if compression == BI_JPEG || compression == BI_PNG { // The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded. - let (w, h) = image::ImageReader::new(Cursor::new(bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; + // A PNG's compressed ICC profile and text chunks expand when its decoder is made, and + // nothing here uses them: they are left out before the size is read and the pixels decoded. + let bits = png_without_metadata(bits); + let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { return Err("a bitmap is too large to read".into()); } charge(w, h, left)?; - let img = image::load_from_memory(bits).map_err(|_| bad())?.to_rgba8(); + let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8(); return Ok(Rgba { width: w, height: h, pixels: img.into_raw() }); } if compression != BI_RGB && compression != BI_BITFIELDS { @@ -297,6 +322,23 @@ pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> { mod tests { use super::*; + #[test] + fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() { + use image::ImageEncoder; + let mut png = vec![]; + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + encoder.set_icc_profile(vec![0; 1 << 20]).unwrap(); + encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap(); + assert!(png.windows(4).any(|w| w == b"iCCP")); + let stripped = png_without_metadata(&png); + assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len()); + let img = image::load_from_memory(&stripped).unwrap().to_rgba8(); + assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]); + // Not a PNG, or a PNG cut short: unchanged. + assert_eq!(&*png_without_metadata(b"BM...."), b"BM...."); + assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]); + } + fn sample() -> Rgba { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 5326e2f307..a517d516a6 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -84,7 +84,7 @@ pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result emf::write(&ops, r, &doc.title), + Kind::Emf => emf::write(&ops, r, doc.info_title()), Kind::Wmf => wmf::write(&ops, r, &mut warnings), }; Ok(Output { bytes, warnings }) diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 87398c1f07..343b422093 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -176,7 +176,8 @@ impl<'a> Scene<'a> { } fn node(&mut self, n: &Node, force: bool) { - if let NodeKind::Layer { template: true, .. } = n.kind { + // Ruler guides draw on screen only: no record and no loss warning. + if n.is_ruler_guide() || n.is_template() { return; } if !force && !n.visible { @@ -237,6 +238,8 @@ impl<'a> Scene<'a> { self.node(c, false); } } + // Ruler guides draw on screen only. + NodeKind::RulerGuide { .. } => {} } self.opacity = opacity; } diff --git a/crates/pathops/src/addons.rs b/crates/pathops/src/addons.rs index 3896d02d05..436ba984bd 100644 --- a/crates/pathops/src/addons.rs +++ b/crates/pathops/src/addons.rs @@ -10,12 +10,15 @@ //! - [`segment_reshape`]: bending a segment by dragging a point on it (shared by the tools that //! reshape segments directly). //! - [`pen`]: the Smart Pen's straight and curved segments and its point edits. +//! - [`stencil`]: Stencil Bridges, the strips cut out of art so that a stencil cut from it keeps +//! its islands attached. pub mod cleanup; pub mod keep_shape; pub mod pathtools; pub mod pen; pub mod segment_reshape; +pub mod stencil; pub use cleanup::{ Rejoined, close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles, diff --git a/crates/pathops/src/addons/stencil.rs b/crates/pathops/src/addons/stencil.rs new file mode 100644 index 0000000000..437433e40c --- /dev/null +++ b/crates/pathops/src/addons/stencil.rs @@ -0,0 +1,653 @@ +//! Stencil Bridges: the art a stencil is cut from, with strips cut out of it so that every island +//! of the stencil sheet stays attached. +//! +//! The art is the area the stencil's holes take. Each bounded area outside the art (the inside of +//! an O, any hole of a shape) is an island of the sheet. A bridge is a straight strip of a set +//! width cut out of the art, from an island across the art to the sheet beyond it, or to another +//! island. The bridges are picked as a spanning tree over the islands and the sheet (shortest +//! crossings first), so every island that has room for one is joined to the sheet, then each +//! island gets more bridges, spread around it, up to the number asked for. +//! +//! Crossings are measured along straight lines in one direction at a time (vertical, horizontal, +//! or every 15 degrees for the shortest crossing), spaced half a bridge width apart. + +#[cfg(test)] +mod tests; + +use std::cell::Cell; + +use kurbo::{BezPath, ParamCurve, PathEl, Point}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; + +use crate::{BoolOp, DEFAULT_PRECISION, PathOpsError, try_boolean, try_unite_all}; + +/// The narrowest and widest bridge, in points. +pub const BRIDGE_WIDTH_RANGE: (f64, f64) = (0.01, 1000.0); +/// The most bridges one island is given. +pub const MAX_BRIDGES_PER_ISLAND: usize = 16; +/// The most straight segments the art is followed by. +pub const MAX_STENCIL_SEGMENTS: usize = 200_000; +/// The most outlines the art may have. +pub const MAX_STENCIL_CONTOURS: usize = 4000; +/// How far from the origin the art and its handles may reach, in points: beyond the coordinates a +/// document holds. +pub const MAX_STENCIL_EXTENT: f64 = 1.0e7; +/// The most segments all lines across the art may look at together. +const MAX_WORK: usize = 300_000_000; +/// The most edges the outlines are tested against when finding which ones bound islands. +const MAX_NESTING_WORK: usize = 50_000_000; +/// The most bands one direction's segments are listed in. +const MAX_LINES: f64 = 1000.0; +/// The most lines all islands are looked across along, in every direction together. +const MAX_ISLAND_LINES: usize = 400_000; +/// The most lines on each side of an island's middle, in one direction. +const MAX_LINES_PER_SIDE: usize = 64; +/// The most times segments are listed against the lines they reach, in one direction. +const MAX_BIN_ENTRIES: usize = 20_000_000; +/// The lines across one bridge its width is checked along. +const CHECKS: usize = 5; +/// The directions the shortest crossing is looked for in, in degrees. +const SHORTEST_STEP_DEG: usize = 15; + +/// Which way bridges run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BridgeDirection { + Vertical, + Horizontal, + /// The shortest crossing in any of 12 directions, 15 degrees apart. + Shortest, +} + +/// What [`stencil_bridges`] makes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BridgeSpec { + /// Each bridge's width (pt), in [`BRIDGE_WIDTH_RANGE`]. + pub width: f64, + /// The bridges each island is given, 1 to [`MAX_BRIDGES_PER_ISLAND`] (fewer where it has no + /// room for more, and more where other islands are joined to the sheet through it). + pub count: usize, + pub direction: BridgeDirection, +} + +/// The art with its bridges cut out. +#[derive(Clone, Debug, PartialEq)] +pub struct Bridged { + /// The art as one area, less the bridges. + pub path: PathData, + /// The islands the art held. + pub islands: usize, + /// The bridges cut. + pub bridges: usize, + /// The islands the cut result still encloses: no bridge of the width fits, or the bridges that + /// fit join them only to each other. + pub unbridged: usize, +} + +/// `art` (each path with its fill rule; open subpaths are closed as a fill closes them) as one +/// area with bridges cut out of it as `spec` says. With no islands, the area is returned as it is +/// and no bridge is cut. +pub fn stencil_bridges(art: &[(&PathData, FillRule)], spec: BridgeSpec) -> Result { + let (lo, hi) = BRIDGE_WIDTH_RANGE; + if !(spec.width.is_finite() && (lo..=hi).contains(&spec.width)) || !(1..=MAX_BRIDGES_PER_ISLAND).contains(&spec.count) { + return Err(PathOpsError::Degenerate); + } + if too_large(art) { + return Err(PathOpsError::TooComplex); + } + let closed: Vec = + art.iter().map(|(p, _)| PathData::new(p.subpaths.iter().map(|sp| SubPath { closed: true, ..sp.clone() }).collect())).collect(); + let refs: Vec<(&PathData, FillRule)> = closed.iter().zip(art).map(|(p, (_, r))| (p, *r)).collect(); + bridge_region(try_unite_all(&refs)?, spec) +} + +/// Whether `art` has more than [`MAX_STENCIL_SEGMENTS`] anchors or reaches past +/// [`MAX_STENCIL_EXTENT`]: art refused before it is united. +fn too_large(art: &[(&PathData, FillRule)]) -> bool { + let anchors: usize = art.iter().flat_map(|(p, _)| &p.subpaths).map(|sp| sp.anchors.len()).sum(); + anchors > MAX_STENCIL_SEGMENTS || !art.iter().all(|(p, _)| within_extent(&p.to_bezpath())) +} + +/// [`stencil_bridges`] on `region`, an area with no overlaps. +fn bridge_region(region: PathData, spec: BridgeSpec) -> Result { + let contours = contours(®ion, spec.width)?; + let holes = contours.iter().filter(|c| c.hole).count(); + if holes == 0 { + return Ok(Bridged { path: region, islands: 0, bridges: 0, unbridged: 0 }); + } + let (chosen, unjoined) = choose(&contours, spec, MAX_WORK)?; + if chosen.is_empty() { + return Ok(Bridged { path: region, islands: holes, bridges: 0, unbridged: unjoined }); + } + let strips = PathData::new(chosen.iter().map(|c| SubPath::polyline(&c.strip, true)).collect()); + let path = try_boolean(®ion, FillRule::NonZero, &strips, FillRule::NonZero, BoolOp::Difference, DEFAULT_PRECISION)?; + // The islands the result still encloses, counted on the cut outlines themselves (removing art + // never encloses a new one). + let unbridged = match self::contours(&path, spec.width) { + Ok(left) => left.iter().filter(|c| c.hole).count(), + Err(_) => unjoined, + }; + Ok(Bridged { path, islands: holes, bridges: chosen.len(), unbridged }) +} + +/// The bridges `spec` asks for across the art that `contours` outline, and how many islands they +/// leave apart from the sheet. Lines across the art look at no more than `work` segments in all; +/// past that, the art is refused when the islands are not all joined yet, and otherwise the extra +/// bridges found so far are kept. +fn choose(contours: &[Contour], spec: BridgeSpec, work: usize) -> Result<(Vec, usize), PathOpsError> { + let degrees: Vec = match spec.direction { + BridgeDirection::Vertical => vec![90.0], + BridgeDirection::Horizontal => vec![0.0], + BridgeDirection::Shortest => (0..180).step_by(SHORTEST_STEP_DEG).map(|d| d as f64).collect(), + }; + let budget = work / degrees.len().max(1); + let mut views = vec![]; + for deg in degrees { + views.push(View::new(contours, deg.to_radians(), spec.width, budget)?); + } + let mut picker = Picker::new(contours, &views, spec.width); + picker.connect(); + if views.iter().any(View::exhausted) { + return Err(PathOpsError::TooComplex); + } + picker.spread(spec.count); + let unjoined = picker.unjoined(); + Ok((picker.chosen, unjoined)) +} + +/// One closed outline of the art, followed in straight segments. +struct Contour { + points: Vec, + /// Whether it bounds an island (it lies inside an odd number of the others). + hole: bool, + /// Its area, without sign. + area: f64, + /// Its box: (min x, min y, max x, max y). + bounds: (f64, f64, f64, f64), +} + +/// The outlines of `region` (an area with no overlaps) followed within a tolerance set by the +/// bridge width: a twentieth of it, from 0.002 to 0.25 pt, raised for a curve that would need more +/// than [`vectorcraft_geom::MAX_FLATTEN_PER_CURVE`] segments. Art reaching past +/// [`MAX_STENCIL_EXTENT`] is refused. +fn contours(region: &PathData, width: f64) -> Result, PathOpsError> { + if !within_extent(®ion.to_bezpath()) { + return Err(PathOpsError::TooComplex); + } + let tolerance = (width / 20.0).clamp(0.002, 0.25); + let mut out: Vec = vec![]; + let mut segments = 0usize; + for sp in ®ion.subpaths { + let room = MAX_STENCIL_SEGMENTS.saturating_sub(segments); + let mut bp = BezPath::new(); + sp.to_bezpath_into(&mut bp); + let mut points = follow(&bp, tolerance, room)?; + while points.len() > 1 && points.first() == points.last() { + points.pop(); + } + if points.len() < 3 { + continue; + } + segments += points.len(); + if segments > MAX_STENCIL_SEGMENTS || out.len() >= MAX_STENCIL_CONTOURS { + return Err(PathOpsError::TooComplex); + } + if points.iter().any(|p| !(p.x.is_finite() && p.y.is_finite())) { + return Err(PathOpsError::NonFinite); + } + let area = signed_area(&points).abs(); + let bounds = points.iter().fold((f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |b, p| { + (b.0.min(p.x), b.1.min(p.y), b.2.max(p.x), b.3.max(p.y)) + }); + out.push(Contour { points, hole: false, area, bounds }); + } + // An outline too small to see is dropped, so its inside counts as art (or, for a speck of art, + // as the area around it). + let tiny = (tolerance * tolerance).max(1e-9); + out.retain(|c| c.area > tiny); + // An outline inside an odd number of others bounds an island. Each outline is placed by the + // middle of its longest edge: outlines of an area with no overlaps meet at most at corners, so + // that point lies on no other outline. + let mut work = 0usize; + let mut depths = Vec::with_capacity(out.len()); + for (i, c) in out.iter().enumerate() { + let p = longest_edge_middle(&c.points); + let mut depth = 0usize; + for (j, o) in out.iter().enumerate() { + if j == i || o.area < c.area || !holds_box(o.bounds, c.bounds) { + continue; + } + work += o.points.len(); + if work > MAX_NESTING_WORK { + return Err(PathOpsError::TooComplex); + } + if contains(o, p) { + depth += 1; + } + } + depths.push(depth); + } + for (c, depth) in out.iter_mut().zip(depths) { + c.hole = depth % 2 == 1; + } + Ok(out) +} + +/// The middle of the longest edge of the closed outline through `points`. +fn longest_edge_middle(points: &[Point]) -> Point { + let n = points.len(); + (0..n) + .map(|i| (points[i], points[(i + 1) % n])) + .max_by(|(a, b), (c, d)| a.distance(*b).total_cmp(&c.distance(*d))) + .map_or(Point::ZERO, |(a, b)| a.midpoint(b)) +} + +/// Whether box `outer` holds box `inner`, edges included. Boxes are (min x, min y, max x, max y). +fn holds_box(outer: (f64, f64, f64, f64), inner: (f64, f64, f64, f64)) -> bool { + outer.0 <= inner.0 && outer.1 <= inner.1 && outer.2 >= inner.2 && outer.3 >= inner.3 +} + +/// Whether `bp` and its handles stay within [`MAX_STENCIL_EXTENT`] of the origin. +fn within_extent(bp: &BezPath) -> bool { + let reach = bp.control_box(); + [reach.x0, reach.y0, reach.x1, reach.y1].iter().all(|v| v.abs() <= MAX_STENCIL_EXTENT) +} + +/// The points that follow outline `bp` within `tolerance`, segment by segment, or +/// [`PathOpsError::TooComplex`] once they pass `room` (and one more for a closed outline's +/// repeated start, which the caller drops). It stops at the first segment past the limit. +fn follow(bp: &BezPath, tolerance: f64, room: usize) -> Result, PathOpsError> { + let limit = room.saturating_add(1); + let mut points: Vec = vec![]; + for seg in bp.segments() { + if points.is_empty() { + points.push(seg.start()); + } + let mut over = false; + vectorcraft_geom::flatten([PathEl::MoveTo(seg.start()), seg.as_path_el()], tolerance, |el| match el { + PathEl::LineTo(p) if points.len() < limit => points.push(p), + PathEl::LineTo(_) => over = true, + _ => {} + }); + if over { + return Err(PathOpsError::TooComplex); + } + } + Ok(points) +} + +fn signed_area(points: &[Point]) -> f64 { + let n = points.len(); + (0..n).map(|i| points[i].to_vec2().cross(points[(i + 1) % n].to_vec2())).sum::() / 2.0 +} + +/// Whether `p` is inside contour `c` (even-odd). +fn contains(c: &Contour, p: Point) -> bool { + let (x0, y0, x1, y1) = c.bounds; + if p.x < x0 || p.x > x1 || p.y < y0 || p.y > y1 { + return false; + } + let n = c.points.len(); + let mut inside = false; + for i in 0..n { + let (a, b) = (c.points[i], c.points[(i + 1) % n]); + if (a.y <= p.y) != (b.y <= p.y) && p.x < a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y) { + inside = !inside; + } + } + inside +} + +/// The area outside the art that a point is in: 0 for the sheet around the art, `i + 1` for the +/// island contour `i` bounds. +type Area = usize; +const SHEET: Area = 0; + +/// The art seen along lines in one direction: rotated so the lines run along x, with its segments +/// listed by the bands of y they reach. +struct View { + angle: f64, + /// Rotated segments, each with the contour it belongs to. + segments: Vec<(Point, Point, usize)>, + /// The lowest y of the rotated art. + y0: f64, + /// The band height, and the lines' spacing. + step: f64, + bands: Vec>, + /// Each contour's lowest and highest rotated y. + ranges: Vec<(f64, f64)>, + /// The segments lines may still look at; past it, every line is missing. + budget: Cell, +} + +/// Where a line crosses the art: the edges in order (even-odd pairs are the art), and the area +/// each stretch outside the art is in (one more than there are pairs). +struct Line { + xs: Vec, + areas: Vec, +} + +impl View { + fn new(contours: &[Contour], angle: f64, width: f64, budget: usize) -> Result { + let (sin, cos) = angle.sin_cos(); + let rotate = |p: Point| Point::new(p.x * cos + p.y * sin, -p.x * sin + p.y * cos); + let mut segments = vec![]; + let mut ranges = vec![]; + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (k, c) in contours.iter().enumerate() { + let pts: Vec = c.points.iter().map(|p| rotate(*p)).collect(); + let (lo, hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.y), hi.max(p.y))); + ranges.push((lo, hi)); + y0 = y0.min(lo); + y1 = y1.max(hi); + for i in 0..pts.len() { + segments.push((pts[i], pts[(i + 1) % pts.len()], k)); + } + } + let span = (y1 - y0).max(width); + let step = (width / 2.0).max(span / MAX_LINES); + let count = (span / step).ceil() as usize + 1; + let mut bands: Vec> = vec![vec![]; count]; + let band = |y: f64| (((y - y0) / step).floor().max(0.0) as usize).min(count - 1); + let mut entries = 0usize; + for (i, (a, b, _)) in segments.iter().enumerate() { + let (from, to) = (band(a.y.min(b.y)), band(a.y.max(b.y))); + entries += to - from + 1; + if entries > MAX_BIN_ENTRIES { + return Err(PathOpsError::TooComplex); + } + for list in &mut bands[from..=to] { + list.push(i as u32); + } + } + Ok(View { angle, segments, y0, step, bands, ranges, budget: Cell::new(budget) }) + } + + /// Whether lines looked at more segments than the budget allows. + fn exhausted(&self) -> bool { + self.budget.get() == 0 + } + + /// The art along the line at rotated y `y`, `None` where its edges don't pair up or the budget + /// is spent. + fn line(&self, y: f64, contours: &[Contour]) -> Option { + let band = ((y - self.y0) / self.step).floor(); + let list = self.bands.get(if band < 0.0 { usize::MAX } else { band as usize })?; + let left = self.budget.get().checked_sub(list.len()).filter(|left| *left > 0); + self.budget.set(left.unwrap_or(0)); + left?; + let mut hits: Vec<(f64, usize)> = vec![]; + for &i in list { + let (a, b, k) = self.segments[i as usize]; + if (a.y <= y) != (b.y <= y) { + hits.push((a.x + (y - a.y) * (b.x - a.x) / (b.y - a.y), k)); + } + } + if hits.len() % 2 == 1 { + return None; + } + hits.sort_by(|p, q| p.0.total_cmp(&q.0)); + // Walking along the line, each contour crossed an odd number of times so far holds the + // point; the smallest island contour holding a stretch outside the art is its island. + let mut open: Vec = vec![]; + let mut areas = vec![SHEET]; + for (n, (_, k)) in hits.iter().enumerate() { + match open.iter().position(|o| o == k) { + Some(at) => { + open.swap_remove(at); + } + None => open.push(*k), + } + if n % 2 == 1 { + let island = open.iter().filter(|o| contours[**o].hole).min_by(|a, b| contours[**a].area.total_cmp(&contours[**b].area)); + areas.push(island.map_or(SHEET, |k| k + 1)); + } + } + Some(Line { xs: hits.into_iter().map(|(x, _)| x).collect(), areas }) + } + + /// The point at rotated `(x, y)` in the art's own coordinates. + fn unrotate(&self, x: f64, y: f64) -> Point { + let (sin, cos) = self.angle.sin_cos(); + Point::new(x * cos - y * sin, x * sin + y * cos) + } +} + +/// A crossing of the art along one line, between the areas on either side of it. +#[derive(Clone, Copy, Debug)] +struct Crossing { + view: usize, + y: f64, + /// Where it enters and leaves the art. + from: f64, + to: f64, + areas: (Area, Area), + /// How far its line is from the middle of the island it starts from. + off_middle: f64, +} + +impl Crossing { + fn len(&self) -> f64 { + self.to - self.from + } +} + +/// A bridge that fits: its crossing, its middle and its strip's corners. +struct Bridge { + areas: (Area, Area), + middle: Point, + strip: Vec, +} + +struct Picker<'a> { + contours: &'a [Contour], + views: &'a [View], + width: f64, + crossings: Vec, + /// The crossings that touch each area. + touching: Vec>, + parent: Vec, + chosen: Vec, +} + +impl<'a> Picker<'a> { + fn new(contours: &'a [Contour], views: &'a [View], width: f64) -> Self { + let areas = contours.len() + 1; + let holes = contours.iter().filter(|c| c.hole).count().max(1); + // Each island is looked across along lines through its middle and out from it on both + // sides, half a width apart, or fewer where there are many islands. + let each_side = (MAX_ISLAND_LINES / (holes * views.len()).max(1)).clamp(1, MAX_LINES_PER_SIDE) as f64; + let mut crossings = vec![]; + for (v, view) in views.iter().enumerate() { + for (k, _) in contours.iter().enumerate().filter(|(_, c)| c.hole) { + let island = k + 1; + let (lo, hi) = view.ranges[k]; + let (middle, reach) = ((lo + hi) / 2.0, (hi - lo) / 2.0); + let step = (width / 2.0).max(reach / each_side); + let mut ys = vec![middle]; + let mut d = step; + while d < reach { + ys.extend([middle - d, middle + d]); + d += step; + } + for y in ys { + let Some(line) = view.line(y, contours) else { continue }; + for (j, pair) in line.xs.as_chunks::<2>().0.iter().enumerate() { + let (a, b) = (line.areas[j], line.areas[j + 1]); + if a == b || (a != island && b != island) { + continue; + } + crossings.push(Crossing { view: v, y, from: pair[0], to: pair[1], areas: (a, b), off_middle: (y - middle).abs() }); + } + } + } + } + // Shortest first; among crossings of about the same length, the one nearest the middle of + // its island. + let grain = width * 0.05; + crossings.sort_by(|p, q| (p.len() / grain).round().total_cmp(&(q.len() / grain).round()).then(p.off_middle.total_cmp(&q.off_middle))); + let mut touching = vec![vec![]; areas]; + for (i, c) in crossings.iter().enumerate() { + touching[c.areas.0].push(i); + touching[c.areas.1].push(i); + } + Picker { contours, views, width, crossings, touching, parent: (0..areas).collect(), chosen: vec![] } + } + + fn root(&mut self, mut a: usize) -> usize { + while self.parent[a] != a { + self.parent[a] = self.parent[self.parent[a]]; + a = self.parent[a]; + } + a + } + + /// Join every island to the sheet by the shortest crossings that fit, as a spanning tree. Bridges + /// that only join islands that stay apart from the sheet are not cut. + fn connect(&mut self) { + let mut apart = self.contours.iter().filter(|c| c.hole).count(); + for i in 0..self.crossings.len() { + if apart == 0 { + break; + } + let c = self.crossings[i]; + let (a, b) = (self.root(c.areas.0), self.root(c.areas.1)); + if a == b { + continue; + } + if let Some(bridge) = self.fit(&c) { + self.parent[a] = b; + self.chosen.push(bridge); + apart -= 1; + } + } + let sheet = self.root(SHEET); + for bridge in std::mem::take(&mut self.chosen) { + if self.root(bridge.areas.0) == sheet { + self.chosen.push(bridge); + } + } + } + + /// Give each island more bridges, up to `count`, each far from the island's others (at least + /// two widths away, and as short as can be among those at least 80% as far as the farthest), + /// and no more than twice as long as its shortest crossing that a bridge fits plus a width. + /// A crossing a bridge does not fit is not tried again, and once the lines' budget is spent no + /// more bridges are found. + fn spread(&mut self, count: usize) { + let sheet = self.root(SHEET); + let mut misfit = vec![false; self.crossings.len()]; + for island in 1..self.touching.len() { + if !self.contours[island - 1].hole || self.root(island) != sheet { + continue; + } + let mut limit = None; + loop { + let mine: Vec = self.chosen.iter().filter(|b| b.areas.0 == island || b.areas.1 == island).map(|b| b.middle).collect(); + if mine.len() >= count { + break; + } + let longest = match limit { + Some(l) => l, + None => { + // The island's crossings are listed shortest first, so the first that fits + // is its shortest bridge. + let mut shortest = None; + for &i in &self.touching[island] { + if misfit[i] { + continue; + } + if self.fit(&self.crossings[i]).is_some() { + shortest = Some(self.crossings[i].len()); + break; + } + misfit[i] = true; + } + let Some(shortest) = shortest else { break }; + *limit.insert(shortest * 2.0 + self.width) + } + }; + let mut ranked: Vec<(f64, usize)> = self.touching[island] + .iter() + .filter(|&&i| !misfit[i] && self.crossings[i].len() <= longest) + .map(|&i| { + let m = self.middle(&self.crossings[i]); + (mine.iter().map(|p| p.distance(m)).fold(f64::INFINITY, f64::min), i) + }) + .filter(|(d, _)| *d >= self.width * 2.0) + .collect(); + // The crossings nearly as far as the farthest go first, in the order `connect` + // takes them (shortest, then nearest the middle); then the rest, farthest first. + let far = ranked.iter().map(|r| r.0).fold(0.0, f64::max) * 0.8; + ranked.sort_by(|p, q| (q.0 >= far).cmp(&(p.0 >= far)).then_with(|| if p.0 >= far { p.1.cmp(&q.1) } else { q.0.total_cmp(&p.0) })); + let mut found = None; + for &(_, i) in &ranked { + match self.fit(&self.crossings[i]) { + Some(bridge) => { + found = Some(bridge); + break; + } + None => misfit[i] = true, + } + } + match found { + Some(bridge) => self.chosen.push(bridge), + None => break, + } + if self.views.iter().any(View::exhausted) { + return; + } + } + } + } + + /// The islands not joined to the sheet. + fn unjoined(&mut self) -> usize { + let sheet = self.root(SHEET); + (1..self.parent.len()).filter(|&a| self.contours[a - 1].hole).filter(|&a| self.root(a) != sheet).count() + } + + fn middle(&self, c: &Crossing) -> Point { + self.views[c.view].unrotate((c.from + c.to) / 2.0, c.y) + } + + /// The bridge of crossing `c`, if a strip of the width fits there: along lines across its + /// width, the art is crossed once between the same two areas, and the strip ends outside the + /// art on each of them. + fn fit(&self, c: &Crossing) -> Option { + let view = &self.views[c.view]; + let half = self.width / 2.0; + let (mut start, mut end) = (f64::INFINITY, f64::NEG_INFINITY); + let (mut room_before, mut room_after) = (f64::NEG_INFINITY, f64::INFINITY); + for k in 0..CHECKS { + let y = c.y - half + self.width * k as f64 / (CHECKS - 1) as f64; + let line = view.line(y, self.contours)?; + let last = line.areas.len() - 1; + // The crossing between the same two areas that overlaps this one, the nearest if several do. + let (j, _) = line + .xs + .as_chunks::<2>() + .0 + .iter() + .enumerate() + .filter(|(j, p)| (line.areas[*j], line.areas[j + 1]) == c.areas && p[1] > c.from - self.width && p[0] < c.to + self.width) + .min_by(|(_, p), (_, q)| (p[0] - c.from).abs().total_cmp(&(q[0] - c.from).abs()))?; + start = start.min(line.xs[2 * j]); + end = end.max(line.xs[2 * j + 1]); + if j > 0 { + room_before = room_before.max(line.xs[2 * j - 1]); + } + if j + 1 < last { + room_after = room_after.min(line.xs[2 * j + 2]); + } + } + if room_before >= start || room_after <= end { + return None; + } + // The strip reaches a little past the art at each end, so no sliver of it is left. + let reach = self.width.min(1.0); + let s0 = (start - reach).max((room_before + start) / 2.0); + let s1 = (end + reach).min((room_after + end) / 2.0); + let strip = [(s0, c.y - half), (s1, c.y - half), (s1, c.y + half), (s0, c.y + half)].map(|(x, y)| view.unrotate(x, y)).to_vec(); + Some(Bridge { areas: c.areas, middle: self.middle(c), strip }) + } +} diff --git a/crates/pathops/src/addons/stencil/tests.rs b/crates/pathops/src/addons/stencil/tests.rs new file mode 100644 index 0000000000..48d2f8148e --- /dev/null +++ b/crates/pathops/src/addons/stencil/tests.rs @@ -0,0 +1,326 @@ +use kurbo::{BezPath, Point, Shape}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; + +use super::*; + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +/// A square ring: `outer` with the hole `inner`, each (x0, y0, x1, y1). +fn ring(outer: (f64, f64, f64, f64), inner: (f64, f64, f64, f64)) -> PathData { + PathData::new(vec![rect(outer.0, outer.1, outer.2, outer.3), rect(inner.0, inner.1, inner.2, inner.3)]) +} + +fn spec(width: f64, count: usize, direction: BridgeDirection) -> BridgeSpec { + BridgeSpec { width, count, direction } +} + +fn run(art: &PathData, spec: BridgeSpec) -> Bridged { + stencil_bridges(&[(art, FillRule::EvenOdd)], spec).unwrap() +} + +/// Is `(x, y)` inside the area `p` draws? +fn inside(p: &PathData, x: f64, y: f64) -> bool { + p.to_bezpath().winding(Point::new(x, y)) != 0 +} + +/// The islands left once the bridges are cut. +fn islands_left(b: &Bridged) -> usize { + run(&b.path, spec(1.0, 1, BridgeDirection::Shortest)).islands +} + +/// A letter O made square: 100 pt across with bars 20 pt thick. +fn letter_o() -> PathData { + ring((0.0, 0.0, 100.0, 100.0), (20.0, 20.0, 80.0, 80.0)) +} + +#[test] +fn an_o_gets_a_bridge_and_its_island_joins_the_sheet() { + let b = run(&letter_o(), spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 1, 0)); + assert_eq!(islands_left(&b), 0, "the inside of the O is joined to the sheet"); + // The bridge crosses the top bar at the middle of the hole; the rest of the O stays. + assert!(!inside(&b.path, 50.0, 10.0)); + assert!(inside(&b.path, 30.0, 10.0) && inside(&b.path, 50.0, 90.0) && inside(&b.path, 10.0, 50.0)); +} + +#[test] +fn the_bridge_is_as_wide_as_asked() { + for width in [2.0, 6.0] { + let b = run(&letter_o(), spec(width, 1, BridgeDirection::Vertical)); + let half = width / 2.0; + assert!(!inside(&b.path, 50.0 - half * 0.9, 10.0) && !inside(&b.path, 50.0 + half * 0.9, 10.0), "{width}"); + assert!(inside(&b.path, 50.0 - half * 1.2, 10.0) && inside(&b.path, 50.0 + half * 1.2, 10.0), "{width}"); + } +} + +#[test] +fn horizontal_bridges_cross_the_sides() { + let b = run(&letter_o(), spec(4.0, 1, BridgeDirection::Horizontal)); + assert_eq!((b.bridges, islands_left(&b)), (1, 0)); + assert!(!inside(&b.path, 10.0, 50.0) || !inside(&b.path, 90.0, 50.0)); + assert!(inside(&b.path, 50.0, 10.0) && inside(&b.path, 50.0, 90.0)); +} + +#[test] +fn the_shortest_crossing_takes_the_thinnest_bar() { + // The left bar is 5 pt thick, the others 20. + let art = ring((0.0, 0.0, 100.0, 100.0), (5.0, 20.0, 80.0, 80.0)); + let b = run(&art, spec(4.0, 1, BridgeDirection::Shortest)); + assert_eq!((b.bridges, islands_left(&b)), (1, 0)); + assert!(!inside(&b.path, 2.5, 50.0), "the bridge crosses the thin bar"); + assert!(inside(&b.path, 50.0, 10.0) && inside(&b.path, 90.0, 50.0)); + // Vertical bridges cross a 20 pt bar instead. + let v = run(&art, spec(4.0, 1, BridgeDirection::Vertical)); + assert!(inside(&v.path, 2.5, 50.0) && !inside(&v.path, 42.5, 10.0)); +} + +#[test] +fn a_shape_with_two_holes_gets_a_bridge_for_each() { + let art = PathData::new(vec![rect(0.0, 0.0, 100.0, 50.0), rect(10.0, 10.0, 40.0, 40.0), rect(60.0, 10.0, 90.0, 40.0)]); + let b = run(&art, spec(3.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (2, 2, 0)); + assert_eq!(islands_left(&b), 0); + assert!(!inside(&b.path, 25.0, 5.0) && !inside(&b.path, 75.0, 5.0)); +} + +#[test] +fn more_bridges_per_island_spread_around_it() { + let b = run(&letter_o(), spec(4.0, 2, BridgeDirection::Vertical)); + assert_eq!(b.bridges, 2); + assert!(!inside(&b.path, 50.0, 10.0) && !inside(&b.path, 50.0, 90.0), "one at the top, one at the bottom"); +} + +#[test] +fn a_short_crossing_too_narrow_for_a_bridge_does_not_limit_the_others() { + // Hole A has a 2 pt slot B just above it: the 5 pt crossing from A to B is the shortest, but + // no 4 pt bridge fits there. A's 20 pt crossings to the sheet take its two bridges. + let art = PathData::new(vec![rect(0.0, 0.0, 200.0, 100.0), rect(20.0, 20.0, 80.0, 80.0), rect(49.0, 5.0, 51.0, 15.0)]); + let b = run(&art, spec(4.0, 2, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (2, 2, 1)); +} + +#[test] +fn islands_that_only_reach_each_other_get_no_bridge() { + // Holes Y and X, one above the other, with combs of 2 pt slots above Y and below X: no 4 pt + // vertical bridge reaches the sheet from either, so the bridge that fits between them would + // join nothing to the sheet. + let mut subpaths = vec![rect(0.0, 0.0, 100.0, 100.0), rect(20.0, 20.0, 80.0, 30.0), rect(30.0, 40.0, 70.0, 60.0)]; + for k in 0..27 { + let x = 10.0 + 3.0 * k as f64; + subpaths.push(rect(x, 5.0, x + 2.0, 15.0)); + subpaths.push(rect(x, 85.0, x + 2.0, 95.0)); + } + let b = run(&PathData::new(subpaths), spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (56, 0, 56)); +} + +#[test] +fn an_island_inside_an_island_is_joined_through_it() { + // A ring in the hole of a ring: two islands, the gap between the rings and the inner hole. + let art = + PathData::new(vec![rect(0.0, 0.0, 100.0, 100.0), rect(10.0, 10.0, 90.0, 90.0), rect(30.0, 30.0, 70.0, 70.0), rect(40.0, 40.0, 60.0, 60.0)]); + let b = run(&art, spec(2.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (2, 2, 0)); + assert_eq!(islands_left(&b), 0); +} + +#[test] +fn an_island_too_narrow_for_the_width_is_counted() { + let art = ring((0.0, 0.0, 100.0, 100.0), (49.0, 20.0, 51.0, 80.0)); + let b = run(&art, spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 0, 1)); + assert_eq!(islands_left(&b), 1); +} + +#[test] +fn art_without_islands_is_left_whole() { + let art = PathData::new(vec![rect(0.0, 0.0, 50.0, 50.0), rect(100.0, 0.0, 150.0, 50.0)]); + let b = run(&art, spec(4.0, 1, BridgeDirection::Shortest)); + assert_eq!((b.islands, b.bridges, b.unbridged), (0, 0, 0)); + assert!(inside(&b.path, 25.0, 25.0) && inside(&b.path, 125.0, 25.0)); +} + +#[test] +fn the_shortest_crossing_may_run_at_an_angle() { + // A diamond ring: its walls are 20 pt across horizontally and vertically but about 14 pt + // across at 45°, so only a diagonal line finds the shortest crossing. + let diamond = |r: f64| { + let pts = [(100.0, 100.0 - r), (100.0 + r, 100.0), (100.0, 100.0 + r), (100.0 - r, 100.0)].map(|(x, y)| Point::new(x, y)); + SubPath::polyline(&pts, true) + }; + let art = PathData::new(vec![diamond(60.0), diamond(40.0)]); + let b = run(&art, spec(2.0, 1, BridgeDirection::Shortest)); + assert_eq!((b.bridges, islands_left(&b)), (1, 0)); + // The middles of the four diagonal walls: one is cut. The middles of the walls straight + // above, below and beside the hole all stay. + let diagonal = [(125.0, 125.0), (75.0, 75.0), (125.0, 75.0), (75.0, 125.0)]; + assert!(diagonal.iter().any(|&(x, y)| !inside(&b.path, x, y)), "a diagonal bridge"); + for (x, y) in [(150.0, 100.0), (50.0, 100.0), (100.0, 150.0), (100.0, 50.0)] { + assert!(inside(&b.path, x, y), "({x}, {y}) stays"); + } + let h = run(&art, spec(2.0, 1, BridgeDirection::Horizontal)); + assert!(diagonal.iter().all(|&(x, y)| inside(&h.path, x, y))); +} + +#[test] +fn a_hole_touching_another_outline_at_a_corner_is_still_an_island() { + // A diamond hole whose bottom corner, where its outline starts, touches the bottom edge of the + // square around it. + let hole = SubPath::polyline(&[(50.0, 100.0), (70.0, 70.0), (50.0, 40.0), (30.0, 70.0)].map(|(x, y)| Point::new(x, y)), true); + let region = PathData::new(vec![rect(0.0, 0.0, 100.0, 100.0), hole]); + let found = contours(®ion, 1.0).unwrap(); + assert_eq!(found.iter().filter(|c| c.hole).count(), 1); +} + +#[test] +fn a_sliver_too_small_to_see_counts_as_art() { + // A hole 10 pt long and 0.005 pt high between the island and the top edge: a bridge that + // reaches only the sliver would join nothing to the sheet. + let region = PathData::new(vec![rect(0.0, 0.0, 100.0, 100.0), rect(40.0, 40.0, 60.0, 60.0), rect(45.0, 20.0, 55.0, 20.005)]); + let b = bridge_region(region, spec(5.0, 1, BridgeDirection::Vertical)).unwrap(); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 1, 0)); + assert_eq!(islands_left(&b), 0); +} + +#[test] +fn extra_bridges_stay_two_widths_apart() { + // Sixteen 10 pt bridges have no room around a hole 60 pt across with 20 pt between them. + let width = 10.0; + let found = contours(&letter_o(), width).unwrap(); + let (bridges, unjoined) = choose(&found, spec(width, 16, BridgeDirection::Shortest), MAX_WORK).unwrap(); + assert!(bridges.len() > 4 && bridges.len() < 16, "{}", bridges.len()); + assert_eq!(unjoined, 0); + for (i, a) in bridges.iter().enumerate() { + for b in &bridges[i + 1..] { + assert!(a.middle.distance(b.middle) >= width * 2.0, "{:?} {:?}", a.middle, b.middle); + } + } +} + +#[test] +fn bridges_found_before_the_budget_runs_out_are_kept() { + let found = contours(&letter_o(), 4.0).unwrap(); + // The least work that joins the island with one bridge also gives one with up to 16 asked + // for: the extra bridges stop where the budget ends. + let least = (1..100_000).find(|&work| choose(&found, spec(4.0, 1, BridgeDirection::Vertical), work).is_ok()).unwrap(); + let (bridges, unjoined) = choose(&found, spec(4.0, 16, BridgeDirection::Vertical), least).unwrap(); + assert_eq!((bridges.len(), unjoined), (1, 0)); + assert!(matches!(choose(&found, spec(4.0, 1, BridgeDirection::Vertical), least - 1), Err(PathOpsError::TooComplex))); +} + +#[test] +fn curves_are_followed_within_a_twentieth_of_the_width() { + let circle = PathData::from_bezpath(&kurbo::Circle::new((0.0, 0.0), 100.0).to_path(0.001)); + let mut counts = vec![]; + for (width, tolerance) in [(0.01, 0.002), (1.0, 0.05), (20.0, 0.25)] { + let found = contours(&circle, width).unwrap(); + let points = &found[0].points; + // The sag of each chord below the circle. + let sag = (0..points.len()).map(|i| 100.0 - points[i].midpoint(points[(i + 1) % points.len()]).to_vec2().hypot()).fold(0.0, f64::max); + assert!(sag <= tolerance + 0.002, "{width}: {sag}"); + counts.push(points.len()); + } + assert!(counts[0] > counts[1] && counts[1] > counts[2], "{counts:?}"); +} + +#[test] +fn open_outlines_are_closed_as_a_fill_closes_them() { + let mut art = letter_o(); + art.subpaths[0].closed = false; + let b = run(&art, spec(4.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, b.unbridged), (1, 1, 0)); +} + +#[test] +fn art_too_large_is_refused_before_it_is_combined() { + let far = PathData::new(vec![rect(0.0, 0.0, 1e8, 1e8)]); + let points: Vec = (0..=MAX_STENCIL_SEGMENTS).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64)).collect(); + let dense = PathData::new(vec![SubPath::polyline(&points, true)]); + assert!(too_large(&[(&far, FillRule::EvenOdd)]) && too_large(&[(&dense, FillRule::EvenOdd)])); + assert!(!too_large(&[(&letter_o(), FillRule::EvenOdd), (&letter_o(), FillRule::NonZero)])); +} + +#[test] +fn outlines_nested_too_deep_to_place_are_refused() { + // Rings of 190-sided polygons, one inside the next: placing each inside the others takes + // about 95 million tests of a point against an edge with 1000 of them, and 8 million with 300. + let polygon = |r: f64| { + let pts: Vec = (0..190).map(|i| (i as f64 / 190.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| Point::new(c * r, s * r)).collect(); + SubPath::polyline(&pts, true) + }; + let nested = |n: usize| PathData::new((0..n).map(|i| polygon(10.0 + i as f64)).collect()); + assert!(contours(&nested(300), 1.0).is_ok()); + assert!(matches!(contours(&nested(1000), 1.0), Err(PathOpsError::TooComplex))); +} + +#[test] +fn a_curved_o_is_bridged_at_its_thinnest() { + // Two circles, the hole 8 pt above the middle: the O is 2 pt thick at the top and 18 pt at + // the bottom. + let circle = |cy: f64, r: f64| PathData::from_bezpath(&kurbo::Circle::new((100.0, cy), r).to_path(0.01)); + let mut art = circle(100.0, 60.0); + art.subpaths.extend(circle(92.0, 50.0).subpaths); + let b = run(&art, spec(1.0, 1, BridgeDirection::Vertical)); + assert_eq!((b.islands, b.bridges, islands_left(&b)), (1, 1, 0)); + assert!(!inside(&b.path, 100.0, 41.0), "it crosses the thin top"); + assert!(inside(&b.path, 100.0, 151.0), "the thick bottom stays"); +} + +#[test] +fn art_with_too_many_outlines_is_refused() { + let squares = (0..MAX_STENCIL_CONTOURS + 1) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 3.0, (i / 100) as f64 * 3.0); + rect(x, y, x + 1.0, y + 1.0) + }) + .collect(); + let region = PathData::new(squares); + assert!(matches!(contours(®ion, 1.0), Err(PathOpsError::TooComplex))); + let mut fewer = region.clone(); + fewer.subpaths.pop(); + assert_eq!(contours(&fewer, 1.0).unwrap().len(), MAX_STENCIL_CONTOURS); +} + +#[test] +fn art_as_large_as_a_document_holds_is_followed_and_larger_art_is_refused() { + // An O 8000000 pt across, the most a document holds, with a 60 pt hole near its edge, followed + // within 0.002 pt. + let circle = |c: (f64, f64), r: f64| PathData::from_bezpath(&kurbo::Circle::new(c, r).to_path(0.01)); + let mut art = circle((0.0, 0.0), 4e6); + art.subpaths.extend(circle((0.0, 0.0), 2e6).subpaths); + art.subpaths.extend(circle((4e6 - 100.0, 0.0), 30.0).subpaths); + let found = contours(&art, 0.01).unwrap(); + assert_eq!(found.iter().filter(|c| c.hole).count(), 2); + let far = PathData::new(vec![rect(0.0, 0.0, 1e8, 1e8)]); + assert!(matches!(contours(&far, 0.01), Err(PathOpsError::TooComplex))); + let r = stencil_bridges(&[(&far, FillRule::EvenOdd)], spec(4.0, 1, BridgeDirection::Vertical)); + assert!(matches!(r, Err(PathOpsError::TooComplex))); +} + +#[test] +fn art_with_too_many_anchors_is_refused() { + let points: Vec = (0..=MAX_STENCIL_SEGMENTS).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64)).collect(); + let art = PathData::new(vec![SubPath::polyline(&points, true)]); + let r = stencil_bridges(&[(&art, FillRule::EvenOdd)], spec(4.0, 1, BridgeDirection::Vertical)); + assert!(matches!(r, Err(PathOpsError::TooComplex))); +} + +#[test] +fn following_stops_past_the_limit_and_allows_the_closing_point() { + // A closed square: its four corners and the start again. + let square = rect(0.0, 0.0, 10.0, 10.0); + let mut bp = BezPath::new(); + square.to_bezpath_into(&mut bp); + assert_eq!(follow(&bp, 0.01, 4).unwrap().len(), 5); + assert!(matches!(follow(&bp, 0.01, 3), Err(PathOpsError::TooComplex))); +} + +#[test] +fn bad_widths_and_counts_are_refused() { + let art = letter_o(); + for s in [spec(0.0, 1, BridgeDirection::Vertical), spec(f64::NAN, 1, BridgeDirection::Vertical), spec(4.0, 0, BridgeDirection::Vertical)] { + assert!(stencil_bridges(&[(&art, FillRule::EvenOdd)], s).is_err(), "{s:?}"); + } +} diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index e12c9fb395..60c2a8b296 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -22,6 +22,8 @@ thread_local! { pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The sweeps [`normalize_bez`] made on this thread. static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The input curves [`exact_merge`] tested on this thread. + static EXACT_MERGE_CURVES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Default curve-refit tolerance (document points) used to merge split curve pieces back together. @@ -663,16 +665,17 @@ fn try_merge(run: &[Seg], tidy: &Tidy) -> Option { } /// If every piece of `run` lies on one input cubic, return the exact sub-curve spanning the run. +/// Only the input curves whose bounds hold both ends of the run are tested +/// ([`Tidy::curves_around`]). fn exact_merge(run: &[Seg], tidy: &Tidy) -> Option { use kurbo::{ParamCurve, ParamCurveNearest}; let a = run[0].c.p0; let b = run[run.len() - 1].c.p3; let scale = 1.0 + a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs()); let tol = 1e-6 * scale; - for (r, c) in &tidy.curves { - if !r.contains(a) || !r.contains(b) { - continue; - } + for c in tidy.curves_around(a, b) { + #[cfg(test)] + EXACT_MERGE_CURVES.with(|n| n.set(n.get() + 1)); let na = c.nearest(a, 1e-12); let nb = c.nearest(b, 1e-12); if na.distance_sq.sqrt() > tol || nb.distance_sq.sqrt() > tol { @@ -1366,6 +1369,29 @@ mod tests { assert_eq!(tidy.repair(&lens), lens); } + #[test] + fn rejoining_a_split_curve_tests_only_the_curves_around_it() { + // A row of 1,000 short curves; one of them is cut in three, as the sweep cuts a curve. + let mut row = BezPath::new(); + row.move_to((0.0, 0.0)); + for k in 0..1000 { + let x = f64::from(k); + row.curve_to((x + 0.3, 1.0), (x + 0.7, 1.0), (x + 1.0, 0.0)); + } + let tidy = Tidy::keeping(DEFAULT_PRECISION, [&row]); + let c = CubicBez::new((500.0, 0.0), (500.3, 1.0), (500.7, 1.0), (501.0, 0.0)); + let pieces: Vec = [0.0..0.3, 0.3..0.6, 0.6..1.0].into_iter().map(|t| Seg { c: c.subsegment(t), line: false }).collect(); + EXACT_MERGE_CURVES.with(|n| n.set(0)); + let merged = tidy_segments(pieces, false, &tidy); + let tested = EXACT_MERGE_CURVES.with(std::cell::Cell::get); + assert_eq!(merged.len(), 1); + for (got, want) in [(merged[0].c.p1, c.p1), (merged[0].c.p2, c.p2)] { + assert!(got.distance(want) < 1e-9, "{got:?} {want:?}"); + } + // Each merge attempt tests the curves whose bounds hold both ends of the run, not all 1,000. + assert!(tested <= 4, "{tested} curves tested"); + } + #[test] fn arrangement_new_budgeted_fails_on_complexity_and_open_paths() { let mut bp = BezPath::new(); diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index ced1db16e2..d8d121ecb9 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use kurbo::{CubicBez, ParamCurve, PathSeg, Point, Rect, Vec2}; +use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; @@ -85,9 +85,13 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { } /// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath -/// whose refit is one segment, or two lines that enclose no area, is refitted in two parts, cut at -/// the point farthest from its start, or in three when two still give that; one of a single segment -/// stays as it is. +/// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the +/// point farthest from its start, or in three when two still give that. When three parts still give +/// no area, straight lines follow the subpath within the tolerance, and without straight lines it +/// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose +/// an area, it stays as it is, or with straight lines follows the lines between samples of each +/// curved segment when the limits leave room for lines within the tolerance; one that is all in line +/// keeps the refit. fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); @@ -105,7 +109,12 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let across = if sp.closed && opts.smooth > 0.0 { unit(end_tangent(&segs[n - 1].c) + start_tangent(&segs[0].c)) } else { None }; let across = across.filter(|_| (0..n).all(|i| turn_deg(&segs[(i + n - 1) % n], &segs[i]) <= opts.corner_angle_deg)); let mut result = simplify_run_within(&segs, opts, MAX_RUN_SAMPLES, across); - let flat = |r: &[Seg]| r.len() < 2 || r.len() == 2 && r.iter().all(|s| s.line); + let in_line = |pts: &[Point]| { + let Some(&a) = pts.first() else { return true }; + let far = pts.iter().map(|&p| p - a).max_by(|u, v| u.hypot2().total_cmp(&v.hypot2())).unwrap_or_default(); + pts.iter().all(|&p| far.cross(p - a).abs() <= 1e-6 * far.hypot()) + }; + let flat = |r: &[Seg]| r.len() < 2 || r.iter().all(|s| s.line) && in_line(&r.iter().map(|s| s.c.p0).collect::>()); if sp.closed && flat(&result) { // Each segment in two, and the loop cut where they meet: first at the point farthest from its // start, then also at the point farthest from the line between those two. @@ -131,11 +140,84 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { if flat(&result) && k != j { result = refit(&[0, j.min(k), j.max(k), m]); } + let ctrl: Vec = segs.iter().flat_map(|s| [s.c.p0, s.c.p1, s.c.p2]).collect(); + if flat(&result) && !in_line(&ctrl) { + // Each curved segment split in 2, 4, 8 and so on, up to 1,024 pieces and 65,536 pieces in all + // with the line segments, until every piece is within the tolerance of the line between its + // ends and those lines enclose an area: with straight lines they are the result, and without + // them the loop stays as it is. When no split within those limits encloses an area, the loop + // stays as it is, or with straight lines each curved segment becomes the lines between its + // samples, up to `MAX_RUN_RESULT` lines in all with the line segments; when those do not keep + // some curved segment within the tolerance, the loop stays as it is. A loop whose points are + // all in line keeps the lines of the refit. + let near = |c: &CubicBez| [c.p1, c.p2].iter().all(|&p| Line::new(c.p0, c.p3).nearest(p, 1e-9).distance_sq.sqrt() <= opts.tolerance); + let curved = segs.iter().filter(|s| !s.line).count(); + for k in 1..=10u32 { + let parts = 1u32 << k; + if curved.saturating_mul(parts as usize).saturating_add(n - curved) > 1 << 16 { + break; + } + let at = |i: u32| f64::from(i) / f64::from(parts); + let pieces: Vec = segs + .iter() + .flat_map(|s| { + let count = if s.line { 1 } else { parts }; + (0..count).map(move |i| if s.line { s.c } else { s.c.subsegment(at(i)..at(i + 1)) }) + }) + .collect(); + let lines: Vec = pieces.iter().map(|c| Seg::line(c.p0, c.p3)).collect(); + if pieces.iter().all(near) && !flat(&lines) { + if !opts.straight_lines { + return Some(sp.clone()); + } + return segs_to_subpath(&lines, true); + } + } + if !opts.straight_lines { + return Some(sp.clone()); + } + let Some(room) = sample_room(curved, n - curved) else { + return Some(sp.clone()); + }; + let mut lines: Vec = Vec::new(); + for s in &segs { + if s.line { + lines.push(Seg::line(s.c.p0, s.c.p3)); + continue; + } + let Some(steps) = steps_within(&s.c, opts.tolerance.max(1e-6), room) else { + return Some(sp.clone()); + }; + let mut pts = Vec::new(); + sample(&s.c, steps, &mut pts, true); + lines.extend(pts.windows(2).map(|p| Seg::line(p[0], p[1]))); + } + return segs_to_subpath(&lines, true); + } } let s = segs_to_subpath(&result, sp.closed)?; Some(if opts.straight_lines { s } else { no_worse(sp, s) }) } +/// Most lines between samples of each of `curved` segments, so that they and the `kept` line segments +/// make at most [`MAX_RUN_RESULT`] lines, and each has at most [`MAX_SEGMENT_SAMPLES`]. `None` when +/// that leaves no line for some curved segment. +fn sample_room(curved: usize, kept: usize) -> Option { + let left = MAX_RUN_RESULT.checked_sub(kept)?; + if curved > left { + return None; + } + Some((left / curved.max(1)).min(MAX_SEGMENT_SAMPLES)) +} + +/// How many evenly spaced lines along `c`, at most `room`, follow it: [`sample_steps`] when that +/// fits, or fewer, but never fewer than keep `c` within `tol` of them. `None` when those do not fit +/// in `room`. +fn steps_within(c: &CubicBez, tol: f64, room: usize) -> Option { + let need = line_steps(c, tol).max(1); + (need <= room).then(|| sample_steps(c, tol).min(room).max(need)) +} + /// How far a segment may be from the lines between its samples, as a share of the tolerance. const SAMPLE_GAP: f64 = 0.005; @@ -1100,6 +1182,39 @@ mod tests { assert!(work <= 400 * pts.len(), "{work} steps for {} samples", pts.len()); } + #[test] + fn the_samples_of_a_flat_loop_and_its_line_segments_stay_within_the_result_limit() { + for (curved, kept) in [(1, 0), (32, 1), (40, 1_000_000), (1_000, MAX_RUN_RESULT - 1_000), (3, MAX_RUN_RESULT - 7)] { + let room = sample_room(curved, kept).unwrap_or_else(|| panic!("{curved} curved, {kept} kept: no room")); + assert!((1..=MAX_SEGMENT_SAMPLES).contains(&room), "{curved} curved, {kept} kept: room {room}"); + assert!(curved * room + kept <= MAX_RUN_RESULT, "{curved} curved, {kept} kept: room {room}"); + } + assert_eq!(sample_room(32, 0), Some(MAX_SEGMENT_SAMPLES)); + assert_eq!(sample_room(2, MAX_RUN_RESULT - 1), None); + assert_eq!(sample_room(1, MAX_RUN_RESULT + 5), None); + } + + #[test] + fn lines_with_too_little_room_for_the_tolerance_are_not_used() { + let c = CubicBez::new((0.0, 0.0), (0.0, 100.0), (100.0, 100.0), (100.0, 0.0)); + let tol = 0.01; + let need = line_steps(&c, tol); + assert!(need > 4, "{need}"); + assert_eq!(steps_within(&c, tol, need - 1), None); + for room in [need, need + 3, MAX_SEGMENT_SAMPLES] { + let steps = steps_within(&c, tol, room).unwrap_or_else(|| panic!("room {room}: no steps")); + assert!((need..=room).contains(&steps), "room {room}: {steps} steps"); + let mut pts = Vec::new(); + sample(&c, steps, &mut pts, true); + let lines: Vec = pts.windows(2).map(|p| Line::new(p[0], p[1])).collect(); + for i in 0..=1000 { + let p = c.eval(f64::from(i) / 1000.0); + let gap = lines.iter().map(|l| l.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + assert!(gap <= tol + 1e-9, "room {room}, {steps} steps: {gap} at {i}"); + } + } + } + #[test] fn smoothing_points_whose_arc_length_overflows_returns_every_point() { let pts: Vec = (0..40).map(|i| Point::new(if i % 2 == 0 { -1e308 } else { 1e308 }, f64::from(i))).collect(); diff --git a/crates/pathops/src/fit.rs b/crates/pathops/src/fit.rs index 6b1f4eb0c1..0411a71f40 100644 --- a/crates/pathops/src/fit.rs +++ b/crates/pathops/src/fit.rs @@ -17,6 +17,9 @@ const MAX_BULGE_SAMPLES: f64 = 1024.0; /// About how many points of a long piece its first fit uses. const COARSE_POINTS: usize = 16; +/// Most times [`fit_through_rec`] splits a run of points, which bounds its recursion. +const MAX_SPLITS: usize = 40; + /// Unit vector or `None` if (nearly) zero. pub(crate) fn unit(v: Vec2) -> Option { let l = v.hypot(); @@ -37,7 +40,7 @@ pub(crate) fn end_tangent(c: &CubicBez) -> Vec2 { /// /// `t0` is the unit tangent leaving `pts[0]`; `t1` is the unit tangent arriving at the last point /// (forward direction). Consecutive output cubics are G1 continuous. -pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec { +pub fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec { let pts = dedup(pts); if pts.len() < 2 { return Vec::new(); @@ -48,6 +51,43 @@ pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec Vec { + let pts = dedup(pts); + let mut out = Vec::new(); + if pts.len() < 2 { + return out; + } + fit_through_rec(&pts, t0, t1, tol.max(1e-9), &mut out, 0); + out +} + +/// Fits all of `pts` with one cubic, splitting at its worst point until each piece is within `tol` +/// of its points (see [`fit_cubics_through`]). `depth` bounds the recursion on hostile points. +fn fit_through_rec(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64, out: &mut Vec, depth: usize) { + let n = pts.len(); + if n == 2 { + let d = pts[0].distance(pts[1]) / 3.0; + out.push(CubicBez::new(pts[0], pts[0] + t0 * d, pts[1] - t1 * d, pts[1])); + return; + } + let (curve, err, split) = fit_single_tol(pts, t0, t1, tol); + if err <= tol || depth >= MAX_SPLITS { + out.push(curve); + return; + } + let split = split.clamp(1, n - 2); + let tc = unit(pts[split + 1] - pts[split - 1]).unwrap_or(t0); + fit_through_rec(&pts[..=split], t0, tc, tol, out, depth + 1); + fit_through_rec(&pts[split..], tc, t1, tol, out, depth + 1); +} + /// The curves of `pieces`, which follow each other along `pts` from its first point, leaving it /// along `t0`. Each curve takes up to [`MAX_JOINS`] of the pieces after its first one, as long as /// the fit of them together is within `tol`. @@ -152,6 +192,32 @@ pub(crate) fn fit_single(pts: &[Point], t0: Vec2, t1: Vec2) -> (CubicBez, f64, u fit_single_from(pts, chord_params(pts), t0, t1) } +/// [`fit_single`] that stops reparameterising once the curve is within `tol` of its points: a +/// curve already that close needs no better fit, and each Newton round reads every point. +fn fit_single_tol(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> (CubicBez, f64, usize) { + let mut u = chord_params(pts); + let mut best = generate(pts, &u, t0, t1); + let (mut best_err, mut best_split) = max_error(pts, &best, &u); + for _ in 0..MAX_REPARAM { + if best_err <= tol { + break; + } + for (i, ui) in u.iter_mut().enumerate() { + *ui = newton(&best, pts[i], *ui); + } + let c = generate(pts, &u, t0, t1); + let (e, s) = max_error(pts, &c, &u); + if e < best_err { + best = c; + best_err = e; + best_split = s; + } else { + break; + } + } + (best, best_err, best_split) +} + /// [`fit_single`] starting from the parameters `u` (one per point, 0 to 1) instead of the /// chord-length ones. pub(crate) fn fit_single_from(pts: &[Point], u: Vec, t0: Vec2, t1: Vec2) -> (CubicBez, f64, usize) { @@ -334,6 +400,25 @@ mod tests { assert!(out[0].p1.distance(c.p1) < 1.0, "{:?}", out[0]); } + /// A curve's samples are followed between the points, not chopped to the chords through + /// them: a smooth outline fitted from coarse samples must keep its bow (an outline's area + /// depends on it), unlike a polyline's samples. + #[test] + fn through_fit_bows_between_coarse_points() { + // The parabola y = 4t(1 - t) over x = 100t, sampled at 8 points. + let node = |t: f64| Point::new(100.0 * t, 4.0 * t * (1.0 - t)); + let pts: Vec = (0..=8).map(|i| node(i as f64 / 8.0)).collect(); + let (t0, t1) = (Vec2::new(1.0, 0.04).normalize(), Vec2::new(1.0, -0.04).normalize()); + let out = fit_cubics_through(&pts, t0, t1, 0.001); + for c in &out { + for k in 0..=100 { + let q = c.eval(k as f64 / 100.0); + let want = 4.0 * (q.x / 100.0) * (1.0 - q.x / 100.0); + assert!((q.y - want).abs() < 0.01, "{:?} at {q:?} wants {want}", c); + } + } + } + #[test] fn splits_when_needed() { // A zig-zag cannot be fitted with one cubic. diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index b7af34c89a..291c956786 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -26,6 +26,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 fit::{fit_cubics, fit_cubics_through}; 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, regions_within}; pub use planar::{ diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 01e89efe08..81e7f83ce7 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -424,17 +424,95 @@ fn simplify_keeps_a_closed_subpath_that_refits_to_one_curve() { ], true, )); + // A straight edge and an S curve whose midpoints all lie on that edge. + let s_curve = |h: f64, x: f64| { + PathData::single(SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, h)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(x, -h), Point::new(100.0, 0.0)), + ], + true, + )) + }; + let (s_low, s_high) = (s_curve(3.0, 0.0), s_curve(13.5, 100.0)); for straight_lines in [false, true] { for tolerance in [4.0, 10.0, 32.0] { let opts = SimplifyOptions { tolerance, straight_lines, ..Default::default() }; - for path in [&compound, &lone, &bow] { + for path in [&compound, &lone, &bow, &s_low] { let s = simplify_with(path, &opts); assert_eq!(s.subpaths.len(), path.subpaths.len(), "{tolerance} pt, straight lines {straight_lines}: {s:?}"); assert!(s.subpaths.iter().all(|sp| sp.closed && sp.anchors.len() >= 2 && sp.area().abs() > 1.0), "{s:?}"); assert!(max_deviation(path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(path, &s)); + let lines = s.subpaths.iter().all(|sp| (0..sp.segment_count()).all(|i| sp.segment_is_line(i))); + assert!(lines || !straight_lines, "{tolerance} pt: {s:?}"); } } } + // Lobes on both sides of the edge, 3.9 pt from it, stay within the tolerance. + for straight_lines in [false, true] { + let s = simplify_with(&s_high, &SimplifyOptions { tolerance: 4.0, straight_lines, ..Default::default() }); + assert!(max_deviation(&s_high, &s) <= 4.0 + 1e-6, "straight lines {straight_lines}: {}", max_deviation(&s_high, &s)); + } + // Curves whose handles lie on the line between their anchors become lines. + let thin = PathData::single(SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(30.0, 0.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(70.0, 0.0), Point::new(80.0, 0.0)), + ], + true, + )); + let s = simplify_with(&thin, &SimplifyOptions { tolerance: 4.0, straight_lines: true, ..Default::default() }); + assert!(s.subpaths.iter().all(|sp| (0..sp.segment_count()).all(|i| sp.segment_is_line(i))), "{s:?}"); + // Anchors in line on a closed path are still removed. + let in_line = PathData::single(SubPath::new([0.0, 25.0, 50.0, 100.0].map(|x| Anchor::corner(Point::new(x, 0.0))).to_vec(), true)); + let s = simplify_with(&in_line, &SimplifyOptions { tolerance: 4.0, ..Default::default() }); + assert!(s.subpaths[0].anchors.len() < 4, "{s:?}"); + let many = PathData::single(SubPath::new((0..5000).map(|i| Anchor::corner(Point::new(f64::from(i), 0.0))).collect(), true)); + for tolerance in [4.0, f64::INFINITY, f64::NAN] { + for path in [&in_line, &thin, &many] { + simplify_with(path, &SimplifyOptions { tolerance, straight_lines: true, ..Default::default() }); + } + } + // A long, thin rectangle keeps its corners. + let long = rect(0.0, 0.0, 1e9, 0.5); + let s = simplify_with(&long, &SimplifyOptions { tolerance: 0.1, straight_lines: true, ..Default::default() }); + assert!(max_deviation(&long, &s) <= 0.1 + 1e-6, "{s:?}"); +} + +/// An S curve closed by a straight edge of 20,000 anchors, whose curve shows only when it is split in +/// four, keeps its outline within the tolerance. With corner anchors on the edge, only the curve is +/// split. With smooth anchors whose handles lie along the edge, four pieces of every segment pass the +/// limit on pieces: the loop stays as it is, or with straight lines follows lines between samples. +#[test] +fn simplify_keeps_a_flat_loop_with_many_anchors_on_its_edge() { + let n = 20_000; + let step = 100.0 / f64::from(n); + let curve_anchors = vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 3.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(0.0, -3.0), Point::new(100.0, 0.0)), + ]; + let curve = PathData::single(SubPath::new(curve_anchors.clone(), false)); + for smooth_edge in [false, true] { + let mut anchors = curve_anchors.clone(); + anchors.extend((1..n).map(|i| { + let p = Point::new(100.0 - f64::from(i) * step, 0.0); + if smooth_edge { + Anchor::with_handles(p, Point::new(p.x + step / 3.0, 0.0), Point::new(p.x - step / 3.0, 0.0)) + } else { + Anchor::corner(p) + } + })); + let path = PathData::single(SubPath::new(anchors, true)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 4.0, straight_lines, ..Default::default() }); + let at = format!("smooth edge {smooth_edge}, straight lines {straight_lines}"); + assert_eq!(s.subpaths.len(), 1, "{at}"); + let sp = &s.subpaths[0]; + assert!(sp.closed && sp.area().abs() > 1.0, "{at}: area {}", sp.area()); + assert!(max_deviation(&curve, &s) <= 4.0 + 1e-6, "{at}: {}", max_deviation(&curve, &s)); + assert!(!straight_lines || (0..sp.segment_count()).all(|i| sp.segment_is_line(i)), "{at}: a curve is left"); + } + } } /// The Simplify slider's levels: 1 pt at 50, doubled for every 10 levels down and halved for every diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index d8316e94e3..f4d65398e0 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -13,7 +13,7 @@ use krilla::geom::{Path, PathBuilder, Size}; use krilla::image::Image; use krilla::num::NormalizedF32; use krilla::page::PageSettings; -use krilla::paint::{Fill, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash}; +use krilla::paint::{Fill, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash, SweepGradient}; use krilla::text::{Glyph, GlyphId, KrillaGlyph}; use kurbo::{PathEl, Shape, Vec2}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; @@ -68,6 +68,9 @@ pub(crate) struct Exporter<'a> { lab_spots: Vec<(String, vectorcraft_color::cms::Lab)>, /// Images may ask viewers to smooth them (not in PDF/A). interpolate: bool, + /// Conic gradients may be written as sweep shadings, whose PostScript calculator functions + /// PDF/A forbids; otherwise they are drawn as images ([`Self::area_paint`]). + sweeps: bool, /// Images may have 16 bits a sample (PDF 1.5 and later); in earlier files they are written at /// 8 bits ([`embed`]). sixteen_bit: bool, diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 75b87209c5..788cacea3a 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -53,7 +53,9 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let raised = for_long_pages(set, &pages)?; let set = raised.as_ref().unwrap_or(set); - let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.title.clone())); + // The file's Title is File Info's; the page information names the document, as its tab does. + let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.info_title().to_owned())); + let name = opts.title.as_deref().unwrap_or(&doc.title); // The time of writing (none on the web) dates the editing data and the page information. let now = vectorcraft_doc::metadata::output_time(); let created_at = opts.created.or(now); @@ -63,9 +65,11 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // Preserve Editing: the native document as an embedded file (`check` refused PDF/A with it). let mut warnings = set.warnings(); if raised.is_some() { - warnings.push( - "PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6".into(), - ); + warnings.push(if opts.settings.compatibility == Compatibility::Pdf14 { + "PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6".into() + } else { + "PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6".into() + }); } let native = opts.native.as_deref().filter(|_| set.preserve_editing); if let Some(native) = native { @@ -92,7 +96,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha 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()); + layer.walk(&mut |n| linked |= !n.is_ruler_guide() && n.url().is_some()); } if linked { warnings.push(format!("{} files have no links: the objects' URLs aren't clickable", set.standard.label())); @@ -106,7 +110,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; vectorcraft_doc::cancel::progress(written as u64 + 1, total, &format!("Writing page {} of {total}", written + 1)); let (m, r) = (boxes.media, boxes.bleed); - let info = if marks.page_info { crate::marks::page_info(doc, &title, i, now) } else { String::new() }; + let info = if marks.page_info { crate::marks::page_info(doc, name, i, now) } else { String::new() }; let art = crate::marks::art(doc, &marks, &boxes, bleed, &info); // The page is the media box, y down from its top-left corner (like ours), in units of // `unit` points. @@ -192,9 +196,18 @@ const MIN_PAGE_SIDE: f64 = 3.0; const MAX_PDF14_REAL: f64 = 32_767.0; /// Pages with a side longer than [`MAX_PAGE_SIDE`] are written with a `UserUnit`: in PDF 1.6 and -/// later files that aren't PDF/X files. Other files have every page in points. +/// later files that aren't PDF/X files, unless `long_pages_in_points` applies. Other files have +/// every page in points. fn writes_user_units(set: &PdfSettings) -> bool { - set.compatibility.has_user_unit() && !set.standard.is_pdfx() + set.compatibility.has_user_unit() && !set.standard.is_pdfx() && !long_pages_in_points(set) +} + +/// `long_pages_in_points` is on in a file without a standard. PDF/X files write long pages in +/// points anyway, and PDF/A files keep the `UserUnit`, which keeps their page boundaries within +/// 14,400 units (ISO 19005-2, 6.1.13). A PDF/A file at PDF 1.4 is written as PDF 1.6 to have one +/// ([`for_long_pages`]). +fn long_pages_in_points(set: &PdfSettings) -> bool { + set.long_pages_in_points && set.standard == Standard::None } /// The `UserUnit` (PDF 1.6) of a page `w` × `h` points large: 1 when both sides are at most @@ -220,20 +233,30 @@ pub fn check_page_sizes(doc: &Document, opts: &PdfOptions) -> Result<(), PdfErro /// The settings `set` is written with when one of `pages` has a side longer than /// [`MAX_PAGE_SIDE`]: a PDF 1.5 file that isn't a PDF/X file is written as PDF 1.6, which has a -/// page's `UserUnit` (`None`: `set` as it is). Other files without a `UserUnit` have the page in -/// points. The writer puts a whole number as an integer and fails a PDF 1.3 or 1.4 file that has +/// page's `UserUnit`, unless `long_pages_in_points` applies (`None`: `set` as it is). Other files +/// without a `UserUnit` have the page in points. The writer puts a whole number as an integer and fails a PDF 1.3 or 1.4 file that has /// a real number past [`MAX_PDF14_REAL`]: a page whose side is past it and not a whole number of /// points is refused here, before anything is drawn ([`page_too_long`]). fn for_long_pages(set: &PdfSettings, pages: &[(usize, PageBoxes)]) -> Result, PdfError> { if !pages.iter().any(|(_, b)| b.media.width().max(b.media.height()) > MAX_PAGE_SIDE) { return Ok(None); } - let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx()) + let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx() && !long_pages_in_points(set)) .then(|| PdfSettings { compatibility: Compatibility::Pdf16, ..set.clone() }); + // PDF/A-2 limits page boundaries to 14,400 units (ISO 19005-2, 6.1.13), and PDF 1.4 has no + // `UserUnit`: a PDF/A file at PDF 1.4 is written as PDF 1.6, with the `UserUnit` whether or + // not `long_pages_in_points` is on. + let raised = raised.or_else(|| { + (set.standard == Standard::PdfA2b && set.compatibility == Compatibility::Pdf14).then(|| PdfSettings { + compatibility: Compatibility::Pdf16, + long_pages_in_points: false, + ..set.clone() + }) + }); // The writer's test for a whole number, on the `f32` it writes. let real = |side: f64| side > MAX_PDF14_REAL && (side as f32) as i32 as f32 != side as f32; if let Some((i, b)) = pages.iter().find(|(_, b)| real(b.media.width()) || real(b.media.height())) { - page_too_long(set, *i, b.media.width().max(b.media.height()))?; + page_too_long(raised.as_ref().unwrap_or(set), *i, b.media.width().max(b.media.height()))?; } Ok(raised) } diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index d3d5f8e7fe..ff94c6759f 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -35,6 +35,7 @@ impl<'a> Exporter<'a> { knockout: doc.page_knockout, lab_spots: vec![], interpolate: set.standard != Standard::PdfA2b, + sweeps: set.standard != Standard::PdfA2b, // PDF 1.3 and 1.4 files are written with the PDF 1.4 settings ([`Writer::new`]). sixteen_bit: !matches!(set.compatibility, Compatibility::Pdf13 | Compatibility::Pdf14), compression: &set.compression, diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 390fcc3445..2143ecba61 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -254,10 +254,20 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { Some(png) } +/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image +/// it holds is still written. +const MAX_EMBED_PIXELS: u64 = 1 << 27; + /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), /// other formats decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG of 16 bits a /// sample is written at 8 bits ([`png_8_bit`]). pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool) -> Option { + // The header's size first: the writer's decoders allocate what it declares, and the encoded + // bytes of an image that is far larger than any the app reads may be a few kilobytes. + let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); + if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_EMBED_PIXELS) { + return None; + } let bytes = blob.bytes.as_ref().clone(); let direct = match blob.mime.as_str() { "image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()), @@ -281,6 +291,18 @@ mod tests { use vectorcraft_doc::{Document, ImageBlob, ImageObject}; use vectorcraft_geom::Affine; + #[test] + fn an_image_whose_header_declares_far_more_pixels_than_the_app_reads_is_left_out() { + // A real 8 × 8 PNG whose IHDR (width, height at 16..24) claims 65535 × 65535, with its CRC fixed. + let mut png = vec![]; + image::DynamicImage::ImageRgb8(image::RgbImage::new(8, 8)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png[16..24].copy_from_slice(&[0, 0, 0xFF, 0xFF, 0, 0, 0xFF, 0xFF]); + let crc = + !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); + png[29..33].copy_from_slice(&crc.to_be_bytes()); + assert!(super::embed(&ImageBlob::png(png), false, true).is_none()); + } + #[test] fn colorized_image_caches_rejected_images() { let mut doc = Document::new(10.0, 10.0); diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 2d9a9cc175..90b7ae5248 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -1,7 +1,7 @@ use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf}; use super::{ - Affine, AppearanceItem, BezPath, BlendMode, Exporter, Fill, FillRule, LineCap, LineJoin, Mark, Node, NodeKind, NormalizedF32, Paint, Path, Rect, - Shape, Stroke, StrokeAlign, StrokeDash, StrokeLayer, Surface, WrittenShape, krilla, stroke, + Affine, AppearanceItem, BezPath, BlendMode, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind, NormalizedF32, + Paint, Path, Rect, Shape, Stroke, StrokeAlign, StrokeDash, StrokeLayer, Surface, WrittenShape, krilla, stroke, }; /// An object's visual box for leaving out what is off the page. A plain group or layer also holds @@ -318,6 +318,8 @@ impl Exporter<'_> { self.node(s, c, page, false); } } + // Ruler guides draw on screen only. + NodeKind::RulerGuide { .. } => {} } self.knockout = enclosing; for _ in 0..pushes { @@ -431,20 +433,28 @@ impl Exporter<'_> { /// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which /// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot - /// inks ([`Self::perceptual_spot`])? + /// inks ([`Self::perceptual_spot`]), a conic gradient that can't be a sweep shading (in + /// PDF/A, or with more than [`super::paint::MAX_SWEEP_STOPS`] stops), or a diamond gradient + /// (four linear gradients, [`Self::diamond`])? pub(super) fn area_paint(&self, p: &Paint, fill: bool) -> bool { match p { Paint::Pattern { pattern, .. } => self.doc.pattern(pattern).is_some(), - Paint::Gradient(g) => g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill), + Paint::Gradient(g) => { + let sweep_unwritable = || !self.sweeps || g.gradient.expanded().nth(super::paint::MAX_SWEEP_STOPS).is_some(); + (g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill)) + || (g.gradient.kind == GradientKind::Conic && sweep_unwritable()) + || g.gradient.kind == GradientKind::Diamond + } _ => false, } } /// Paint the area `clip` (filled by `rule`; bounds `area`) with `p` at `transparency` (opacity, /// blend mode) when it is an [area paint](Self::area_paint) of a fill (`fill`) or a stroke: a - /// pattern's [tiling pattern](Self::tiling) (else its tile instances covering it), or an image - /// of a gradient drawn as pixels placed on `bounds` (the painted object's box, as on the - /// canvas), clipped to it. False (nothing drawn) for other paints. + /// pattern's [tiling pattern](Self::tiling) (else its tile instances covering it), a diamond + /// gradient's four linear gradients, or an image of a gradient drawn as pixels, placed on + /// `bounds` (the painted object's box, as on the canvas), clipped to it. False (nothing drawn) + /// for other paints. #[allow(clippy::too_many_arguments)] pub(super) fn area( &mut self, @@ -492,7 +502,12 @@ impl Exporter<'_> { } } } - Paint::Gradient(g) => self.field_image(s, g, bounds, area, fill), + Paint::Gradient(g) => { + let pixels = g.draws_as_pixels(fill) && !self.perceptual_spot(g, fill); + if pixels || g.gradient.kind != GradientKind::Diamond || !self.diamond(s, g, bounds, area) { + self.field_image(s, g, bounds, area, fill); + } + } _ => {} } } diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 9e4578bdca..38ab52f182 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -1,9 +1,14 @@ use super::exporter::{MAX_FIELD_PX, MAX_GRADIENT_PX, MAX_PATTERN_DEPTH, color, ctm, in_range, norm, q, to_path, writable, xf}; use super::{ Affine, Color, Exporter, GradientKind, LinearGradient, Paint, RadialGradient, Rect, SepColor, SeparationColorant, SeparationSpace, Shape, Size, - SpreadMethod, Stop, Surface, Vec2, cmyk, krilla, rgb, + SpreadMethod, Stop, Surface, SweepGradient, Vec2, cmyk, krilla, rgb, }; +/// Most stops a conic gradient's sweep shading holds: past this the PDF writer keeps only some +/// of them (its calculator function tests the stops one inside another, and viewers limit how +/// deep), so such a gradient is drawn as an image instead ([`Exporter::area_paint`]). +pub(super) const MAX_SWEEP_STOPS: usize = 97; + impl Exporter<'_> { /// A colour for the page, as the Output settings write it ([`ColorOut::color`]): without /// conversion, RGB and Lab colours of CMYK documents are separated into CMYK through the @@ -311,10 +316,36 @@ impl Exporter<'_> { .into(), ) } - // Painted areas get an image of the field ([`Self::area`]); elsewhere (gradient - // slices) the average colour stands in. - GradientKind::Freeform => { - self.warn("freeform gradients are exported as their average colour"); + // A function-based shading (ISO 32000-1, 8.7.4.5.2) whose calculator function + // turns the angle about the origin into the ramp, once around (0 to 360 + // degrees), carried onto the extent ellipse by its frame. + GradientKind::Conic => { + let frame = geom.conic_frame(); + if !writable(s, space * frame, Rect::new(-1.0, -1.0, 1.0, 1.0)) { + return None; + } + Some( + SweepGradient { + cx: 0.0, + cy: 0.0, + start_angle: 0.0, + end_angle: 360.0, + transform: xf(space * frame), + spread_method: SpreadMethod::Pad, + stops, + anti_alias: false, + } + .into(), + ) + } + // Painted areas get an image of the field, or a diamond's four linear gradients + // ([`Self::area`]); elsewhere (gradient slices) the average color stands in. + GradientKind::Freeform | GradientKind::Diamond => { + self.warn(if g.gradient.kind == GradientKind::Diamond { + "diamond gradients in gradient slices are exported as their average color" + } else { + "freeform gradients are exported as their average colour" + }); let n = g.gradient.stops.len().max(1) as f32; let mut acc = [0.0f32; 3]; for s in &g.gradient.stops { @@ -449,10 +480,43 @@ impl Exporter<'_> { g.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) } + /// Draw diamond gradient `g`, placed on `bounds`, over `area` (inside the current clip) as four + /// linear gradients, one for each quadrant of its frame, each equal to the diamond there (PDF + /// has no diamond shading; [`vectorcraft_color::GradientGeom::diamond_quadrants`]). The + /// quadrants overlap so no hairline shows between them, which needs opaque stops. False + /// (nothing drawn) for a diamond with translucent stops or without a frame, which + /// [`Self::field_image`] draws instead. + pub(super) fn diamond(&mut self, s: &mut Surface, g: &vectorcraft_color::GradientPaint, bounds: Rect, area: Rect) -> bool { + if g.gradient.stops.iter().any(|st| st.opacity < 1.0) { + return false; + } + let Some(quadrants) = g.resolve(bounds).diamond_quadrants(area.abs()) else { return false }; + self.warn("diamond gradients are exported as four linear gradients"); + let gradient = vectorcraft_color::Gradient { kind: GradientKind::Linear, ..g.gradient.clone() }; + for (outline, geom) in quadrants { + let linear = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { gradient: gradient.clone(), geom: Some(geom), ..g.clone() })); + let quadrant = kurbo::BezPath::from_vec( + outline + .iter() + .enumerate() + .map(|(i, &p)| if i == 0 { kurbo::PathEl::MoveTo(p) } else { kurbo::PathEl::LineTo(p) }) + .chain([kurbo::PathEl::ClosePath]) + .collect(), + ); + if let (Some(paint), Some(path)) = (self.paint(s, &linear, bounds), to_path(s, &quadrant)) { + s.set_stroke(None); + s.set_fill(Some(krilla::paint::Fill { paint, opacity: krilla::num::NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); + s.draw_path(&path); + s.set_fill(None); + } + } + true + } + /// Draw gradient `g`, placed on `bounds`, as an image over `area`, sampled at the document's /// raster effects resolution where it is drawn (`area` as the current transform sizes it, so /// scaled type gets its pixels too): a freeform gradient's colour field (at most - /// [`MAX_FIELD_PX`] a side), or a linear or radial gradient (at most [`MAX_GRADIENT_PX`] a side), + /// [`MAX_FIELD_PX`] a side), or a linear, radial, conic or diamond gradient (at most [`MAX_GRADIENT_PX`] a side), /// with dither's noise when it paints a fill (`fill`). A linear or radial gradient whose stops /// are all CMYK and not linked to a spot swatch is a CMYK image, unless its Perceptual curve /// has too many stops; any other is an RGB image. @@ -476,7 +540,11 @@ impl Exporter<'_> { let (cols, rows) = (along(w), along(h)); let field = freeform.then(|| g.freeform_on(b).model_field(spread_scale(b))); let cmyk_doc = self.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk; - if !freeform { + if g.gradient.kind == GradientKind::Conic { + self.warn("conic gradients drawn as pixels (dithered fills, and Perceptual ones other than spot ink shadings), in a PDF/A file or with more than 97 stops are exported as images"); + } else if g.gradient.kind == GradientKind::Diamond { + self.warn("diamond gradients drawn as pixels (dithered fills, and Perceptual ones other than spot ink shadings), with translucent stops or without an extent are exported as images"); + } else if !freeform { self.warn("linear and radial gradients drawn as pixels are exported as images"); } let ramp_inks = if freeform || self.has_spot_stop(&g.gradient) { None } else { g.ink_pixels(b, area, cols, rows, fill) }; diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 983a7dcea7..1cb0a45273 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -24,6 +24,8 @@ const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct FileInfo { + /// XMP `dc:title` (its `x-default` item, else its first), else Info `Title`. + pub title: Option, /// XMP `dc:creator` (its names joined with ", "), else Info `Author`. pub author: Option, /// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`. @@ -53,6 +55,7 @@ pub(crate) fn file_info_in(pdf: &Pdf) -> FileInfo { let mut f = packet(pdf).and_then(|p| xmp(&p)).unwrap_or_default(); let info = pdf.metadata(); let text = |b: &Option>| b.as_deref().map(text_string).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + f.title = f.title.or_else(|| text(&info.title)); f.author = f.author.or_else(|| text(&info.author)); f.description = f.description.or_else(|| text(&info.subject)); f.keywords = f.keywords.or_else(|| text(&info.keywords).map(|k| split(&k)).filter(|k| !k.is_empty())); @@ -90,6 +93,7 @@ fn xmp(packet: &[u8]) -> Option { let creators = get(DC, "creator"); let subjects = get(DC, "subject"); Some(FileInfo { + title: first(DC, "title"), author: (!creators.is_empty()).then(|| creators.join(", ")), description: first(DC, "description"), keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 61acbfc8ea..945c082a26 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -26,6 +26,7 @@ impl<'p> Builder<'p> { actual: Default::default(), images: HashMap::new(), image_keys: HashMap::new(), + raster_scales: HashMap::new(), cmyk_keys: HashSet::new(), separation_paints: HashMap::new(), opaque: HashSet::new(), diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 2fb6bb9c80..c21e51dbb5 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -285,6 +285,12 @@ impl<'a> Device<'a> for Builder<'_> { self.add_image(key, || Some((ImageBlob::new("image/jpeg", bytes), w, h)), transform); return; } + // Drawn before: the image is there already, so its pixels aren't converted again. + if let Some(sf) = self.raster_scales.get(&key).copied().filter(|_| self.image_keys.contains_key(&key)) { + let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); + self.add_image(key, || None, xf); + return; + } let mut decoded: Option = None; r.with_rgba( |img, alpha| { @@ -303,6 +309,7 @@ impl<'a> Device<'a> for Builder<'_> { self.warn("an image could not be decoded and was skipped"); return; }; + self.raster_scales.insert(key, sf); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf); } diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 93a84ae688..419952b017 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -85,6 +85,9 @@ pub(super) struct Builder<'p> { pub(super) actual: super::actual_text::ActualText, pub(super) images: HashMap, pub(super) image_keys: HashMap, + /// The scale factors of each decoded raster by its key: drawn again, it is placed from them + /// without its pixels being decoded and converted again. + pub(super) raster_scales: HashMap, /// The images kept with their CMYK samples ([`crate::import_image`]). pub(super) cmyk_keys: HashSet, /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 9263bcd5a3..4f4e35dd3e 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -455,12 +455,15 @@ fn blank_tail(mut bytes: &[u8]) -> bool { } } -struct Walker<'w, 'p> { +pub(crate) struct Walker<'w, 'p> { ocgs: &'w mut Ocgs, /// The groups that are off for the interpreter (none once [`all_on`] turned them on). off: HashSet, xref: &'p craft_pdf::syntax::xref::XRef, - fonts: &'w mut FontNames, + pub(crate) fonts: &'w mut FontNames, + /// The font dictionaries ([`Dict::cache_key`]) whose fonts were noted: a form drawn again with + /// the same resources isn't read for its fonts again. + pub(crate) font_dicts: HashSet, visible: Vec, ops: usize, max_ops: usize, @@ -632,6 +635,9 @@ impl Walker<'_, '_> { } fn note_fonts(&mut self, res: &Resources<'_>) { + if !self.font_dicts.insert(res.fonts.cache_key()) { + return; + } for key in res.fonts.keys() { if let Some(f) = res.fonts.get::>(key.as_ref()) && let Some(name) = font_name(&f) @@ -1049,13 +1055,20 @@ pub(crate) fn scan_page(page: &Page<'_>, ocgs: &mut Ocgs, all_on: bool, fonts: & if scan.cut { Err(incomplete_content()) } else { Ok(scan) } } -fn walk_page<'w, 'p>(page: &Page<'p>, ocgs: &'w mut Ocgs, all_on: bool, fonts: &'w mut FontNames, max_form_bytes: usize) -> Walker<'w, 'p> { +pub(crate) fn walk_page<'w, 'p>( + page: &Page<'p>, + ocgs: &'w mut Ocgs, + all_on: bool, + fonts: &'w mut FontNames, + max_form_bytes: usize, +) -> Walker<'w, 'p> { let off = if all_on { HashSet::new() } else { ocgs.off.clone() }; let mut w = Walker { ocgs, off, xref: page.xref(), fonts, + font_dicts: HashSet::new(), visible: vec![], ops: 0, max_ops: max_ops(), diff --git a/crates/pdf/src/import_shading.rs b/crates/pdf/src/import_shading.rs index c80b2a29b4..2cafbf010a 100644 --- a/crates/pdf/src/import_shading.rs +++ b/crates/pdf/src/import_shading.rs @@ -1,7 +1,9 @@ //! Shadings: axial and radial ones become gradients (their stops sampled from the shading //! function in its own colour model; an end that doesn't extend clips the painted area), a -//! function-based one whose colour changes along one axis a linear gradient (else its average -//! colour; all of them within one budget of function evaluations per import), patch and triangle +//! function-based one whose color changes along one axis a linear gradient, one whose color +//! turns around the origin of its space a conic gradient, and one whose color is the same along +//! each square about that origin a diamond gradient (else its average color; all of them +//! within one budget of function evaluations per import), patch and triangle //! meshes become gradient meshes, a gradient drawn through a luminosity mask that is //! the same gradient in grey (how stop opacity is written) gets its opacity stops back, and a shape //! clipping a gradient that fills it becomes one path with the gradient. @@ -159,7 +161,7 @@ impl FunctionBudget { /// What a function-based shading comes in as ([`function_paint`]). pub(crate) enum FunctionPaint { - /// Its colour changes along one axis: a linear gradient. + /// Its color changes along one axis (a linear gradient) or around the origin (a conic one). Gradient(Box), /// It has no gradient: the colour it averages to. Average(Color), @@ -179,7 +181,10 @@ pub(crate) fn function_paint( if !matches!(sp.shading.shading_type.as_ref(), ShadingType::FunctionBased { .. }) { return None; } - Some(match function_gradient(sp, colors, inks, budget) { + let gradient = function_gradient(sp, colors, inks, budget) + .or_else(|| function_sweep(sp, colors, inks, budget)) + .or_else(|| function_diamond(sp, colors, inks, budget)); + Some(match gradient { Some(g) => FunctionPaint::Gradient(Box::new(g)), None => function_average(sp, budget).map_or(FunctionPaint::Unread, FunctionPaint::Average), }) @@ -257,6 +262,215 @@ fn function_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option< _ => return None, }; let point = |s: f32| if along_x { (lerp(x0, x1, s), lerp(y0, y1, 0.5)) } else { (lerp(x0, x1, 0.5), lerp(y0, y1, s)) }; + let out = function_stops(sp, function, colors, inks, budget, &point)?; + let p = |s: f32| { + let (x, y) = point(s); + Point::new(x as f64, y as f64) + }; + let mut geom = GradientGeom { start: p(0.0), end: p(1.0), aspect: 1.0, focal: None }; + geom.transform(sp.matrix * *matrix, GradientKind::Linear); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, out)); + g.geom = Some(geom); + // It paints only over its domain ([`extend_clip`]). + Some(g) +} + +/// A function-based shading (type 1) whose color turns around the origin of its space and stays +/// the same along each ray from it (how a conic gradient is written: a function of the angle, +/// ISO 32000-1 8.7.4.5.2, as the calculator function's `atan` gives it, 7.10.5) as a conic +/// gradient, its vector along the space's x axis and its sweep towards its y axis: stops sampled +/// around a circle about the origin, as [`function_stops`] samples them. When the origin lies +/// outside the domain (a conic whose center is off the painted area), the stops are read across +/// the turns the domain shows, and the colors there extend to the rest of the sweep. `None` when +/// the color changes along a ray or doesn't change from ray to ray, the stops would be more than +/// [`MAX_FUNCTION_STOPS`], or `budget` runs out (leaving [`AVERAGE_EVALUATIONS`] for +/// [`function_average`]). +fn function_sweep(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option<&[String]>, budget: &FunctionBudget) -> Option { + use std::f32::consts::TAU; + let ShadingType::FunctionBased { matrix, .. } = sp.shading.shading_type.as_ref() else { return None }; + let (function, domain) = function_domain(sp)?; + let [x0, x1, y0, y1] = domain; + let rgb = |x: f32, y: f32| function_rgb(sp, function, x, y, budget, AVERAGE_EVALUATIONS); + let around = x0 < 0.0 && x1 > 0.0 && y0 < 0.0 && y1 > 0.0; + // The angles the domain shows: once around, ending just before the seam (where the angle + // starts again at 0), or those its corners span seen from outside it. + let (a0, a1) = if around { (0.0, TAU * (1.0 - SWEEP_SEAM)) } else { seen_angles(domain)? }; + // Around the origin, the circle the stops are read on, well inside the domain. + let inner = 0.25 * (-x0).min(x1).min(-y0).min(y1); + // Where the ray at angle `a` runs through the domain (from that circle around the origin). + let ray = |a: f32| ray_in_domain(a, domain).map(|(near, far)| if around { (inner, far) } else { (near, far) }); + // Along each test ray (off round angles), the color near where it enters the domain, halfway + // through and near where it leaves is the same. Outside, the first is a little way in, off the + // origin when the domain's edge runs through it. + let mut first = None; + let mut turns = false; + let enter = if around { 0.0 } else { 0.05 }; + for i in 0..=FUNCTION_GRID { + let a = a0 + (a1 - a0) * grid_at(i); + let (dx, dy) = (a.cos(), a.sin()); + let (near, far) = ray(a)?; + let at = |f: f32| near + (far - near) * f; + let c = rgb(at(enter) * dx, at(enter) * dy)?; + for r in [at(0.5), at(0.9)] { + if !same_rgb(rgb(r * dx, r * dy)?, c) { + return None; + } + } + match first { + None => first = Some(c), + Some(f) => turns |= !same_rgb(f, c), + } + } + if !turns { + return None; + } + // The stops of turns `from..to` (as fractions of a turn from the space's x axis; `angle` gives + // the angle of a turn), read where each ray enters the domain, or halfway through it outside. + let mut read = |from: f32, to: f32, angle: &dyn Fn(f32) -> f32| -> Option> { + let point = |s: f32| { + let a = angle(from + (to - from) * s); + let (near, far) = ray(a).unwrap_or((0.0, 0.0)); + let r = if around { near } else { (near + far) / 2.0 }; + (r * a.cos(), r * a.sin()) + }; + let mut stops = function_stops(sp, function, colors, inks, budget, &point)?; + for s in &mut stops { + s.offset = from + (to - from) * s.offset; + } + Some(stops) + }; + let out = if around { + read(0.0, 1.0 - SWEEP_SEAM, &|t| t * TAU)? + } else { + let t0 = (a0 / TAU).rem_euclid(1.0); + let t1 = t0 + (a1 - a0) / TAU; + let angle = |t: f32| a0 + (t - t0) * TAU; + if t1 <= 1.0 { + read(t0, t1, &angle)? + } else { + // The turns it shows run on past the seam: those after it first, then those before. + let mut out = read(0.0, t1 - 1.0, &|t| angle(t + 1.0))?; + out.extend(read(t0, 1.0 - SWEEP_SEAM, &angle)?); + out + } + }; + if out.len() > MAX_FUNCTION_STOPS { + return None; + } + let mut geom = GradientGeom { start: Point::ZERO, end: Point::new(1.0, 0.0), aspect: 1.0, focal: None }; + geom.transform(sp.matrix * *matrix, GradientKind::Conic); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, out)); + g.geom = Some(geom); + // It paints only over its domain ([`extend_clip`]). + Some(g) +} + +/// A function-based shading (type 1) whose domain holds the origin of its space and whose color +/// is the same along each square about it with corners on the axes (a function of `abs(x) + +/// abs(y)`, as a calculator function gives it, ISO 32000-1 7.10.5) as a diamond gradient, its +/// vector along the space's x axis to the corner of the largest such square the domain reaches +/// (through the domain's farthest corner): stops sampled from the origin out to that corner, as +/// [`function_stops`] samples them. `None` when the domain does not hold the origin, the color +/// differs between grid points on one square or doesn't change from square to square, the stops +/// would be more than [`MAX_FUNCTION_STOPS`], or `budget` runs out (leaving +/// [`AVERAGE_EVALUATIONS`] for [`function_average`]). +fn function_diamond(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option<&[String]>, budget: &FunctionBudget) -> Option { + let ShadingType::FunctionBased { matrix, .. } = sp.shading.shading_type.as_ref() else { return None }; + let (function, domain) = function_domain(sp)?; + let [x0, x1, y0, y1] = domain; + if !(x0 < 0.0 && x1 > 0.0 && y0 < 0.0 && y1 > 0.0) { + return None; + } + let rgb = |x: f32, y: f32| function_rgb(sp, function, x, y, budget, AVERAGE_EVALUATIONS); + let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t; + // The farthest corner of the domain, and a point on each square up to it inside the domain: + // along the x axis toward that corner, then up its side. + let (fx, fy) = (if x1 >= -x0 { x1 } else { x0 }, if y1 >= -y0 { y1 } else { y0 }); + let reach = fx.abs() + fy.abs(); + let on_square = |level: f32| { + let x = level.clamp(0.0, fx.abs()); + (x.copysign(fx), (level - x).clamp(0.0, fy.abs()).copysign(fy)) + }; + // Each grid point has the color of that point on its square, and the color changes from + // square to square. + let mut turns = false; + let origin = rgb(0.0, 0.0)?; + for j in 0..=FUNCTION_GRID { + for i in 0..=FUNCTION_GRID { + let (x, y) = (lerp(x0, x1, grid_at(i)), lerp(y0, y1, grid_at(j))); + let (sx, sy) = on_square(x.abs() + y.abs()); + let on_path = rgb(sx, sy)?; + if !same_rgb(rgb(x, y)?, on_path) { + return None; + } + turns |= !same_rgb(on_path, origin); + } + } + if !turns { + return None; + } + let out = function_stops(sp, function, colors, inks, budget, &|s: f32| on_square(s * reach))?; + let mut geom = GradientGeom { start: Point::ZERO, end: Point::new(f64::from(reach), 0.0), aspect: 1.0, focal: None }; + geom.transform(sp.matrix * *matrix, GradientKind::Diamond); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, out)); + g.geom = Some(geom); + // It paints only over its domain ([`extend_clip`]). + Some(g) +} + +/// How far short of a whole turn [`function_sweep`] reads the last stop: just before the seam. +const SWEEP_SEAM: f32 = 1e-4; + +/// The angles (radians, the first the smaller, less than half a turn apart) at which rays from the +/// origin cross domain `[x0, x1, y0, y1]`, which does not hold the origin, kept a little inside the +/// angles of its corners; `None` when the domain shows no angles. +fn seen_angles([x0, x1, y0, y1]: [f32; 4]) -> Option<(f32, f32)> { + use std::f32::consts::{PI, TAU}; + let mid = ((y0 + y1) / 2.0).atan2((x0 + x1) / 2.0); + let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY); + for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] { + // A corner on the origin has no angle. + if x.hypot(y) > 1e-6 { + let r = (y.atan2(x) - mid + PI).rem_euclid(TAU) - PI; + (lo, hi) = (lo.min(r), hi.max(r)); + } + } + let margin = (hi - lo) * 0.01; + (hi - lo > 1e-4 && (hi - lo).is_finite()).then_some((mid + lo + margin, mid + hi - margin)) +} + +/// Where the ray from the origin at angle `a` (radians) runs through domain `[x0, x1, y0, y1]`: +/// its distances from the origin where it enters (0 when the domain holds the origin) and +/// leaves; `None` when it misses the domain. +fn ray_in_domain(a: f32, [x0, x1, y0, y1]: [f32; 4]) -> Option<(f32, f32)> { + let (mut near, mut far) = (0.0f32, f32::INFINITY); + for (d, lo, hi) in [(a.cos(), x0, x1), (a.sin(), y0, y1)] { + if d.abs() < 1e-6 { + if lo > 0.0 || hi < 0.0 { + return None; + } + continue; + } + let (t0, t1) = (lo / d, hi / d); + (near, far) = (near.max(t0.min(t1)), far.min(t0.max(t1))); + } + (far > near && far.is_finite()).then_some((near, far)) +} + +/// The stops of a function-based shading's function `function` read along `point` (0..1 to a +/// point of the domain): sampled at [`FUNCTION_SAMPLES`] even steps, each hard color change two +/// stops at one offset, and stops between which the color runs straight left out. `None` when +/// they would be more than [`MAX_FUNCTION_STOPS`], or `budget` runs out (leaving +/// [`AVERAGE_EVALUATIONS`]). +fn function_stops( + sp: &ShadingPattern, + function: &ShadingFunction, + colors: &mut Colors<'_>, + inks: Option<&[String]>, + budget: &FunctionBudget, + point: &dyn Fn(f32) -> (f32, f32), +) -> Option> { + let rgb = |x: f32, y: f32| function_rgb(sp, function, x, y, budget, AVERAGE_EVALUATIONS); let color_of = |s: f32| { let (x, y) = point(s); rgb(x, y) @@ -311,19 +525,7 @@ fn function_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option< out.push(shading_stop(colors, space, value(read).as_deref(), offset, rgb)); } } - if out.len() > MAX_FUNCTION_STOPS { - return None; - } - let p = |s: f32| { - let (x, y) = point(s); - Point::new(x as f64, y as f64) - }; - let mut geom = GradientGeom { start: p(0.0), end: p(1.0), aspect: 1.0, focal: None }; - geom.transform(sp.matrix * *matrix, GradientKind::Linear); - let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, out)); - g.geom = Some(geom); - // It paints only over its domain ([`extend_clip`]). - Some(g) + (out.len() <= MAX_FUNCTION_STOPS).then_some(out) } /// The colour a function-based shading averages to over its domain, for one that has no gradient diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 116d1cf0c7..e367221d59 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -211,23 +211,46 @@ pub(crate) fn verify(pdf: &[u8], standard: Standard) -> Result<(), PdfError> { Ok(()) } -/// `pdf` without its streams' data (dictionaries and the rest of the syntax), so that what is -/// looked for there isn't found in image or font bytes. +/// `pdf` without its streams' data, the text of its literal strings and its comments (dictionaries +/// and the rest of the syntax), so that what is looked for there isn't found in image or font +/// bytes, or in a string such as the file identifier, whose base64 hash can hold `/BM`. fn without_streams(pdf: &[u8]) -> Vec { let mut out = Vec::with_capacity(pdf.len().min(1 << 20)); let mut at = 0; - while let Some(s) = find(pdf, b"stream", at) { - let data = s + b"stream".len(); - // `endstream` itself, or a stream keyword that isn't one (inside a name or string). - if (s >= 3 && pdf.get(s - 3..s) == Some(b"end")) || !pdf.get(data).is_some_and(|b| matches!(b, b'\r' | b'\n')) { - out.extend_from_slice(pdf.get(at..data).unwrap_or_default()); - at = data; - continue; + while let Some(&b) = pdf.get(at) { + match b { + // A literal string: parentheses nest, and a backslash escapes the next byte. + b'(' => { + out.extend_from_slice(b"()"); + let mut depth = 0usize; + at += 1; + while let Some(&c) = pdf.get(at) { + at += 1; + match c { + b'\\' => at += 1, + b'(' => depth += 1, + b')' if depth == 0 => break, + b')' => depth -= 1, + _ => {} + } + } + } + // A comment, to the end of its line. + b'%' => at += pdf.get(at..).unwrap_or_default().iter().take_while(|c| !matches!(c, b'\r' | b'\n')).count(), + // A stream keyword (not `endstream`, and followed by its end of line): its data is left out. + b's' if pdf.get(at..at + 6) == Some(b"stream") + && !(at >= 3 && pdf.get(at - 3..at) == Some(b"end")) + && pdf.get(at + 6).is_some_and(|c| matches!(c, b'\r' | b'\n')) => + { + out.extend_from_slice(b"stream"); + at = find(pdf, b"endstream", at + 6).unwrap_or(pdf.len()); + } + _ => { + out.push(b); + at += 1; + } } - out.extend_from_slice(pdf.get(at..data).unwrap_or_default()); - at = find(pdf, b"endstream", data).unwrap_or(pdf.len()); } - out.extend_from_slice(pdf.get(at..).unwrap_or_default()); out } diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index 17f37f90b8..710037a7c1 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -236,6 +236,11 @@ pub struct PdfSettings { /// Keep the layers whose Print option is off (they are left out otherwise, unless /// `create_layers` is on). pub include_non_printing: bool, + /// Write a page with a side longer than 14,400 pt (200 in) at its size in points, without a + /// `UserUnit`, at every PDF version, in files without a standard (off, and in PDF/A files: + /// PDF 1.6 and later files that aren't PDF/X files write it with a `UserUnit`, and PDF 1.5 + /// files are written as PDF 1.6 for it). + pub long_pages_in_points: bool, pub compression: CompressionSettings, pub marks: MarkSettings, pub bleed: BleedSettings, diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index af744437d5..d8238d8038 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -15,7 +15,9 @@ mod cmykblend; mod cmykimages; mod colorize; mod compression; +mod conic; mod dashalign; +mod diamond; mod editing; mod encrypt; mod file_info; diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 97388ea313..f81fc17514 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -493,3 +493,21 @@ fn a_duotone_devicen_image_still_opens_as_rgb() { assert_eq!(blobs.len(), 1); assert!(!blobs[0].0.is_cmyk() && !blobs[0].1, "RGB, not colorized"); } + +/// A raster drawn again is placed from what the first drawing found, as the same image at its own +/// size, without its pixels being converted again. +#[test] +fn a_raster_drawn_twice_is_one_image_placed_twice() { + let content = "q 80 0 0 10 10 50 cm /Im1 Do Q q 40 0 0 10 10 20 cm /Im1 Do Q"; + let r = separation_report("/DeviceRGB", 2, 8, "", "FF0000 00FF00", &[], content); + let mut placed = vec![]; + r.document.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + placed.push((im.key.clone(), im.xf.as_coeffs()[0])); + } + }); + assert_eq!(placed.len(), 2, "{placed:?}"); + assert_eq!(placed[0].0, placed[1].0); + assert!(placed[0].1 > placed[1].1 * 1.9 && placed[0].1 < placed[1].1 * 2.1, "{placed:?}"); + assert_eq!(r.document.images.len(), 1); +} diff --git a/crates/pdf/src/tests/conic.rs b/crates/pdf/src/tests/conic.rs new file mode 100644 index 0000000000..477a4fb662 --- /dev/null +++ b/crates/pdf/src/tests/conic.rs @@ -0,0 +1,190 @@ +//! Conic gradients as function-based shadings (ISO 32000-1, 8.7.4.5.2) whose calculator function +//! turns the angle about the center into the ramp: written exactly, read back as conic gradients, +//! and drawn as images where a sweep shading can't be written. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, Document, Node}; +use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_testkit::raster::{assert_similar, render_artboard}; + +use crate::*; + +/// A page-sized square filled with `gradient` placed on `geom`. +fn doc(gradient: Gradient, geom: GradientGeom) -> Document { + let mut gp = GradientPaint::new(gradient); + gp.geom = Some(geom); + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let ap = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0); + d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), ap)).unwrap(); + d +} + +/// Red to green to blue, once around. +fn rgb_conic() -> Gradient { + let stops = vec![ + GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), + GradientStop::new(0.5, Color::rgb(0.0, 1.0, 0.0)), + GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)), + ]; + Gradient::new(GradientKind::Conic, stops) +} + +/// The first gradient fill in `d`. +fn gradient(d: &Document) -> GradientPaint { + let mut out = None; + d.walk(|n| { + if let (None, Paint::Gradient(g)) = (&out, n.appearance.fill_paint()) { + out = Some(*g.clone()); + } + }); + out.expect("a gradient fill") +} + +/// Held while a test imports function-based shadings, so tests that count evaluations count only +/// their own ([`super::import_fidelity::SHADINGS`]). +fn shadings() -> std::sync::MutexGuard<'static, ()> { + super::import_fidelity::SHADINGS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +fn uncompressed(d: &Document, o: &PdfOptions) -> (String, Vec) { + let report = export_with_report(d, o).unwrap(); + (String::from_utf8_lossy(&report.bytes).into_owned(), report.warnings) +} + +#[test] +fn a_conic_is_written_as_a_sweep_shading() { + let geom = GradientGeom { start: Point::new(100.0, 100.0), end: Point::new(180.0, 60.0), aspect: 0.6, focal: None }; + let (text, warnings) = uncompressed(&doc(rgb_conic(), geom), &PdfOptions::uncompressed()); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(text.contains("/ShadingType 1"), "a function-based shading"); + assert!(text.contains("/FunctionType 4") && text.contains("atan"), "its function turns the angle into the ramp"); + assert!(!text.contains("/ShadingType 2") && !text.contains("/ShadingType 3"), "no axial or radial stand-in"); + // One without an extent still has its sweep. + let c = Point::new(100.0, 100.0); + let (text, _) = uncompressed(&doc(rgb_conic(), GradientGeom { start: c, end: c, aspect: 1.0, focal: None }), &PdfOptions::uncompressed()); + assert!(text.contains("/ShadingType 1")); +} + +/// Written and read back, a conic is a conic on the same frame with the same colors around it, +/// squashed, turned or mirrored. +#[test] +fn a_conic_comes_back_as_a_conic() { + let _held = shadings(); + let c = Point::new(100.0, 100.0); + for geom in [ + GradientGeom { start: c, end: Point::new(170.0, 100.0), aspect: 1.0, focal: None }, + GradientGeom { start: Point::new(90.0, 110.0), end: Point::new(150.0, 60.0), aspect: 0.5, focal: None }, + GradientGeom { start: c, end: Point::new(100.0, 40.0), aspect: -1.0, focal: None }, + ] { + let d = doc(rgb_conic(), geom); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let g = gradient(&back); + assert_eq!(g.gradient.kind, GradientKind::Conic, "{geom:?}"); + let got = g.geom.unwrap(); + assert!(got.start.distance(geom.start) < 0.05 && got.is_mirrored() == geom.is_mirrored(), "{geom:?} → {got:?}"); + for p in [Point::new(30.0, 100.0), Point::new(100.0, 170.0), Point::new(140.0, 60.0), Point::new(60.0, 40.0), Point::new(185.0, 130.0)] { + let want = rgb_conic().sample(geom.param_at(GradientKind::Conic, p) as f32).0.to_rgb(); + let have = g.gradient.sample(got.param_at(GradientKind::Conic, p) as f32).0.to_rgb(); + assert!(want.iter().zip(have).all(|(a, b)| (a - b).abs() < 0.03), "{geom:?} at {p:?}: {want:?} vs {have:?}"); + } + assert_similar(&render_artboard(&back), &render_artboard(&d), 4.0, 0.01); + } +} + +/// A conic whose center lies off the painted square, so the shading's domain does not hold its +/// origin, comes back as a conic with the colors the square shows, the seam among them or not. +#[test] +fn a_conic_centered_off_the_object_comes_back_as_a_conic() { + let _held = shadings(); + for geom in [ + // The seam points into the square. + GradientGeom { start: Point::new(-50.0, 100.0), end: Point::new(30.0, 100.0), aspect: 1.0, focal: None }, + // The seam points away from it. + GradientGeom { start: Point::new(-50.0, 100.0), end: Point::new(-50.0, 20.0), aspect: 1.0, focal: None }, + // Above it, mirrored and squashed. + GradientGeom { start: Point::new(120.0, -60.0), end: Point::new(170.0, -60.0), aspect: -0.5, focal: None }, + ] { + let d = doc(rgb_conic(), geom); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let g = gradient(&back); + assert_eq!(g.gradient.kind, GradientKind::Conic, "{geom:?}"); + let got = g.geom.unwrap(); + assert!(got.start.distance(geom.start) < 0.05 && got.is_mirrored() == geom.is_mirrored(), "{geom:?} → {got:?}"); + // Off the seam: on it, either side's color is right. + for p in [Point::new(5.0, 112.0), Point::new(100.0, 195.0), Point::new(195.0, 5.0), Point::new(60.0, 40.0), Point::new(185.0, 130.0)] { + let want = rgb_conic().sample(geom.param_at(GradientKind::Conic, p) as f32).0.to_rgb(); + let have = g.gradient.sample(got.param_at(GradientKind::Conic, p) as f32).0.to_rgb(); + assert!(want.iter().zip(have).all(|(a, b)| (a - b).abs() < 0.03), "{geom:?} at {p:?}: {want:?} vs {have:?}"); + } + assert_similar(&render_artboard(&back), &render_artboard(&d), 4.0, 0.01); + } +} + +/// A conic with translucent stops comes back as a conic with their opacity. +#[test] +fn a_translucent_conic_comes_back_with_its_opacity() { + let _held = shadings(); + let mut ramp = rgb_conic(); + ramp.stops[1].opacity = 0.4; + let geom = GradientGeom { start: Point::new(100.0, 100.0), end: Point::new(170.0, 100.0), aspect: 1.0, focal: None }; + let d = doc(ramp.clone(), geom); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let g = gradient(&back); + assert_eq!(g.gradient.kind, GradientKind::Conic); + let got = g.geom.unwrap(); + for p in [Point::new(30.0, 100.0), Point::new(100.0, 170.0), Point::new(140.0, 60.0), Point::new(185.0, 130.0)] { + let (wc, wo) = ramp.sample(geom.param_at(GradientKind::Conic, p) as f32); + let (hc, ho) = g.gradient.sample(got.param_at(GradientKind::Conic, p) as f32); + assert!((wo - ho).abs() < 0.03, "at {p:?}: opacity {wo} vs {ho}"); + assert!(wc.to_rgb().iter().zip(hc.to_rgb()).all(|(a, b)| (a - b).abs() < 0.03), "at {p:?}"); + } + assert_similar(&render_artboard(&back), &render_artboard(&d), 4.0, 0.01); +} + +/// A sweep shading holds up to 97 stops: a conic with that many is a sweep, and one more makes +/// it an image. +#[test] +fn a_conic_of_97_stops_is_a_sweep_and_98_an_image() { + let geom = GradientGeom { start: Point::new(100.0, 100.0), end: Point::new(180.0, 100.0), aspect: 1.0, focal: None }; + let stops = |n: usize| -> Gradient { + let v = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, Color::rgb((i % 2) as f32, 0.0, 1.0 - (i % 2) as f32))).collect(); + Gradient::new(GradientKind::Conic, v) + }; + for (n, sweep) in [(97, true), (98, false)] { + let g = stops(n); + assert_eq!(g.expanded().count(), n, "every stop is its own"); + let (text, warnings) = uncompressed(&doc(g, geom), &PdfOptions::uncompressed()); + assert_eq!(text.contains("/FunctionType 4"), sweep, "{n} stops"); + assert_eq!(text.contains("/ShadingType 1"), sweep, "{n} stops"); + assert_eq!(warnings.iter().any(|w| w.contains("conic gradients") && w.contains("images")), !sweep, "{n} stops: {warnings:?}"); + } +} + +/// PDF/A forbids calculator functions, and a sweep shading holds at most 97 stops: such a conic +/// is drawn as an image of its colors, with a warning. +#[test] +fn a_conic_a_sweep_cannot_hold_is_an_image() { + let _held = shadings(); + let geom = GradientGeom { start: Point::new(100.0, 100.0), end: Point::new(180.0, 100.0), aspect: 1.0, focal: None }; + let mut o = PdfOptions::uncompressed(); + (o.settings.standard, o.settings.compatibility) = (Standard::PdfA2b, Standard::PdfA2b.version()); + let many: Vec = + (0..=120).map(|i| GradientStop::new(i as f32 / 120.0, Color::rgb(i as f32 / 120.0, 0.0, 1.0 - i as f32 / 120.0))).collect(); + for (case, d, o) in + [("PDF/A", doc(rgb_conic(), geom), o), ("121 stops", doc(Gradient::new(GradientKind::Conic, many), geom), PdfOptions::uncompressed())] + { + let (text, warnings) = uncompressed(&d, &o); + assert!(!text.contains("/FunctionType 4") && !text.contains("atan"), "{case}: no calculator function"); + assert!(text.contains("/Image") && !text.contains("/ShadingType"), "{case}: an image of the sweep"); + assert!(warnings.iter().any(|w| w.contains("conic gradients") && w.contains("images")), "{case}: {warnings:?}"); + // Read back, the image shows the sweep where the canvas draws it. + let back = import(&export(&d, &o).unwrap()).unwrap(); + let (want, got) = (render_artboard(&d), render_artboard(&back)); + for (x, y) in [(150, 120), (100, 160), (40, 100), (100, 40), (160, 80), (30, 30), (170, 170)] { + let (a, b) = (want.over_white(x, y), got.over_white(x, y)); + assert!(a.iter().zip(b).all(|(p, q)| p.abs_diff(q) <= 12), "{case} at ({x}, {y}): {a:?} vs {b:?}"); + } + } +} diff --git a/crates/pdf/src/tests/diamond.rs b/crates/pdf/src/tests/diamond.rs new file mode 100644 index 0000000000..8f0e4d8946 --- /dev/null +++ b/crates/pdf/src/tests/diamond.rs @@ -0,0 +1,118 @@ +//! Diamond gradients (PDF has no diamond shading): four axial shadings, one for each quadrant of +//! the diamond's frame and equal to it there, drawn as the canvas draws the diamond; an image +//! where the gradient is drawn as pixels or has no extent. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, Document, Node}; +use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_testkit::raster::{assert_similar, render_artboard}; + +use crate::*; + +/// A page-sized square filled with `gradient` placed on `geom`. +fn doc(gradient: Gradient, geom: GradientGeom) -> Document { + let mut gp = GradientPaint::new(gradient); + gp.geom = Some(geom); + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let ap = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0); + d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), ap)).unwrap(); + d +} + +/// Red to green to blue from the center out. +fn rgb_diamond() -> Gradient { + let stops = vec![ + GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), + GradientStop::new(0.5, Color::rgb(0.0, 1.0, 0.0)), + GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)), + ]; + Gradient::new(GradientKind::Diamond, stops) +} + +/// Turned and stretched across its vector, off the square's center. +fn placed() -> GradientGeom { + GradientGeom { start: Point::new(90.0, 110.0), end: Point::new(150.0, 70.0), aspect: 0.6, focal: None } +} + +fn uncompressed(d: &Document, o: &PdfOptions) -> (String, Vec) { + let report = export_with_report(d, o).unwrap(); + (String::from_utf8_lossy(&report.bytes).into_owned(), report.warnings) +} + +/// Written as four axial shadings and read back, a diamond draws as the canvas draws it, with no +/// hairline between the quadrants: level and placed, and in PDF/A, which allows axial shadings. +#[test] +fn a_diamond_is_written_as_four_axial_shadings() { + let level = GradientGeom::fit(GradientKind::Diamond, Rect::new(0.0, 0.0, 200.0, 200.0), 0.0); + let mut pdfa = PdfOptions::uncompressed(); + (pdfa.settings.standard, pdfa.settings.compatibility) = (Standard::PdfA2b, Standard::PdfA2b.version()); + for (case, d, o) in [ + ("level", doc(rgb_diamond(), level), PdfOptions::uncompressed()), + ("placed", doc(rgb_diamond(), placed()), PdfOptions::uncompressed()), + ("PDF/A", doc(rgb_diamond(), placed()), pdfa), + ] { + let (text, warnings) = uncompressed(&d, &o); + assert_eq!(text.matches("/ShadingType 2").count(), 4, "{case}"); + for other in ["/ShadingType 1", "/ShadingType 3", "/Subtype /Image"] { + assert!(!text.contains(other), "{case}: {other}"); + } + assert!(warnings.iter().any(|w| w.contains("diamond gradients are exported as four linear gradients")), "{case}: {warnings:?}"); + let back = import(&export(&d, &o).unwrap()).unwrap(); + assert_similar(&render_artboard(&back), &render_artboard(&d), 4.0, 0.01); + } +} + +/// A Perceptual diamond of one spot ink running out to paper white is not drawn as pixels: its +/// four quadrants are axial shadings in that ink's Separation space, as a Perceptual linear +/// gradient of spot inks is. +#[test] +fn a_perceptual_diamond_of_a_spot_ink_is_four_separation_shadings() { + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + let mut stops = vec![]; + for (offset, tint) in [(0.0, 1.0), (0.5, 0.4)] { + let mut s = GradientStop::new(offset, gold.tinted(tint)); + (s.swatch, s.tint) = (Some("Gold".into()), tint); + stops.push(s); + } + stops.push(GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))); + let g = Gradient { method: vectorcraft_color::GradientMethod::Perceptual, ..Gradient::new(GradientKind::Diamond, stops) }; + let mut d = doc(g, placed()); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + d.swatches.push(vectorcraft_color::Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true }); + let (text, warnings) = uncompressed(&d, &PdfOptions::uncompressed()); + assert_eq!(text.matches("/ShadingType 2").count(), 4, "{text}"); + assert!(text.contains("[/Separation/Gold"), "{text}"); + assert!(!text.contains("/Subtype /Image"), "{text}"); + assert!(warnings.iter().any(|w| w.contains("diamond gradients are exported as four linear gradients")), "{warnings:?}"); +} + +/// A dithered fill, a Perceptual gradient of process colors, one with translucent stops (whose +/// quadrants would add up their opacity where they overlap) and a diamond without an extent are +/// images of what the canvas draws, with a warning. +#[test] +fn a_diamond_drawn_as_pixels_or_without_an_extent_is_an_image() { + let c = Point::new(100.0, 100.0); + let dithered = Gradient { dither: true, ..rgb_diamond() }; + let perceptual = Gradient { method: vectorcraft_color::GradientMethod::Perceptual, ..rgb_diamond() }; + let mut translucent = rgb_diamond(); + translucent.stops[1].opacity = 0.4; + for (case, d) in [ + ("dithered", doc(dithered, placed())), + ("perceptual", doc(perceptual, placed())), + ("translucent", doc(translucent, placed())), + ("no vector", doc(rgb_diamond(), GradientGeom { start: c, end: c, aspect: 1.0, focal: None })), + ("flat", doc(rgb_diamond(), GradientGeom { aspect: 0.0, ..placed() })), + ] { + let (text, warnings) = uncompressed(&d, &PdfOptions::uncompressed()); + assert!(text.contains("/Image") && !text.contains("/ShadingType"), "{case}"); + assert!(warnings.iter().any(|w| w.contains("diamond gradients drawn as pixels")), "{case}: {warnings:?}"); + let back = import(&export(&d, &PdfOptions::uncompressed()).unwrap()).unwrap(); + let (want, got) = (render_artboard(&d), render_artboard(&back)); + for (x, y) in [(150, 120), (100, 160), (40, 100), (100, 40), (90, 110), (30, 30), (170, 170)] { + let (a, b) = (want.over_white(x, y), got.over_white(x, y)); + assert!(a.iter().zip(b).all(|(p, q)| p.abs_diff(q) <= 12), "{case} at ({x}, {y}): {a:?} vs {b:?}"); + } + } +} diff --git a/crates/pdf/src/tests/file_info.rs b/crates/pdf/src/tests/file_info.rs index 7ce2f42f47..4c837ba67f 100644 --- a/crates/pdf/src/tests/file_info.rs +++ b/crates/pdf/src/tests/file_info.rs @@ -45,7 +45,7 @@ fn description(attrs: &str, body: &str) -> String { } const INFO: &str = "/Author (Grace Hopper) /Subject /Keywords (navy; compilers, , cobol) \ - /CreationDate (D:20261005140300+02'00') /ModDate (D:20261006090000Z) /Title (Ignored title)"; + /CreationDate (D:20261005140300+02'00') /ModDate (D:20261006090000Z) /Title (Compiler manual)"; /// Unix seconds of 2026-10-05 12:03:00 UTC (14:03 at +02:00). const CREATED: i64 = 1_791_201_780; @@ -58,6 +58,7 @@ fn the_information_dictionary_gives_file_info() { assert_eq!( f, FileInfo { + title: Some("Compiler manual".into()), author: Some("Grace Hopper".into()), description: Some("Cata log".into()), keywords: Some(vec!["navy".into(), "compilers".into(), "cobol".into()]), @@ -79,7 +80,8 @@ fn the_information_dictionary_gives_file_info() { fn the_xmp_packet_gives_file_info() { let body = description( "xmpRights:Marked=\"False\" xmp:ModifyDate=\"2026-10-06T09:00:00.25Z\"", - "Ada LovelaceCharles Babbage\ + "PlakatPoster\ + Ada LovelaceCharles Babbage\ Ein PlakatA poster\nfor the fair\ fair print \ (c) 2026 Ada\ @@ -90,6 +92,7 @@ fn the_xmp_packet_gives_file_info() { assert_eq!( f, FileInfo { + title: Some("Poster".into()), author: Some("Ada Lovelace, Charles Babbage".into()), description: Some("A poster\nfor the fair".into()), keywords: Some(vec!["fair".into(), "print".into()]), @@ -138,6 +141,13 @@ fn the_xmp_packet_wins_where_both_give_a_field() { assert_eq!(f.created, Some(1_791_331_200 + 5 * 3600 + 30 * 60)); assert_eq!(f.description.as_deref(), Some("Cata log")); assert_eq!(f.modified, Some(MODIFIED)); + // The title is the packet's where it gives one (a blank `x-default` item leaves the next one), + // else the dictionary's. + assert_eq!(f.title.as_deref(), Some("Compiler manual")); + let body = + description("", " Manuel"); + let f = file_info(&pdf(Some(INFO), Some(&packet(&body))), None).unwrap(); + assert_eq!(f.title.as_deref(), Some("Manuel")); } #[test] @@ -197,17 +207,29 @@ fn an_xmp_packet_nested_too_deep_leaves_the_information_dictionary() { #[test] fn a_written_pdf_gives_its_file_info_back() { let mut d = Document::new(100.0, 100.0); + d.title = "Fair poster".into(); d.metadata.author = "Ada Lovelace".into(); d.metadata.description = "A poster\nfor the fair".into(); d.metadata.keywords = vec!["fair".into(), "print".into()]; let bytes = export(&d, &PdfOptions { created: Some(CREATED), ..PdfOptions::uncompressed() }).unwrap(); let f = file_info(&bytes, None).unwrap(); + assert_eq!(f.title.as_deref(), Some("Fair poster")); assert_eq!(f.author.as_deref(), Some("Ada Lovelace")); assert_eq!(f.description.as_deref(), Some("A poster\nfor the fair")); assert_eq!(f.keywords, Some(vec!["fair".to_string(), "print".into()])); assert_eq!((f.created, f.modified), (Some(CREATED), Some(CREATED))); } +#[test] +fn a_written_pdf_carries_the_file_info_title_not_the_documents_name() { + let mut d = Document::new(100.0, 100.0); + d.title = "poster.svg".into(); + d.metadata.title = Some("Fair poster".into()); + let bytes = export(&d, &PdfOptions { created: Some(CREATED), ..PdfOptions::uncompressed() }).unwrap(); + assert_eq!(file_info(&bytes, None).unwrap().title.as_deref(), Some("Fair poster")); + assert!(!String::from_utf8_lossy(&bytes).contains("poster.svg")); +} + #[test] fn a_written_pdf_gives_its_copyright_back() { use vectorcraft_doc::CopyrightStatus; diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index e60f3e98c5..abb15552da 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -474,6 +474,22 @@ fn a_composite_font_is_noted_by_its_cid_font_name() { assert_eq!(noted("<< /Type /Font /Subtype /Type1 /BaseFont /Vctest-Identity-H >>"), ["Vctest-Identity-H"]); } +/// A form drawn again and again without resources of its own reads the page's font dictionary once, +/// not at every drawing; the fonts are noted all the same. +#[test] +fn a_form_drawn_many_times_reads_its_font_resources_once() { + let form_no = first_extra(1); + let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 100 100]", "0 0 1 rg 50 50 30 30 re f"); + let resources = format!("/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> /XObject << /X0 {form_no} 0 R >>"); + let page = PdfPage { resources, ..PdfPage::new(100.0, 100.0, &format!("BT /F1 24 Tf 10 30 Td (Hi) Tj ET {}", "/X0 Do ".repeat(500))) }; + let pdf = craft_pdf::syntax::Pdf::new(pdf_with(&[page], &[&form], None)).unwrap(); + let mut fonts = crate::import_scan::FontNames::new(); + let mut ocgs = crate::import_scan::Ocgs::read(&pdf); + let walk = crate::import_scan::walk_page(&pdf.pages()[0], &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()); + assert_eq!(walk.font_dicts.len(), 1); + assert_eq!(walk.fonts.len(), 1); +} + /// A value of the page's font dictionary that the reader can't parse (a name with a broken `#` /// escape, a number with a stray `-`) is left out when the page's fonts are noted, and the fonts /// after it are noted. @@ -685,6 +701,115 @@ fn a_function_based_shading_along_one_axis_becomes_a_linear_gradient() { } } +/// A function-based shading whose calculator function turns the angle about the origin into a gray +/// ramp (`atan` gives the angle of `y` over `x` in degrees, 0 to 360, ISO 32000-1 7.10.5) comes in +/// as a conic gradient about the origin's place on the page, turning the way the page shows it. +#[test] +fn a_function_based_shading_around_the_origin_becomes_a_conic_gradient() { + use vectorcraft_geom::Point; + let _held = shadings(); + // The origin at the square's center, a unit 50 pt. + let r = function_shading("-1 1 -1 1", "50 0 0 50 50 50", "{ exch atan 360 div dup dup }"); + assert!(!r.warnings.iter().any(|w| w.contains("flat")), "{:?}", r.warnings); + let g = all(&r.document) + .into_iter() + .find_map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(Paint::Gradient(g)) => Some(g.clone()), + _ => None, + }) + .expect("a gradient fill"); + assert_eq!(g.gradient.kind, GradientKind::Conic); + let geom = g.geom.unwrap(); + assert!(geom.start.distance(Point::new(50.0, 50.0)) < 0.01, "{geom:?}"); + // The page's y runs up, the document's down: the sweep turns counterclockwise on the page, + // through the top of the square a quarter turn on. + assert!(geom.is_mirrored(), "{geom:?}"); + for (x, y, want) in [(90.0, 48.0, 0.0), (50.0, 10.0, 0.25), (10.0, 50.0, 0.5), (50.0, 90.0, 0.75), (90.0, 52.0, 1.0)] { + let gray = g.gradient.sample(geom.param_at(GradientKind::Conic, Point::new(x, y)) as f32).0.to_rgb()[0]; + assert!((gray - want).abs() < 0.03, "({x}, {y}): {gray} vs {want}"); + } +} + +/// The same shading over a domain that leaves the origin out (the conic's center lies off the +/// painted area) comes in as a conic gradient too, with the colors the domain shows, whether or not +/// the seam (angle 0) runs through it. +#[test] +fn a_function_based_shading_beside_the_origin_becomes_a_conic_gradient() { + use vectorcraft_geom::Point; + let _held = shadings(); + // The shading's x and y from a point of the 100 pt page (its y up, the document's down). + let turn = |x: f64, y: f64| { + let (sx, sy) = ((x - 50.0) / 50.0, (50.0 - y) / 50.0); + sy.atan2(sx).to_degrees().rem_euclid(360.0) / 360.0 + }; + for (domain, points) in [ + // Right of the origin, across the seam. + ("0.2 1 -0.6 0.6", [(70.0, 30.0), (70.0, 70.0), (90.0, 45.0), (90.0, 55.0), (65.0, 25.0)]), + // Above it. + ("-1 1 0.2 1", [(50.0, 20.0), (20.0, 30.0), (80.0, 30.0), (5.0, 35.0), (95.0, 5.0)]), + // The origin on its left edge: the rays it shows run from straight down to straight up. + ("0 1 -1 1", [(52.0, 5.0), (52.0, 95.0), (90.0, 40.0), (90.0, 60.0), (75.0, 20.0)]), + ] { + let r = function_shading(domain, "50 0 0 50 50 50", "{ exch atan 360 div dup dup }"); + let g = all(&r.document) + .into_iter() + .find_map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(Paint::Gradient(g)) => Some(g.clone()), + _ => None, + }) + .unwrap_or_else(|| panic!("{domain}: a gradient fill, {:?}", r.warnings)); + assert_eq!(g.gradient.kind, GradientKind::Conic, "{domain}"); + let geom = g.geom.unwrap(); + assert!(geom.start.distance(Point::new(50.0, 50.0)) < 0.01, "{domain}: {geom:?}"); + for (x, y) in points { + let gray = g.gradient.sample(geom.param_at(GradientKind::Conic, Point::new(x, y)) as f32).0.to_rgb()[0]; + let want = turn(x, y) as f32; + assert!((gray - want).abs() < 0.03, "{domain} ({x}, {y}): {gray} vs {want}"); + } + } +} + +/// A function-based shading whose calculator function turns `abs(x) + abs(y)` into a gray ramp +/// (ISO 32000-1 7.10.5; the ramp clipped to 1 past the square with corners at the domain's edges) +/// comes in as a diamond gradient about the origin's place on the page. A ramp along a circle +/// about the origin does not. +#[test] +fn a_function_based_shading_of_squares_about_the_origin_becomes_a_diamond_gradient() { + use vectorcraft_geom::Point; + let _held = shadings(); + let fill = |r: &ImportReport| { + all(&r.document).into_iter().find_map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(Paint::Gradient(g)) => Some(g.clone()), + _ => None, + }) + }; + // The origin at the square's center, a unit 50 pt. + let r = function_shading("-1 1 -1 1", "50 0 0 50 50 50", "{ abs exch abs add dup dup }"); + let g = fill(&r).unwrap_or_else(|| panic!("a gradient fill, {:?}", r.warnings)); + assert_eq!(g.gradient.kind, GradientKind::Diamond); + let geom = g.geom.unwrap(); + assert!(geom.start.distance(Point::new(50.0, 50.0)) < 0.01, "{geom:?}"); + for (x, y) in [(50.0, 50.0), (75.0, 50.0), (50.0, 20.0), (70.0, 70.0), (35.0, 60.0), (95.0, 95.0), (10.0, 80.0)] { + let gray = g.gradient.sample(geom.param_at(GradientKind::Diamond, Point::new(x, y)) as f32).0.to_rgb()[0]; + let want = (((x - 50.0) as f32).abs() / 50.0 + ((y - 50.0) as f32).abs() / 50.0).min(1.0); + assert!((gray - want).abs() < 0.03, "({x}, {y}): {gray} vs {want}"); + } + // A radial ramp (the distance from the origin) is not one. + let r = function_shading("-1 1 -1 1", "50 0 0 50 50 50", "{ dup mul exch dup mul add sqrt dup dup }"); + assert!(fill(&r).is_none_or(|g| g.gradient.kind != GradientKind::Diamond)); + // A domain wider than it is tall: the ramp keeps changing out to its far corners, past the + // largest square the domain holds whole. + let r = function_shading("-2 2 -1 1", "50 0 0 50 50 50", "{ abs exch abs add 3 div dup dup }"); + let g = fill(&r).unwrap_or_else(|| panic!("a gradient fill, {:?}", r.warnings)); + assert_eq!(g.gradient.kind, GradientKind::Diamond); + let geom = g.geom.unwrap(); + for (x, y) in [(50.0, 50.0), (125.0, 90.0), (-20.0, 10.0), (140.0, 50.0), (60.0, 95.0), (0.0, 30.0)] { + let gray = g.gradient.sample(geom.param_at(GradientKind::Diamond, Point::new(x, y)) as f32).0.to_rgb()[0]; + let want = (((x - 50.0) as f32).abs() / 50.0 + ((y - 50.0) as f32).abs() / 50.0) / 3.0; + assert!((gray - want).abs() < 0.03, "({x}, {y}): {gray} vs {want}"); + } +} + /// A function-based shading paints only over its domain: a square filled with one whose domain /// covers its left half is clipped to that half; one whose domain covers it all isn't clipped. #[test] diff --git a/crates/pdf/src/tests/marks.rs b/crates/pdf/src/tests/marks.rs index 19031505d3..603138bd49 100644 --- a/crates/pdf/src/tests/marks.rs +++ b/crates/pdf/src/tests/marks.rs @@ -256,14 +256,48 @@ fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() { } } } - // PDF/X-4 and PDF/A-2b files at PDF 1.4 have no `UserUnit` either. + // PDF/X-4 files at PDF 1.4 have no `UserUnit` either; PDF/A-2b files at PDF 1.4 are written as + // PDF 1.6 to have one. let at_14 = |standard| report(&d, PdfSettings { standard, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }); refused(at_14(Standard::PdfX4).err().unwrap(), "PDF 1.4"); - refused(at_14(Standard::PdfA2b).err().unwrap(), "PDF 1.4"); + let r = at_14(Standard::PdfA2b).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.6")); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938]); +} + +/// PDF/A-2 limits page boundaries to 14,400 units (ISO 19005-2, 6.1.13), and PDF 1.4 has no +/// `UserUnit`: a PDF/A-2b file at PDF 1.4 with a page longer than 14,400 pt is written as PDF 1.6, +/// with a `UserUnit` that keeps the page within 14,400 units and a warning, with +/// `long_pages_in_points` on or off. Pages past 32,767 pt that aren't whole numbers of points are +/// written too. A file whose pages are all 14,400 pt or shorter stays PDF 1.4. +#[test] +fn pdfa2b_at_pdf_1_4_writes_a_long_page_as_pdf_1_6_within_14400_units() { + for in_points in [false, true] { + let set = PdfSettings { + standard: Standard::PdfA2b, + compatibility: Compatibility::Pdf14, + long_pages_in_points: in_points, + ..PdfSettings::default() + }; + for side in [17_000.0, 32_767.0, 32_767.5, 40_000.0, TWENTY_M] { + let r = report(&sized(side, 300.0), set.clone()).unwrap_or_else(|e| panic!("{side} {in_points}: {e}")); + assert!(r.bytes.starts_with(b"%PDF-1.6"), "{side} {in_points}"); + let unit = raw_numbers(&r.bytes, "/UserUnit", 1); + assert_eq!(unit.len(), 1, "{side} {in_points}"); + let media = raw_numbers(&r.bytes, "/MediaBox", 4); + assert!(media[2] - media[0] <= 14_400.0 && media[3] - media[1] <= 14_400.0, "{side} {in_points}: {media:?}"); + assert!(((media[2] - media[0]) * unit[0] - side).abs() < side * 0.001, "{side} {in_points}: {media:?} {unit:?}"); + let raised = "PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6"; + assert!(r.warnings.iter().any(|w| w == raised), "{side} {in_points}: {:?}", r.warnings); + } + let r = report(&sized(14_400.0, 300.0), set.clone()).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.4"), "{in_points}"); + assert!(!r.warnings.iter().any(|w| w.contains("has no UserUnit")), "{in_points}: {:?}", r.warnings); + } } /// A page from 14,400 to 32,767 pt long is written in points, with the warning, in PDF 1.3 and 1.4 -/// files, PDF/X-1a, PDF/X-3, PDF/X-4 and PDF/A-2b files among them, as before the warning. Past +/// files, PDF/X-1a, PDF/X-3 and PDF/X-4 files among them, as before the warning. Past /// 32,767 pt a page of whole points is written too, as the writer puts whole numbers as integers; /// a side that isn't a whole number, or art that needs a real number past 32,767, gets the error. #[test] @@ -276,7 +310,6 @@ fn pdf_1_4_writes_a_page_up_to_32767_pt_in_points() { ("PDF/X-1a:2001", preset("PDF/X-1a:2001")), ("PDF/X-3:2002", preset("PDF/X-3:2002")), ("PDF/X-4:2010", PdfSettings { standard: Standard::PdfX4, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), - ("PDF/A-2b", PdfSettings { standard: Standard::PdfA2b, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), ]; for (label, set) in &sets { for side in [17_000.0, 32_767.0, 40_000.0] { @@ -287,8 +320,8 @@ fn pdf_1_4_writes_a_page_up_to_32767_pt_in_points() { let points = format!("{label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"); assert!(w.len() == 1 && w[0].ends_with(&points), "{label}: {w:?}"); } - // For PDF/X-4 and PDF/A-2b files the error names the PDF version. - let label = if matches!(*label, "PDF/X-4:2010" | "PDF/A-2b") { "PDF 1.4" } else { label }; + // For PDF/X-4 files the error names the PDF version. + let label = if *label == "PDF/X-4:2010" { "PDF 1.4" } else { label }; let refused = |e: PdfError, side: &str| { let refusal = format!("{label} files hold real numbers up to 32,767, and the page of artboard 1, {side} pt long, needs larger ones"); assert!(e.to_string().contains(&refusal), "{e}"); @@ -418,6 +451,102 @@ fn a_page_within_14400_pt_is_written_as_before_at_every_version() { assert!(r.bytes.starts_with(b"%PDF-1.5") && has(b"/CFM/V2") && !has(b"AESV2")); } +/// 10 m in points. +const TEN_M: f64 = 10.0 / 0.0254 * 72.0; + +/// With `long_pages_in_points`, a 10 m page at PDF 1.7 is written at its size in points, with no +/// `UserUnit`, the warning says so, and the page reads back at 10 m. Without it the page keeps +/// its `UserUnit`. +#[test] +fn long_pages_in_points_writes_a_10_m_page_in_points() { + let d = sized(TEN_M, TEN_M / 10.0); + let r = report(&d, PdfSettings { long_pages_in_points: true, ..PdfSettings::default() }).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.7")); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new()); + let media = raw_numbers(&r.bytes, "/MediaBox", 4); + assert!((media[2] - media[0] - 28_346.46).abs() < 0.01 && (media[3] - media[1] - 2_834.65).abs() < 0.01, "{media:?}"); + assert_eq!( + long_page_warnings(&r), + [ + "the page of artboard 1 is 28347 × 2835 pt (10.00 × 1.00 m), longer than PDF's page limit of 14,400 pt (200 in): PDF 1.7 pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in" + ], + "{:?}", + r.warnings + ); + let page = &info(&r.bytes, None).unwrap().pages[0]; + assert!((page.width - TEN_M).abs() < 0.01 && (page.height - TEN_M / 10.0).abs() < 0.01, "{page:?}"); + let back = import(&r.bytes).unwrap(); + let rect = back.artboards[0].rect; + assert!((rect.width() - TEN_M).abs() < 0.01 && (rect.height() - TEN_M / 10.0).abs() < 0.01, "{rect:?}"); + // Off (the default), the page has a `UserUnit` of 28,346.46 / 14,400, rounded up. + let off = report(&d, PdfSettings::default()).unwrap(); + assert_eq!(raw_numbers(&off.bytes, "/UserUnit", 1), [1.969]); + assert!( + long_page_warnings(&off)[0].ends_with("it is written with a UserUnit of 1.969, so apps that ignore UserUnit show it that many times smaller") + ); + assert!(!settings(json!({})).long_pages_in_points, "off by default"); +} + +/// With `long_pages_in_points`, every PDF version writes a 10 m page in points: PDF 1.5 stays +/// PDF 1.5, and versions that write it in points anyway (PDF 1.3 and 1.4, PDF/X-4) give the same +/// file as without it. +#[test] +fn long_pages_in_points_keeps_every_version_and_changes_nothing_where_pages_are_in_points_already() { + let d = sized(TEN_M, TEN_M / 10.0); + let with = |set: &PdfSettings| PdfSettings { long_pages_in_points: true, ..set.clone() }; + for c in Compatibility::ALL.iter().copied() { + let set = PdfSettings { compatibility: c, ..PdfSettings::default() }; + let r = report(&d, with(&set)).unwrap(); + assert!(r.bytes.starts_with(format!("%PDF-{}", c.id()).as_bytes()), "{}", c.label()); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{}", c.label()); + assert!((raw_meters(&r.bytes).0 - 10.0).abs() < 0.001, "{}", c.label()); + assert!(!r.warnings.iter().any(|w| w.starts_with("PDF 1.5 has no UserUnit")), "{}: {:?}", c.label(), r.warnings); + assert_eq!(long_page_warnings(&r).len(), 1, "{}: {:?}", c.label(), r.warnings); + if matches!(c, Compatibility::Pdf13 | Compatibility::Pdf14) { + assert_eq!(r.bytes, report(&d, set).unwrap().bytes, "{}", c.label()); + } + } + let x4 = crate::builtin_presets().into_iter().find(|p| p.name == "PDF/X-4:2010").unwrap().settings; + assert_eq!(report(&d, with(&x4)).unwrap().bytes, report(&d, x4).unwrap().bytes); +} + +/// PDF/A-2 limits page boundaries to 14,400 units (ISO 19005-2, 6.1.13): with +/// `long_pages_in_points`, a PDF/A file gives the same file as without it at every version its +/// standard allows, and a 10 m page keeps its `UserUnit` from PDF 1.5 on (PDF 1.5 is written as +/// PDF 1.6 for it). +#[test] +fn pdfa2b_long_page_stays_within_14400_units() { + let d = sized(TEN_M, TEN_M / 10.0); + for s in Standard::ALL.iter().copied().filter(|s| *s != Standard::None && !s.is_pdfx()) { + for c in Compatibility::ALL.iter().copied().filter(|c| s.allows(*c)) { + let off = PdfSettings { standard: s, compatibility: c, ..PdfSettings::default() }; + let on = PdfSettings { long_pages_in_points: true, ..off.clone() }; + let (on, off) = (report(&d, on).unwrap(), report(&d, off).unwrap()); + assert_eq!(on.bytes, off.bytes, "{} {}", s.label(), c.label()); + assert_eq!(on.warnings, off.warnings, "{} {}", s.label(), c.label()); + if c != Compatibility::Pdf14 { + assert_eq!(raw_numbers(&on.bytes, "/UserUnit", 1), [1.969], "{} {}", s.label(), c.label()); + let media = raw_numbers(&on.bytes, "/MediaBox", 4); + assert!(media[2] - media[0] <= 14_400.0 && media[3] - media[1] <= 14_400.0, "{} {}: {media:?}", s.label(), c.label()); + } + } + } +} + +/// A page of 14,400 pt or less gives the same file with `long_pages_in_points` on or off, at every +/// PDF version. +#[test] +fn long_pages_in_points_leaves_a_page_within_14400_pt_as_it_is() { + let d = sized(14_400.0, 300.0); + for c in Compatibility::ALL.iter().copied() { + let off = PdfSettings { compatibility: c, ..PdfSettings::default() }; + let on = PdfSettings { long_pages_in_points: true, ..off.clone() }; + let (off, on) = (report(&d, off).unwrap(), report(&d, on).unwrap()); + assert_eq!(on.bytes, off.bytes, "{}", c.label()); + assert_eq!(on.warnings, off.warnings, "{}", c.label()); + } +} + #[test] fn art_in_the_bleed_is_kept_and_clipped_to_the_bleed_box() { let d = doc(); diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index dbc221e0dd..ec22eb0186 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -224,3 +224,23 @@ fn verify_finds_what_each_standard_forbids() { assert!(matches!(verify(&file(font), Standard::PdfX4), Err(PdfError::Unsupported(m)) if m.contains("fonts"))); assert!(verify(&file("<>"), Standard::PdfX4).is_ok()); } + +/// Names inside a string or a comment are text, not syntax: a file identifier, whose base64 hash +/// can hold `/BM` or `/Lab`, does not make a file break its standard. +#[test] +fn verify_skips_names_in_strings_and_comments() { + use crate::pdfx::verify; + let file = |body: &str| format!("%PDF-1.3\n%/BM/Multiply\n1 0 obj\n{body}\nendobj\n").into_bytes(); + for ok in [ + "<>", + "<>", + "<>", + ] { + for standard in [Standard::PdfX1a, Standard::PdfX3] { + assert!(verify(&file(ok), standard).is_ok(), "{standard:?}: {ok}"); + } + } + // A name after a string is still read. + let after = "<>"; + assert!(matches!(verify(&file(after), Standard::PdfX3), Err(PdfError::Unsupported(m)) if m.contains("blend modes"))); +} diff --git a/crates/plugins/src/deferred.rs b/crates/plugins/src/deferred.rs index 1645dd55e0..a29d877d44 100644 --- a/crates/plugins/src/deferred.rs +++ b/crates/plugins/src/deferred.rs @@ -19,7 +19,7 @@ //! [`revision`] changes, so that drawings made with the deferred stage are drawn again. use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -106,9 +106,108 @@ enum Phase { Open, } +/// The deferred records in the order they were made, indexed by stage and cache key. A stage holds +/// at most one record for each key. +#[derive(Default)] +struct Records { + /// The order number of the next record. + next: u64, + by_order: BTreeMap, + /// For each stage with records, the order number of its record for each key. + by_stage: HashMap>, +} + +impl Records { + /// Every record, oldest first. + fn iter(&self) -> impl Iterator { + self.by_order.values().inspect(|_| looked_at(1)) + } + + /// The stages with records, in no particular order. + fn stages(&self) -> impl Iterator + '_ { + self.by_stage.keys().copied() + } + + /// The records of `stage`, in no particular order. + fn of(&self, stage: Stage) -> impl Iterator { + self.by_stage.get(&stage).into_iter().flat_map(|keys| keys.values()).filter_map(|n| { + looked_at(1); + self.by_order.get(n) + }) + } + + /// Is `stage` recorded with cache key `key`? + fn contains(&self, stage: Stage, key: u64) -> bool { + looked_at(1); + self.by_stage.get(&stage).is_some_and(|keys| keys.contains_key(&key)) + } + + /// Adds `d` as the newest record, in place of the record of its stage and key. + fn push(&mut self, d: Deferred) { + let order = self.next; + self.next = self.next.wrapping_add(1); + if let Some(old) = self.by_stage.entry(d.stage).or_default().insert(d.key, order) + && let Some(old) = self.by_order.remove(&old) + { + unmark(old.key); + } + self.by_order.insert(order, d); + } + + /// Drops the records of `stage` whose key `drop` gives true for. + fn drop_where(&mut self, stage: Stage, drop: impl Fn(u64) -> bool) { + let Some(keys) = self.by_stage.get_mut(&stage) else { return }; + looked_at(keys.len()); + let by_order = &mut self.by_order; + keys.retain(|&key, order| { + let keep = !drop(key); + if !keep && let Some(d) = by_order.remove(order) { + unmark(d.key); + } + keep + }); + if keys.is_empty() { + self.by_stage.remove(&stage); + } + } + + /// Drops the records for which `keep` is false. + fn retain(&mut self, mut keep: impl FnMut(&Deferred) -> bool) { + let by_stage = &mut self.by_stage; + self.by_order.retain(|_, d| { + looked_at(1); + let k = keep(d); + if !k { + if let Some(keys) = by_stage.get_mut(&d.stage) { + keys.remove(&d.key); + if keys.is_empty() { + by_stage.remove(&d.stage); + } + } + unmark(d.key); + } + k + }); + } +} + +#[cfg(test)] +thread_local! { + /// How many records the lookups on this thread have looked at. + static LOOKED_AT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Counts `n` records looked at, in tests. +fn looked_at(n: usize) { + #[cfg(test)] + LOOKED_AT.with(|c| c.set(c.get() + n)); + #[cfg(not(test))] + let _ = n; +} + struct State { phase: Phase, - deferred: Vec, + deferred: Records, /// How many stages the first view left deferred, until [`Deferrals::take_report`] takes it. report: Option, /// The refresh running, if one is ([`Deferrals::refresh`]). @@ -123,13 +222,13 @@ struct Refresh { /// When its budget started (`None`: no run yet). started: Option, /// The objects whose stages run again; the others' stay deferred. - ids: Vec, + ids: HashSet, /// The cache keys whose cached failures have been run again. - retried: Vec, + retried: HashSet, /// The stages of `ids` that were drawn. - visited: Vec, + visited: HashSet, /// The stage inputs of `ids` that ran, or were taken from the cache, or were deferred again. - touched: Vec<(Stage, u64)>, + touched: HashSet<(Stage, u64)>, } impl State { @@ -155,7 +254,7 @@ impl State { impl Drop for State { fn drop(&mut self) { - for d in &self.deferred { + for d in self.deferred.iter() { unmark(d.key); } } @@ -197,7 +296,7 @@ impl Deferrals { pub fn with_clock(clock: Clock) -> Self { Self(Arc::new(Mutex::new(State { phase: Phase::Budgeted { started: None, first: true }, - deferred: Vec::new(), + deferred: Records::default(), report: None, refresh: None, clock, @@ -211,7 +310,7 @@ impl Deferrals { /// The deferred stages, by object and effect, each once (a stage drawn with several inputs, /// such as the paths of a group, is listed with the first one's reason). pub fn list(&self) -> Vec { - let mut out = self.state().deferred.clone(); + let mut out: Vec = self.state().deferred.iter().cloned().collect(); out.sort_by_key(|d| (d.stage.object, d.stage.item, d.stage.effect)); out.dedup_by_key(|d| d.stage); out @@ -238,13 +337,10 @@ impl Deferrals { if pass.ran.is_empty() { return; } - self.state().deferred.retain(|d| { - let keep = !pass.ran.contains(&d.stage) || pass.seen.contains(&(d.stage, d.key)); - if !keep { - unmark(d.key); - } - keep - }); + let mut s = self.state(); + for &stage in &pass.ran { + s.deferred.drop_where(stage, |key| !pass.seen.contains(&(stage, key))); + } } /// The first view has been drawn: later drawings leave deferred stages deferred, and @@ -271,14 +367,14 @@ impl Deferrals { pub fn refresh(&self, objects: Option<&[u64]>, run: impl FnOnce(&[u64]) -> Vec) -> Refreshed { let (targets, ids) = { let mut s = self.state(); - let mut targets: Vec = s.deferred.iter().map(|d| d.stage).filter(|t| objects.is_none_or(|o| o.contains(&t.object))).collect(); + let asked: Option> = objects.map(|o| o.iter().copied().collect()); + let mut targets: Vec = s.deferred.stages().filter(|t| asked.as_ref().is_none_or(|o| o.contains(&t.object))).collect(); targets.sort_by_key(|t| (t.object, t.item, t.effect)); - targets.dedup(); let mut ids: Vec = targets.iter().map(|t| t.object).collect(); ids.dedup(); let thread = std::thread::current().id(); - let (retried, visited, touched) = (Vec::new(), Vec::new(), Vec::new()); - s.refresh = Some(Refresh { thread, started: None, ids: ids.clone(), retried, visited, touched }); + let (retried, visited, touched) = (HashSet::new(), HashSet::new(), HashSet::new()); + s.refresh = Some(Refresh { thread, started: None, ids: ids.iter().copied().collect(), retried, visited, touched }); (targets, ids) }; // The refresh ends when `run` returns, also when it unwinds. @@ -289,20 +385,16 @@ impl Deferrals { } } let reopen = Reopen(self); - let whole = run(&ids); + let whole: HashSet = run(&ids).into_iter().collect(); let mut s = self.state(); let touched = match s.refresh.take() { Some(r) => { - s.deferred.retain(|d| { - let gone = r.visited.contains(&d.stage) && whole.contains(&d.stage.object) && !r.touched.contains(&(d.stage, d.key)); - if gone { - unmark(d.key); - } - !gone - }); + for &stage in r.visited.iter().filter(|t| whole.contains(&t.object)) { + s.deferred.drop_where(stage, |key| !r.touched.contains(&(stage, key))); + } r.touched } - None => Vec::new(), + None => HashSet::new(), }; drop(s); drop(reopen); @@ -310,11 +402,11 @@ impl Deferrals { // than time; one with records left that this refresh did not run is still deferred. let s = self.state(); let mut out = Refreshed::default(); - for t in &targets { - let mut left = s.deferred.iter().filter(|d| d.stage == *t).peekable(); + for &t in &targets { + let mut left = s.deferred.of(t).peekable(); if left.peek().is_none() { out.refreshed += 1; - } else if left.any(|d| d.reason != Reason::Budget && touched.contains(&(d.stage, d.key))) { + } else if left.any(|d| d.reason != Reason::Budget && touched.contains(&(t, d.key))) { out.failed += 1; } else { out.still_deferred += 1; @@ -355,7 +447,7 @@ impl Deferrals { pub(crate) fn holds(&self, stage: Stage, key: u64) -> bool { let mut s = self.state(); let settled = s.phase_here() == Phase::Open || s.refreshes(stage.object) == Some(false); - let held = settled && s.deferred.iter().any(|d| d.stage == stage && d.key == key); + let held = settled && s.deferred.contains(stage, key); drop(s); if held { seen(stage, key); @@ -367,30 +459,22 @@ impl Deferrals { /// reached the stage. pub(crate) fn visit(&self, stage: Stage) { let mut s = self.state(); - if let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object) && !r.visited.contains(&stage)) { - r.visited.push(stage); + if let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object)) { + r.visited.insert(stage); } } /// Drops the records of the stages for which `keep` (given the stage and the plug-in id) is /// false, such as those of effects or objects removed from the document. pub fn retain(&self, keep: impl Fn(Stage, &str) -> bool) { - self.state().deferred.retain(|d| { - let k = keep(d.stage, &d.plugin); - if !k { - unmark(d.key); - } - k - }); + self.state().deferred.retain(|d| keep(d.stage, &d.plugin)); } /// Should the failure cached for `stage` with cache key `key` be run again? Yes once per key /// while a refresh running here runs the stages of `stage`'s object. pub(crate) fn retries(&self, stage: Stage, key: u64) -> bool { let mut s = self.state(); - let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object) && !r.retried.contains(&key)) else { return false }; - r.retried.push(key); - true + s.refresh_here().filter(|r| r.ids.contains(&stage.object)).is_some_and(|r| r.retried.insert(key)) } /// What a run starting now may take of the budget: the budget starts with the first run. @@ -425,13 +509,7 @@ impl State { /// plug-in was not looked at) stands for any input, so it goes whatever `key` is, and `key` 0 /// removes every record of the stage. fn remove(&mut self, stage: Stage, key: u64) { - self.deferred.retain(|d| { - let keep = d.stage != stage || (d.key != key && d.key != 0 && key != 0); - if !keep { - unmark(d.key); - } - keep - }); + self.deferred.drop_where(stage, |k| k == key || k == 0 || key == 0); } /// `stage` was run with cache key `key`, or taken from the cache, by the drawing on this @@ -439,12 +517,12 @@ impl State { /// view [`Deferrals::settle`] looks at the stage when that drawing ends. fn ran_here(&mut self, stage: Stage, key: u64) { if let Some(r) = self.refresh_here().filter(|r| r.ids.contains(&stage.object)) { - r.touched.push((stage, key)); + r.touched.insert((stage, key)); } if self.phase_here() == Phase::Open { let _ = PASSES.try_with(|p| { - if let Some(pass) = p.borrow_mut().last_mut().filter(|pass| !pass.ran.contains(&stage)) { - pass.ran.push(stage); + if let Some(pass) = p.borrow_mut().last_mut() { + pass.ran.insert(stage); } }); } @@ -452,9 +530,8 @@ impl State { /// The deferred stages, each once. fn stages(&self) -> Vec { - let mut out: Vec = self.deferred.iter().map(|d| d.stage).collect(); + let mut out: Vec = self.deferred.stages().collect(); out.sort_by_key(|t| (t.object, t.item, t.effect)); - out.dedup(); out } } @@ -469,15 +546,15 @@ thread_local! { /// deferred again), and the stage inputs it left deferred. #[derive(Default)] struct Pass { - ran: Vec, - seen: Vec<(Stage, u64)>, + ran: HashSet, + seen: HashSet<(Stage, u64)>, } /// The drawing on this thread left `stage` deferred with cache key `key`. fn seen(stage: Stage, key: u64) { let _ = PASSES.try_with(|p| { if let Some(pass) = p.borrow_mut().last_mut() { - pass.seen.push((stage, key)); + pass.seen.insert((stage, key)); } }); } @@ -676,6 +753,79 @@ mod tests { assert_eq!(d.list().iter().map(|x| x.stage).collect::>(), [st(2, 0), st(3, 0)]); } + /// Objects asked for or drawn whole more than once count once; a stage with several inputs + /// gives a result when its object is drawn whole, fails when an input it ran with fails again + /// (even beside an older failure it did not run), and stays deferred when it is reached but + /// not drawn whole or not reached at all. + #[test] + fn a_refresh_with_repeated_objects_and_several_inputs_per_stage() { + const K: u64 = 0xdef1_0000; + let marked = |key| MARKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&key)); + let d = Deferrals::with_clock(stepping(1)); + d.first_view_done(); + let st = |object| Stage { object, effect: 0, item: None }; + for (object, reason, key) in [ + (10, Reason::Budget, K + 1), + (10, Reason::Budget, K + 2), + (11, Reason::Timeout, K + 3), + (11, Reason::Budget, K + 4), + (12, Reason::Timeout, K + 5), + (13, Reason::Budget, K + 6), + (14, Reason::Budget, K + 7), + ] { + d.defer(st(object), "a", reason, key); + } + let before = revision(); + let seen = std::cell::RefCell::new(vec![]); + let counts = d.refresh(Some(&[10, 11, 12, 13, 10, 11, 99]), |ids| { + seen.borrow_mut().extend_from_slice(ids); + d.visit(st(10)); + d.visit(st(10)); + d.ran(st(10), K + 1); + d.visit(st(11)); + d.defer(st(11), "a", Reason::Failed, K + 8); + d.visit(st(12)); + vec![10, 13, 10, 13] + }); + assert_eq!(*seen.borrow(), [10, 11, 12, 13]); + assert_eq!(counts, Refreshed { refreshed: 1, still_deferred: 2, failed: 1 }); + assert!(revision() > before); + let keys = || d.state().deferred.iter().map(|x| (x.stage.object, x.key)).collect::>(); + assert_eq!(keys(), [(11, K + 3), (11, K + 4), (12, K + 5), (13, K + 6), (14, K + 7), (11, K + 8)]); + assert!(!marked(K + 1) && !marked(K + 2), "the records of the stage that gave a result"); + assert!(marked(K + 3) && marked(K + 8)); + + // Again, with nothing reached: every stage asked for stays as it was. + let counts = d.refresh(Some(&[11, 12, 12]), |_| vec![11, 12]); + assert_eq!(counts, Refreshed { refreshed: 0, still_deferred: 2, failed: 0 }); + assert_eq!(keys(), [(11, K + 3), (11, K + 4), (12, K + 5), (13, K + 6), (14, K + 7), (11, K + 8)]); + } + + /// A refresh whose drawing unwinds ends: later drawings on this thread are no longer part of + /// it, and the next refresh has a budget of its own. + #[test] + fn a_refresh_that_unwinds_ends() { + let d = Deferrals::with_clock(stepping(1)); + d.first_view_done(); + let s = Stage { object: 5, effect: 0, item: None }; + d.defer(s, "a", Reason::Budget, 0xdef2_0001); + let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + d.refresh(None, |_| { + assert!(!d.holds(s, 0xdef2_0001)); + panic!("the drawing stopped") + }) + })); + assert!(unwound.is_err()); + assert!(matches!(d.allowance(), Allowance::Unlimited)); + assert!(d.holds(s, 0xdef2_0001), "the stage stays deferred"); + let counts = d.refresh(Some(&[5]), |_| { + assert!(matches!(d.allowance(), Allowance::Until { .. })); + d.visit(s); + vec![5] + }); + assert_eq!(counts, Refreshed { refreshed: 1, still_deferred: 0, failed: 0 }); + } + /// After the first view, a stage drawn with several inputs (the paths of a group) whose one /// changed input runs keeps the records of the inputs the same drawing left deferred, and drops /// the record of the input it no longer has. @@ -724,4 +874,62 @@ mod tests { drop((d, other)); assert!(!marked(), "the document closed"); } + + /// Deferrals after the first view with `n` stages, one input each, keyed from `base`. + fn many(n: u64, base: u64) -> Deferrals { + let d = Deferrals::with_clock(stepping(1)); + for object in 0..n { + d.defer(Stage { object, effect: 0, item: None }, "a", Reason::Budget, base + object); + } + d.first_view_done(); + d + } + + /// How many records `f` looks at on this thread. + fn looked_at_by(f: impl FnOnce()) -> usize { + let before = LOOKED_AT.with(std::cell::Cell::get); + f(); + LOOKED_AT.with(std::cell::Cell::get) - before + } + + /// Asking whether a stage input stays deferred looks at that stage's records only, however + /// many other stages are deferred. + #[test] + fn holding_a_stage_looks_at_its_own_records_only() { + const K: u64 = 0xdef3_0000; + let d = many(2_000, K); + let s = Stage { object: 1_000, effect: 0, item: None }; + let n = looked_at_by(|| { + assert!(d.holds(s, K + 1_000)); + assert!(!d.holds(s, K + 1_001), "another stage's input"); + assert!(!d.holds(Stage { effect: 1, ..s }, K + 1_000), "another stage"); + }); + assert!(n <= 3, "looked at {n} records"); + } + + /// A stage that gives a result, or is deferred again, replaces its own records only, and so + /// does the end of a drawing after the first view: the other stages' records are not looked at. + #[test] + fn replacing_a_stage_record_looks_at_its_own_records_only() { + const K: u64 = 0xdef4_0000; + let d = many(2_000, K); + let st = |object| Stage { object, effect: 0, item: None }; + let n = looked_at_by(|| { + d.ran(st(1_000), K + 1_000); + d.defer(st(1_001), "a", Reason::Failed, K + 9_999); + d.defer(st(1_002), "a", Reason::Missing, 0); + d.ran(st(1_002), 7); + }); + assert!(n <= 6, "looked at {n} records"); + let n = looked_at_by(|| { + d.view(|| { + assert!(!d.holds(st(1_003), K + 9_998)); + d.ran(st(1_003), K + 9_998); + }); + }); + assert!(n <= 4, "looked at {n} records"); + let keys = d.state().deferred.iter().filter(|x| (1_000..1_004).contains(&x.stage.object)).map(|x| x.key).collect::>(); + assert_eq!(keys, [K + 1_001, K + 9_999]); + assert_eq!(d.list().len(), 1_997); + } } diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index f06d17e242..6d549ed070 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -552,7 +552,7 @@ mod tests { // Traps on a long input. let first = "(if (i32.gt_u (local.get $il) (i32.const 4096)) (then unreachable))"; let src = crate::wat::with_imports(&manifest, "", first, r#"{"objects":[]}"#); - registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); let doc = Document::new(100.0, 100.0); let line = |n: usize| PathData::single(SubPath::polyline(&(0..n).map(|i| Point::new(i as f64, 0.0)).collect::>(), false)); let draw = @@ -583,7 +583,7 @@ mod tests { // Traps on a long input. let first = "(if (i32.gt_u (local.get $il) (i32.const 4096)) (then unreachable))"; let src = crate::wat::with_imports(&manifest, "", first, &output); - registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); let doc = Document::new(100.0, 100.0); let line = |n: usize| PathData::single(SubPath::polyline(&(0..n).map(|i| Point::new(i as f64, 0.0)).collect::>(), false)); let draw = @@ -647,7 +647,7 @@ mod tests { crate::safe_mode::set_active(None); const ID: &str = "test.effect.budget"; let src = crate::wat::returning(&crate::wat::manifest(ID, "effect", "{}"), r#"{"objects":[]}"#); - registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); // Each run takes 900 ms by this clock (it is read before and after each run). let view = crate::deferred::Deferrals::with_clock(stepping(450)); let ran = view.view(|| (0..4).map(|i| drawn(ID, &line(i + 2), i)).collect::>()); @@ -677,7 +677,7 @@ mod tests { const ID: &str = "test.effect.deferfailed"; // Runs to its instruction budget. let src = crate::wat::spinning(&crate::wat::manifest(ID, "effect", "{}"), 1_000_000_000, r#"{"objects":[]}"#); - registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); let view = crate::deferred::Deferrals::with_clock(stepping(1)); assert!(!view.view(|| drawn(ID, &line(2), 0))); assert!(last_error(ID).is_some()); @@ -712,9 +712,9 @@ mod tests { const FAST: &str = "test.effect.cutshort.fast"; let src = crate::wat::spinning(&crate::wat::manifest(ID, "effect", "{}"), 10_000_000, r#"{"objects":[]}"#); let limits = Limits { fuel_base: 1_000_000_000, ..Limits::default() }; - registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), limits).unwrap()); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), limits).unwrap()).unwrap(); let fast = crate::wat::returning(&crate::wat::manifest(FAST, "effect", "{}"), r#"{"objects":[]}"#); - registry::install(crate::Plugin::load(&wat::parse_str(&fast).unwrap(), Limits::default()).unwrap()); + registry::install(crate::Plugin::load(&wat::parse_str(&fast).unwrap(), Limits::default()).unwrap()).unwrap(); // The first run starts the budget at 0 ms and ends at 1,999: the next has 1 ms left, and // ten million steps take longer. let reads = Arc::new(std::sync::atomic::AtomicU64::new(0)); @@ -737,7 +737,7 @@ mod tests { let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); crate::safe_mode::set_active(None); let src = crate::wat::spinning(&crate::wat::manifest("test.effect.cancelled", "effect", "{}"), 1_000_000_000, r#"{"objects":[]}"#); - let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); let ran_first = || RUNS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|r| matches!(r.get(&plugin.serial()), Some(Runs::Done))); let draw = || { @@ -777,7 +777,7 @@ mod tests { crate::safe_mode::parse_marker(&std::fs::read(&json[0]).unwrap()) }; let src = crate::wat::returning(&crate::wat::manifest("test.effect.overlap", "effect", "{}"), r#"{"objects":[]}"#); - let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); let named = Some(crate::safe_mode::Item::of(&plugin)); assert_eq!(marker(), None); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 8b57adbe63..b304e1721e 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -54,6 +54,8 @@ pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms}; +#[doc(hidden)] +pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; /// What the host puts before a plug-in's id to name what it adds: its live effect /// (`plugin.`, [`effect`]) or its file format ([`export`], [`import`]). @@ -87,6 +89,10 @@ pub enum Error { /// Safe Mode is on ([`safe_mode`]): no plug-in loads or runs. #[error("Safe Mode is on: plug-ins don't load or run until VectorCraft starts normally")] SafeMode, + /// The module lists permissions that no recorded grant gives this very module + /// ([`registry::approved`]): it names them, comma-separated. + #[error("needs approval: it asks for {0}, which the user grants when installing it on its own")] + NeedsApproval(String), #[error("{0}")] Io(String), } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index a16bd8a4f9..b6e17e3ad0 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -736,10 +736,41 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { use serde::de::{Error as _, IgnoredAny, MapAccess, SeqAccess, Visitor}; + /// A visitor's methods for a boolean, a number and a string: each is the error its type's + /// `wrong()` gives. + macro_rules! refuse_scalars { + () => { + fn visit_bool(self, _: bool) -> std::result::Result { + Err(E::custom(self.wrong())) + } + fn visit_i64(self, _: i64) -> std::result::Result { + Err(E::custom(self.wrong())) + } + fn visit_u64(self, _: u64) -> std::result::Result { + Err(E::custom(self.wrong())) + } + fn visit_f64(self, _: f64) -> std::result::Result { + Err(E::custom(self.wrong())) + } + fn visit_str(self, _: &str) -> std::result::Result { + Err(E::custom(self.wrong())) + } + }; + } + + /// A string field of an entry: anything else is the error "`{key}` must be a string". + fn string_field<'de, A: MapAccess<'de>>(map: &mut A, key: &str) -> std::result::Result, A::Error> { + Ok(match map.next_value::()? { + Value::String(s) => Ok(s), + _ => Err(format!("`{key}` must be a string")), + }) + } + /// A command's `params`, read in declaration order. struct Params(Vec<(String, Param)>); impl<'de> Deserialize<'de> for Params { @@ -750,6 +781,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu /// The entry at place `.0` in the list. struct Entry(usize); + impl Entry { + fn wrong(&self) -> String { + format!("command {} must be an object with an `id` and a `label`", command_name(self.0, "")) + } + } impl<'de> serde::de::DeserializeSeed<'de> for Entry { type Value = Command; fn deserialize>(self, d: D) -> std::result::Result { @@ -759,21 +795,29 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu impl<'de> Visitor<'de> for Entry { type Value = Command; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "command [{}] as {{id, label, params?}}", self.0) + f.write_str(&self.wrong()) + } + refuse_scalars!(); + fn visit_unit(self) -> std::result::Result { + Err(E::custom(self.wrong())) + } + fn visit_seq>(self, _: A) -> std::result::Result { + Err(A::Error::custom(self.wrong())) } fn visit_map>(self, mut map: A) -> std::result::Result { let (mut id, mut label, mut params) = (None::, None::, None::); let named = |id: &Option, e: &dyn std::fmt::Display| { A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default()))) }; - while let Some(key) = map.next_key::().map_err(|e| named(&id, &e))? { + // A key and an ignored value can only fail as JSON syntax, which keeps serde's own error. + while let Some(key) = map.next_key::()? { let repeated = match key.as_str() { "id" if id.is_none() => { - id = Some(map.next_value().map_err(|e| named(&id, &e))?); + id = Some(string_field(&mut map, "id")?.map_err(|e| named(&id, &e))?); false } "label" if label.is_none() => { - label = Some(map.next_value().map_err(|e| named(&id, &e))?); + label = Some(string_field(&mut map, "label")?.map_err(|e| named(&id, &e))?); false } "params" if params.is_none() => { @@ -782,7 +826,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu } "id" | "label" | "params" => true, _ => { - map.next_value::().map_err(|e| named(&id, &e))?; + map.next_value::()?; false } }; @@ -801,16 +845,22 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu } struct List; + impl List { + fn wrong(&self) -> &'static str { + "`commands` must be a list of commands, each with an `id` and a `label`" + } + } impl<'de> Visitor<'de> for List { type Value = Vec; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("`commands` as a list of {id, label, params?}") + f.write_str(self.wrong()) } + refuse_scalars!(); fn visit_unit(self) -> std::result::Result { Ok(Vec::new()) } fn visit_map>(self, _: A) -> std::result::Result { - Err(A::Error::custom("`commands` must be a list of {id, label, params?}")) + Err(A::Error::custom(self.wrong())) } fn visit_seq>(self, mut seq: A) -> std::result::Result { let mut out = Vec::new(); @@ -1215,14 +1265,27 @@ mod tests { r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A","params":{"r":{"type":"bool"},"r":{"type":"int"}}}]}"#, "command `x`: parameter `r` is declared twice", ), - (r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0]"), - (r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#, "must be a list"), + (r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0] must be an object with an `id` and a `label`"), + (r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A"},null]}"#, "command [1] must be an object"), + (r#"{"id":"a","name":"x","kind":"filter","commands":[["x"]]}"#, "command [0] must be an object"), + (r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":1,"label":"A"}]}"#, "command [0]: `id` must be a string"), + (r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":true}]}"#, "command `x`: `label` must be a string"), + (r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","id":"y","label":"A"}]}"#, "command `x`: duplicate field `id`"), + ( + r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#, + "`commands` must be a list of commands, each with an `id` and a `label`", + ), + (r#"{"id":"a","name":"x","kind":"filter","commands":"x"}"#, "`commands` must be a list of commands"), + (r#"{"id":"a","name":"x","kind":"filter","commands":7}"#, "`commands` must be a list of commands"), + (r#"{"id":"a","name":"x","kind":"filter","commands":true}"#, "`commands` must be a list of commands"), (r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"commands":[{"id":"x","label":"A"}]}"#, "only a filter or a live effect"), (r#"{"id":"a","name":"x","kind":"filter","budget":"heavy","commands":[{"id":"x","label":"A"}]}"#, "heavy filter"), (too_many.as_str(), "at most 32 `commands`"), ] { let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); assert!(e.contains(says), "{bad}: {e}"); + // The message is the manifest reader's own, with serde's place in the manifest once. + assert!(!e.contains("invalid type") && !e.contains("expected") && e.matches(" at line ").count() <= 1, "{bad}: {e}"); } let long_id = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"{}","label":"A"}}]}}"#, "c".repeat(MAX_COMMAND_ID + 1)); assert!(Manifest::parse(long_id.as_bytes()).is_err()); diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index d0a4619622..0e149579f5 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -616,13 +616,25 @@ fn decode_paint(v: &Value, at: &str) -> Result { } stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); g.angle = g.angle.rem_euclid(360.0); + let conic = g.gradient.kind == vectorcraft_color::GradientKind::Conic; + let no_focal = conic || g.gradient.kind == vectorcraft_color::GradientKind::Diamond; if let Some(geom) = &mut g.geom { check_point(geom.start, at)?; check_point(geom.end, at)?; if let Some(f) = geom.focal { check_point(f, at)?; } - geom.aspect = if geom.aspect.is_finite() { geom.aspect.clamp(0.01, 100.0) } else { 1.0 }; + // Conic and diamond gradients have no focal point (the commands refuse one). + if no_focal { + geom.focal = None; + } + let a = geom.aspect; + // A conic's negative aspect mirrors its sweep, so its sign stays. + geom.aspect = match (a.is_finite(), conic) { + (false, _) => 1.0, + (true, true) => a.abs().clamp(0.01, 100.0).copysign(a), + (true, false) => a.clamp(0.01, 100.0), + }; } if let Some(ff) = &mut g.freeform { if ff.points.len() > MAX_ITEMS || ff.lines.len() > MAX_ITEMS || ff.lines.iter().any(|l| l.len() > MAX_ITEMS) { @@ -1195,7 +1207,10 @@ impl Plan { if self.top.as_ref().is_some_and(|(p, _)| *p == parent) && let Some((_, nodes)) = self.top.take() { - out.get_or_insert_with(|| list.to_vec()).extend(nodes.into_iter().map(Arc::new)); + // On a layer, new objects go below its ruler guides, which stay on top. + let o = out.get_or_insert_with(|| list.to_vec()); + let at = Node::guide_run_start(o); + o.splice(at..at, nodes.into_iter().map(Arc::new)); } out } diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index ba4cccae21..a6f3c63f30 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -67,6 +67,48 @@ fn objects_round_trip_through_the_json_model() { assert_eq!(d, before); } +/// A mirrored conic gradient handed back keeps its negative aspect (its sweep stays mirrored), +/// kept within the same range as other aspects; a radial's is kept positive. +#[test] +fn a_mirrored_conic_keeps_its_sign_through_a_plug_in() { + let (d, ids, _) = doc(); + let a = ids[0].0; + let fill = |kind: &str, aspect: f64| { + let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); + g.geom = Some(vectorcraft_color::GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect, focal: None }); + let mut p = serde_json::to_value(Paint::Gradient(Box::new(g))).unwrap(); + p["gradient"]["kind"] = json!(kind); + p + }; + for (kind, aspect, want) in [("Conic", -0.5, -0.5), ("Conic", -500.0, -100.0), ("Conic", 0.5, 0.5), ("Radial", -0.5, 0.01)] { + let mut d = d.clone(); + let out = decode_json(json!({"objects": [{"id": a, "fills": [fill(kind, aspect)]}]})).unwrap(); + apply_output(&mut d, &ids, out, None, &keep).unwrap(); + let Paint::Gradient(g) = d.node(ids[0]).unwrap().appearance.fill_paint() else { panic!("a gradient fill") }; + assert_eq!(g.geom.unwrap().aspect, want, "{kind} {aspect}"); + } +} + +/// A focal point handed back on a conic or diamond gradient, which have none, is dropped; a +/// radial's is kept. +#[test] +fn only_a_radial_keeps_a_focal_point_through_a_plug_in() { + let (d, ids, _) = doc(); + let a = ids[0].0; + let focal = Point::new(3.0, 1.0); + for (kind, want) in [("Conic", None), ("Diamond", None), ("Radial", Some(focal))] { + let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); + g.geom = Some(vectorcraft_color::GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: Some(focal) }); + let mut p = serde_json::to_value(Paint::Gradient(Box::new(g))).unwrap(); + p["gradient"]["kind"] = json!(kind); + let mut d = d.clone(); + let out = decode_json(json!({"objects": [{"id": a, "fills": [p]}]})).unwrap(); + apply_output(&mut d, &ids, out, None, &keep).unwrap(); + let Paint::Gradient(g) = d.node(ids[0]).unwrap().appearance.fill_paint() else { panic!("a gradient fill") }; + assert_eq!(g.geom.unwrap().focal, want, "{kind}"); + } +} + /// A path handed back as it was stays the live shape it was (a rectangle keeps its corner /// widgets); a path that changed is a plain path. #[test] @@ -164,6 +206,21 @@ fn compound_guides_are_not_filter_targets() { assert!(targets.contains(&made[1]), "the plain compound path"); } +/// New objects put on top of a layer go below its ruler guides, which stay on top; a ruler guide +/// is never a filter target. +#[test] +fn new_objects_go_below_a_layers_ruler_guides() { + let (mut d, _, layer) = doc(); + let guide = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 5.0, artboard: None }); + let gid = d.insert(Some(layer), usize::MAX, guide).unwrap(); + assert!(!filter_targets(&d, &[layer]).contains(&gid)); + let out = json!({"objects": [{"name": "N", "type": "path", "path": square(0.0)}]}); + let made = apply_output(&mut d, &[], decode_json(out).unwrap(), Some(layer), &keep).unwrap(); + let ids: Vec = d.children(Some(layer)).unwrap().iter().map(|n| n.id).collect(); + assert_eq!(ids.last(), Some(&gid)); + assert_eq!(ids.get(ids.len() - 2), made.first()); +} + /// `guide` and `locked` make objects guides (a compound path's members too) and lock them, or undo /// both; locked objects and guides are not [`selectable`]. Other values are refused. #[test] diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 7380edd568..b8c8672693 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -275,6 +275,32 @@ impl Grant { } } +/// A [`Grant`] that [`crate::registry::grant`] records. The engine makes one where it records what +/// a person approved and where it loads the grants kept in its plug-in folder; tests that set up a +/// grant use the same constructors. `tests/grant_sites.rs` fails when other shipped code makes one. +/// Native code linked into the app can still call these constructors, so the token does not +/// protect against such code. +#[derive(Debug)] +pub struct GrantToken(Grant); + +impl GrantToken { + /// The grant the engine records after a person approved the module it covers, or in a session + /// whose starter allowed requests to grant permissions (`--allow-plugin-grants`). + pub fn after_engine_approval(grant: Grant) -> Self { + Self(grant) + } + + /// A grant the engine read from the grants file of its plug-in folder, for a module it loads. + pub fn from_engine_grants_file(grant: Grant) -> Self { + Self(grant) + } + + /// The grant it holds. + pub fn grant(&self) -> &Grant { + &self.0 + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index be7f12180f..ee3732908c 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -7,9 +7,8 @@ use std::collections::{BTreeMap, HashSet}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; -#[cfg(not(target_arch = "wasm32"))] use crate::Error; -use crate::permissions::Grant; +use crate::permissions::{Grant, GrantToken}; use crate::storage::Storage; use crate::{Limits, Plugin, Result}; @@ -35,8 +34,11 @@ pub fn storage(id: &str) -> Option> { STORAGE.read().unwrap_or_else(|e| e.into_inner()).get(id).cloned() } -/// Records what the user approved for a plug-in, replacing an earlier grant for its id. -pub fn grant(g: Grant) { +/// Records what the user approved for a plug-in, replacing an earlier grant for its id. Only a +/// [`GrantToken`] is recorded, which the engine makes after an approval or when it loads its grants +/// file. +pub fn grant(token: GrantToken) { + let g = token.grant().clone(); GRANTS.write().unwrap_or_else(|e| e.into_inner()).insert(g.id.clone(), g); } @@ -63,20 +65,27 @@ pub fn approved(plugin: &Plugin) -> bool { !m.asks_permissions() || granted(&m.id).is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions())) } -/// Installs `plugin`, replacing one with the same id. -pub fn install(mut plugin: Plugin) -> Arc { +/// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists +/// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and +/// the plug-in installed under its id, the grants and the revision stay as they were. +pub fn install(mut plugin: Plugin) -> Result> { // The revision moves while the write lock is held, so a cache that reads the new revision and - // then the plug-ins finds the new plug-in among them. + // then the plug-ins finds the new plug-in among them. The approval is checked while it is held + // too. let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner()); + if !approved(&plugin) { + return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", "))); + } plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1); let p = Arc::new(plugin); plugins.insert(p.id().to_string(), p.clone()); - p + Ok(p) } -/// Loads `bytes` with the default limits and installs the plug-in. +/// Loads `bytes` with the default limits and installs the plug-in ([`install`]: one that lists +/// permissions installs only when they were granted to this very module). pub fn install_bytes(bytes: &[u8]) -> Result> { - Ok(install(Plugin::load(bytes, Limits::default())?)) + install(Plugin::load(bytes, Limits::default())?) } pub fn get(id: &str) -> Option> { @@ -162,7 +171,8 @@ pub fn load_folder(dir: &std::path::Path) -> Result { } /// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list -/// permissions only those `approve` accepts; the others are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and +/// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others +/// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the /// next load skips it before it runs); the launch marker names each file while it loads /// ([`crate::safe_mode::loading`]). In Safe Mode nothing loads ([`Error::SafeMode`]). When the @@ -206,12 +216,14 @@ pub fn load_folder_where( } Ok(p) if p.manifest().asks_permissions() && !approve(&p) => { let asked = crate::permissions::names(&p.manifest().permissions()).join(", "); - report.failed.push(( - f.display().to_string(), - format!("needs approval: it asks for {asked}, which the user grants when installing it on its own"), - )); + report.failed.push((f.display().to_string(), Error::NeedsApproval(asked).to_string())); } - Ok(p) => report.loaded.push(install(p).id().to_string()), + // `approve` only narrows what installs: `install` still refuses a module that no + // recorded grant covers. + Ok(p) => match install(p) { + Ok(p) => report.loaded.push(p.id().to_string()), + Err(e) => report.failed.push((f.display().to_string(), e.to_string())), + }, Err(e) => report.failed.push((f.display().to_string(), e.to_string())), } } @@ -231,6 +243,7 @@ mod tests { /// waiting for the set leaves the revision alone until it holds the set. #[test] fn an_install_changes_the_revision_only_while_it_holds_the_set() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let plugin = Plugin::load(include_bytes!("../tests/fixtures/desaturate.wasm"), Limits::default()).unwrap(); let id = plugin.id().to_string(); let held = PLUGINS.read().unwrap_or_else(|e| e.into_inner()); @@ -241,8 +254,95 @@ mod tests { revision() != before }); drop(held); - installing.join().unwrap(); + installing.join().unwrap().unwrap(); assert!(!moved, "the revision changed while the install waited for the set"); assert!(revision() > before && remove(&id)); } + + /// A module of a filter `id` whose manifest lists `permissions` (a JSON list, or nothing), with + /// `marker` in its code so that two markers give two SHA-256s. + fn module(id: &str, permissions: Option<&str>, marker: i64) -> Vec { + let listed = permissions.map(|p| format!(r#","permissions":{p}"#)).unwrap_or_default(); + let manifest = format!(r#"{{"id":"{id}","name":"T","kind":"filter"{listed}}}"#); + wat::parse_str(crate::wat::module(&manifest, &format!("(i64.const {marker}) (drop) (i64.const 0)"), "", 1)).unwrap() + } + + fn grant_for(id: &str, bytes: &[u8], permissions: Vec) -> Grant { + Grant { id: id.into(), hash: crate::permissions::sha256_hex(bytes), permissions } + } + + /// A module that lists permissions installs only once a recorded grant gives this very module + /// all of them: refused, nothing changes, neither the revision nor the plug-in under its id. + #[test] + fn install_bytes_refuses_unapproved_manifest_permissions() { + // The other tests that install or remove plug-ins hold it, so the revision moves only here. + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.registry.unapproved"; + let plain = install_bytes(&module(id, None, 1)).unwrap(); + let before = revision(); + let e = install_bytes(&module(id, Some(r#"["doc.read"]"#), 2)).unwrap_err(); + assert_eq!(e, Error::NeedsApproval("doc.read".into())); + assert_eq!(revision(), before, "nothing installed"); + assert_eq!(get(id).map(|p| p.hash().to_string()), Some(plain.hash().to_string()), "the plug-in before it stays"); + assert!(granted(id).is_none()); + assert!(remove(id)); + } + + /// `install` itself and a folder load whose `approve` accepts everything refuse the module too. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn install_and_folder_callback_cannot_bypass_approval() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let id = "test.registry.bypass"; + let plain = install_bytes(&module(id, Some("[]"), 3)).unwrap(); + let asking = module(id, Some(r#"["doc.read","doc.write"]"#), 4); + let e = install(Plugin::load(&asking, Limits::default()).unwrap()).unwrap_err(); + assert_eq!(e, Error::NeedsApproval("doc.read, doc.write".into())); + let dir = std::env::temp_dir().join(format!("vc-registry-bypass-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("asking.wasm"), &asking).unwrap(); + let r = load_folder_where(&dir, |_| Ok(()), |_| true).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(r.loaded.is_empty(), "{r:?}"); + assert_eq!(r.failed.len(), 1); + assert!(r.failed[0].1.starts_with("needs approval: it asks for doc.read, doc.write"), "{r:?}"); + assert_eq!(get(id).map(|p| p.hash().to_string()), Some(plain.hash().to_string()), "the plug-in before it stays"); + assert!(remove(id)); + } + + /// A recorded grant lets in only the module with its id and SHA-256 that lists nothing it + /// doesn't grant; a module whose manifest lists no permissions, or an empty list, needs none. + #[test] + fn matching_grant_allows_only_exact_bytes() { + use crate::permissions::Permission::{DocRead, DocWrite}; + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.registry.exact"; + let bytes = module(id, Some(r#"["doc.read","doc.write"]"#), 5); + let plugin = Plugin::load(&bytes, Limits::default()).unwrap(); + assert_eq!(plugin.hash(), crate::permissions::sha256_hex(&bytes), "a grant's hash is the loaded module's"); + let refused = |g: Grant, why: &str| { + let other = g.id.clone(); + revoke(id); + grant(GrantToken::after_engine_approval(g)); + assert!(matches!(install_bytes(&bytes), Err(Error::NeedsApproval(_))), "{why}"); + assert!(get(id).is_none(), "{why}"); + revoke(&other); + }; + refused(grant_for(id, &module(id, Some(r#"["doc.read","doc.write"]"#), 6), vec![DocRead, DocWrite]), "other bytes"); + refused(grant_for("test.registry.other", &bytes, vec![DocRead, DocWrite]), "another id"); + refused(Grant { id: id.into(), hash: "not a hash".into(), permissions: vec![DocRead, DocWrite] }, "a malformed hash"); + refused( + Grant { id: id.into(), hash: crate::permissions::sha256_hex(&bytes).to_uppercase(), permissions: vec![DocRead, DocWrite] }, + "an upper-case hash", + ); + refused(grant_for(id, &bytes, vec![DocRead]), "a missing permission"); + grant(GrantToken::from_engine_grants_file(grant_for(id, &bytes, vec![DocRead, DocWrite]))); + assert_eq!(install_bytes(&bytes).unwrap().hash(), plugin.hash()); + assert!(remove(id) && revoke(id)); + for listed in [None, Some("[]")] { + assert!(install_bytes(&module(id, listed, 7)).is_ok(), "{listed:?}"); + assert!(granted(id).is_none() && remove(id), "{listed:?}"); + } + } } diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 863ec0a3a5..5a2db2ff0d 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -14,7 +14,7 @@ use crate::{Error, Kind, Result}; pub const ABI_VERSION: i32 = 1; /// Fuel handed out per slice; between slices the host checks the deadline. -const FUEL_SLICE: u64 = 20_000_000; +pub const FUEL_SLICE: u64 = 20_000_000; /// wasmi's fuel costs, but compiling costs nothing. wasmi compiles a function when it is first /// called, and charges the run that calls it by the function's size. When the slice a run was in @@ -24,6 +24,9 @@ const FUEL_SLICE: u64 = 20_000_000; /// the next. Copying keeps wasmi's default cost, a unit for every 64 bytes. const FUEL_COSTS: CustomFuelCosts = CustomFuelCosts { bytes_copied_per_fuel: 64, fuel_per_bytes_translated: 0, fuel_per_bytes_validated: 0 }; +/// Bytes a bulk memory instruction copies or fills for each unit of fuel. +pub const BYTES_COPIED_PER_FUEL: u32 = FUEL_COSTS.bytes_copied_per_fuel; + /// Instructions a heavy filter's run may use besides [`Limits::fuel_per_byte`] for each byte of /// input ([`crate::Budget::Heavy`]): 20 times a light one's. Its output's size can't add to it: /// the host learns that only once the run has ended. diff --git a/crates/plugins/tests/grant_sites.rs b/crates/plugins/tests/grant_sites.rs new file mode 100644 index 0000000000..d0c0479337 --- /dev/null +++ b/crates/plugins/tests/grant_sites.rs @@ -0,0 +1,82 @@ +//! The shipped code that records a plug-in grant: only the engine's install approval and its load +//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`. A new call +//! site fails this test until it is added to the list. It checks the source, not what native code +//! can do at run time. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// `(text, file, how many times)` for every place shipped code may name it. +const EXPECTED: &[(&str, &str, usize)] = &[ + ("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1), + ("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2), + ("registry::grant", "crates/engine/src/cmd/plugin.rs", 1), + ("registry::grant", "crates/engine/src/store.rs", 2), +]; + +/// Every `.rs` file under `dir`, without test files and folders. +fn sources(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().to_string(); + if path.is_dir() { + if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") { + sources(&path, out); + } + } else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") { + out.push(path); + } + } +} + +/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {` +/// on. +fn shipped(text: &str) -> Vec<&str> { + let lines: Vec<&str> = text.lines().collect(); + let opens_test_module = |i: usize| { + lines[i] == "#[cfg(test)]" + && lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{')) + }; + let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len()); + lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect() +} + +/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`). +fn count(line: &str, name: &str) -> usize { + line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count() +} + +#[test] +fn grant_token_call_sites_are_limited() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut files = Vec::new(); + for top in ["crates", "apps", "xtask"] { + sources(&root.join(top), &mut files); + } + assert!(files.len() > 100, "found only {} source files under {}", files.len(), root.display()); + let mut found: BTreeMap<(&str, String), usize> = BTreeMap::new(); + for file in &files { + let text = std::fs::read_to_string(file).unwrap(); + let rel = file.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"); + for line in shipped(&text) { + for name in ["GrantToken::after_engine_approval", "GrantToken::from_engine_grants_file", "registry::grant"] { + let n = count(line, name); + if n > 0 { + *found.entry((name, rel.clone())).or_default() += n; + } + } + } + } + let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect(); + assert_eq!(found, expected, "shipped code that makes a grant token or records a grant"); +} + +/// The audit's own filters: a test module and comments are left out, a longer name isn't counted. +#[test] +fn the_audit_skips_test_code_and_comments() { + let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n"; + let lines = shipped(text); + assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::(), 1, "{lines:?}"); +} diff --git a/crates/plugins/tests/safe_mode.rs b/crates/plugins/tests/safe_mode.rs index f6278b8e39..8b3149cf83 100644 --- a/crates/plugins/tests/safe_mode.rs +++ b/crates/plugins/tests/safe_mode.rs @@ -58,9 +58,9 @@ fn temp_dir(name: &str) -> std::path::PathBuf { fn in_safe_mode_nothing_loads_or_runs() { let _f = fresh(); // Installed before Safe Mode was turned on. - let before = registry::install(Plugin::load(&filter("test.safe.before"), Limits::default()).unwrap()); + let before = registry::install(Plugin::load(&filter("test.safe.before"), Limits::default()).unwrap()).unwrap(); let fx = build(&tpl::returning(&tpl::manifest("test.safe.effect", "effect", "{}"), r#"{"objects":[]}"#)); - registry::install(Plugin::load(&fx, Limits::default()).unwrap()); + registry::install(Plugin::load(&fx, Limits::default()).unwrap()).unwrap(); let dir = temp_dir("gate"); std::fs::write(dir.join("a.wasm"), filter("test.safe.folder")).unwrap(); diff --git a/crates/render/src/dither.rs b/crates/render/src/dither.rs index 0dd887089b..dfd2f53927 100644 --- a/crates/render/src/dither.rs +++ b/crates/render/src/dither.rs @@ -1,6 +1,7 @@ -//! Dithered gradient fills in the renderer. +//! Dithered gradient fills, and diamond gradients, in the renderer. //! -//! A dithered linear or radial gradient is drawn as pixels: the gradient sampled on a grid over +//! A dithered linear or radial gradient, and a diamond gradient (which has no vector gradient to +//! draw it), is drawn as pixels: the gradient sampled on a grid over //! the painted box with a cell per device pixel or finer (in quarter-octave steps, so a pan reuses //! the grid and a zoom rarely misses), each colour channel given fine noise of up to a level //! ([`vectorcraft_color::gradient::dither_noise`]) before it is rounded, and drawn as an image @@ -50,18 +51,19 @@ fn cells(px: f64) -> u16 { 2f64.powf(steps / 4.0).ceil().clamp(1.0, MAX_CELLS) as u16 } -/// Cache key of gradient `g` placed on box `b` as a `cols` × `rows` grid, cells `win` of it, -/// painted with `ink` (and the active colour settings, which turn colours into display RGB or -/// inks). -fn key(g: &GradientPaint, b: Rect, cols: u16, rows: u16, win: &[Range; 2], ink: Ink) -> u64 { +/// Cache key of gradient `g` placed on box `place`, sampled as a `cols` × `rows` grid over box +/// `b`, cells `win` of it, painting a fill (`fill`) with `ink` (and the active color settings, +/// which turn colors into display RGB or inks). +#[allow(clippy::too_many_arguments)] +fn key(g: &GradientPaint, place: Rect, b: Rect, cols: u16, rows: u16, win: &[Range; 2], ink: Ink, fill: bool) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); let gr = &g.gradient; - (gr.kind as u8, gr.dither, gr.method as u8).hash(&mut h); + (gr.kind as u8, gr.dither && fill, gr.method as u8).hash(&mut h); for s in &gr.stops { (s.offset.to_bits(), s.opacity.to_bits(), s.midpoint.to_bits()).hash(&mut h); s.color.key().hash(&mut h); } - let geom = g.resolve(b); + let geom = g.resolve(place); (geom.start.x.to_bits(), geom.start.y.to_bits(), geom.end.x.to_bits(), geom.end.y.to_bits(), geom.aspect.to_bits()).hash(&mut h); geom.focal.map(|f| (f.x.to_bits(), f.y.to_bits())).hash(&mut h); (b.x0.to_bits(), b.y0.to_bits(), b.x1.to_bits(), b.y1.to_bits(), cols, rows).hash(&mut h); @@ -89,15 +91,17 @@ fn window(xf: Affine, w: u16, h: u16, b: Rect, cols: u16, rows: u16) -> Option<[ Some([span(seen.x0, seen.x1, b.x0, b.width(), cols)?, span(seen.y0, seen.y1, b.y0, b.height(), rows)?]) } -/// Cells `win` (columns, rows) of `g` placed on `b` as a `cols` × `rows` grid, as a -/// premultiplied pixmap, colours as `ink` paints them. -pub(crate) fn rasterize(g: &GradientPaint, b: Rect, cols: u16, rows: u16, win: [Range; 2], ink: Ink) -> Pixmap { +/// Cells `win` (columns, rows) of `g` placed on `place`, sampled as a `cols` × `rows` grid over +/// `b`, as a premultiplied pixmap, colors as `ink` paints them, with dither's noise when it +/// paints a fill (`fill`). +#[allow(clippy::too_many_arguments)] +pub(crate) fn rasterize(g: &GradientPaint, place: Rect, b: Rect, cols: u16, rows: u16, win: [Range; 2], ink: Ink, fill: bool) -> Pixmap { let (w, h) = (win[0].len() as u16, win[1].len() as u16); let adjusted = ink.gradient(&g.gradient).map(|gradient| GradientPaint { gradient, ..g.clone() }); let ink = if adjusted.is_some() { ink.base() } else { ink }; let g = adjusted.as_ref().unwrap_or(g); let data = g - .pixels_within(b, b, cols, rows, win, true, &|c| ink.rgb(c)) + .pixels_within(place, b, cols, rows, win, fill, &|c| ink.rgb(c)) .map(|[r, gr, bl, a]| { let pm = |v: u8| ((u16::from(v) * u16::from(a) + 127) / 255) as u8; vello_cpu::color::PremulRgba8 { r: pm(r), g: pm(gr), b: pm(bl), a } @@ -106,11 +110,14 @@ pub(crate) fn rasterize(g: &GradientPaint, b: Rect, cols: u16, rows: u16, win: [ Pixmap::from_parts(data, w, h) } -/// Set dithered gradient `g` on box `bounds` (in the paint's space, which the context's current -/// transform maps to pixels) as the context paint. Returns false for an empty box or one off the -/// render target. -pub(crate) fn set_dithered_paint(ctx: &mut RenderContext, g: &GradientPaint, bounds: Rect, ink: Ink) -> bool { - let Some(b) = painted_box(bounds) else { return false }; +/// Set gradient `g` placed on box `bounds` (in the paint's space, which the context's current +/// transform maps to pixels) as the context paint, drawn as pixels over that box and box `area` +/// (a stroke's outline, whose miters, caps and arrowheads can reach past `bounds`), with dither's +/// noise when it paints a fill (`fill`). Returns false for an empty box or one off the render +/// target. Past both boxes, the pixels at their edge continue. +pub(crate) fn set_dithered_paint(ctx: &mut RenderContext, g: &GradientPaint, bounds: Rect, area: Rect, ink: Ink, fill: bool) -> bool { + let Some(place) = painted_box(bounds) else { return false }; + let b = Some(place.union(area.abs())).filter(|r| r.is_finite()).unwrap_or(place); // Device pixels per unit along the box's sides. let [m0, m1, m2, m3, _, _] = ctx.transform().as_coeffs(); let (sx, sy) = (m0.hypot(m1), m2.hypot(m3)); @@ -121,7 +128,7 @@ pub(crate) fn set_dithered_paint(ctx: &mut RenderContext, g: &GradientPaint, bou let (cols, rows) = (cells(wpx), cells(hpx)); let Some(win) = window(*ctx.transform(), ctx.width(), ctx.height(), b, cols, rows) else { return false }; let (first_col, first_row) = (win[0].start, win[1].start); - let k = key(g, b, cols, rows, &win, ink); + let k = key(g, place, b, cols, rows, &win, ink, fill); let pm = GRIDS .with(|c| { let mut c = c.borrow_mut(); @@ -129,7 +136,7 @@ pub(crate) fn set_dithered_paint(ctx: &mut RenderContext, g: &GradientPaint, bou c.get(&k, t).cloned() }) .unwrap_or_else(|| { - let pm = Arc::new(rasterize(g, b, cols, rows, win, ink)); + let pm = Arc::new(rasterize(g, place, b, cols, rows, win, ink, fill)); GRIDS.with(|c| { let mut c = c.borrow_mut(); let t = c.tick(); diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index 201931a8ac..635f906839 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -248,7 +248,7 @@ fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node, held: Option<&Arc>, return None; } match &n.kind { - NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. } => None, + NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => None, NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(n) => children .iter() .skip(usize::from(n.extras().shaper.is_some())) @@ -289,7 +289,7 @@ fn without_undrawn(n: &Node) -> Option { if keeps_all || !matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) { return None; } - let undrawn = |c: &Node| !c.visible || matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. }); + let undrawn = |c: &Node| !c.visible || c.is_guide() || c.is_template(); let mut changed = false; let kept: Vec> = n .children()? diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 777276e696..98c031c89a 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -447,7 +447,7 @@ impl Parts<'_> { /// Node `n` (a top-level layer, or with Maximum Editability anything in one) and its parts. fn add(&mut self, n: &Node) { // Templates and guides aren't artwork. - if matches!(n.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. }) || !(n.visible || self.o.hidden_layers) { + if n.is_template() || n.is_guide() || !(n.visible || self.o.hidden_layers) { return; } let (hidden, opacity) = (!n.visible, opacity_byte(n.opacity)); diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index e56278f1de..a488cceff2 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -271,6 +271,28 @@ fn guides_are_not_layers() { assert_eq!(parse(&export(&b.build(), &o)).count, -3, "the group and the square"); } +/// Ruler guides on a layer and a sublayer change nothing in the export: the same file with and +/// without Maximum Editability, the same drawn bounds and the same cached size of each layer. +#[test] +fn ruler_guides_are_not_exported() { + use vectorcraft_doc::{NodeId, NodeKind}; + let plain = doc(); + let mut guided = plain.clone(); + let guide = |id, vertical, pos| Node::new(NodeId(id), NodeKind::RulerGuide { vertical, pos, artboard: None }); + let (bottom, inner) = (guided.layers[0].id, guided.layers[1].children().unwrap().last().unwrap().id); + guided.insert(Some(bottom), usize::MAX, guide(900, true, 20.0)).unwrap(); + guided.insert(Some(bottom), usize::MAX, guide(901, false, 15.0)).unwrap(); + guided.insert(Some(inner), usize::MAX, guide(902, true, 3.0)).unwrap(); + for psd in [PsdOptions::default(), PsdOptions { max_editability: true, ..PsdOptions::default() }] { + assert_eq!(export(&guided, &opts(psd.clone())), export(&plain, &opts(psd))); + } + assert_eq!(art_bounds(&guided), art_bounds(&plain)); + for (g, p) in guided.layers.iter().zip(&plain.layers) { + assert_eq!(crate::drawn_bounds(&guided, g), crate::drawn_bounds(&plain, p)); + assert_eq!(crate::lru::node_bytes(g), crate::lru::node_bytes(p)); + } +} + #[test] fn a_background_colour_is_the_bottom_layer() { let doc = doc(); diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index 293e824664..a6deb8e334 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -46,6 +46,8 @@ struct Sub { ends: Vec, /// The box of each run of segments ([`segment_bounds`]). boxes: Vec>, + /// The box of the points of each run of segments: their ends and their control points. + controls: Vec>, /// The box of the miter tips of `tips_of` at the joints whose first segment is in each run. tips: Vec>, } @@ -122,6 +124,15 @@ fn end(el: &PathEl) -> Option { } } +/// The box of the points of segment `s`: its ends and its control points. +fn segment_controls(s: PathSeg) -> Rect { + match s { + PathSeg::Line(l) => Rect::from_points(l.p0, l.p1), + PathSeg::Quad(q) => Rect::from_points(q.p0, q.p2).union_pt(q.p1), + PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2), + } +} + /// 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() @@ -146,8 +157,10 @@ 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![] }; + let ends = whole_runs(segs); + let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, ends, boxes: vec![], controls: vec![], tips: vec![] }; sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); + sub.controls = (0..sub.runs()).map(|r| sub.run_controls(els, r)).collect(); if let Some(st) = st { sub.tips = (0..sub.runs()).map(|r| sub.run_tips(els, r, st)).collect(); } @@ -191,6 +204,22 @@ impl Sub { self.range(r).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) } + /// The box of the points of the segments of run `r`: their ends and their control points. + fn run_controls(&self, els: &[PathEl], r: usize) -> Option { + self.range(r).filter_map(|i| self.seg(els, i)).map(segment_controls).reduce(|a, b| a.union(b)) + } + + /// Measure again the box and the box of the points of run `r`. + fn measure_run(&mut self, els: &[PathEl], r: usize) { + let (b, c) = (self.run_box(els, r), self.run_controls(els, r)); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + if let Some(slot) = self.controls.get_mut(r) { + *slot = c; + } + } + /// The segment with length that follows segment `i` (round to the start when closed), or /// `None` when there is none other than `i`. fn next_drawn(&self, els: &[PathEl], i: usize) -> Option { @@ -297,10 +326,7 @@ impl Sub { 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; - } + self.measure_run(els, r); } let Some(st) = st else { return }; // A joint's tip changes with its segments and with which segment with length comes next: @@ -380,11 +406,8 @@ impl Sub { 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; - } + for r in stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r) { + self.measure_run(els, r); } let Some(st) = st else { return Some(()) }; let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); @@ -422,7 +445,7 @@ impl Sub { 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() { + if r1 > self.boxes.len() || r1 > self.controls.len() || r1 > stale.len() { return None; } let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; @@ -430,6 +453,7 @@ impl Sub { 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)); + self.controls.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)); } @@ -602,6 +626,15 @@ impl KeptPath { }) } + /// The box of the points of the path's elements, as [`BezPath::control_box`] measures it: each + /// subpath's MoveTo and the boxes of the points of its runs, joined. + pub(crate) fn control_box(&self) -> Rect { + let els = self.path.elements(); + let start = |s: &Sub| els.get(s.start).and_then(end).filter(|_| s.anchors > 0).map(|p| Rect::from_points(p, p)); + let runs = |s: &Sub| s.controls.iter().flatten().copied().reduce(|a, b| a.union(b)); + self.parts.iter().flatten().flat_map(|s| [start(s), runs(s)]).flatten().reduce(|a, b| a.union(b)).unwrap_or_default() + } + /// The box of the miter tips of `st` at every joint of the path ([`StrokeLayer::miter_tip`]), /// for [`StrokeLayer::bounds_with_tips`]: measured whole when the tips kept are another /// stroke's, then kept up to date with the path. diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 3f5ebbb2fe..2b6610beb1 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -781,7 +781,7 @@ mod tests { d.symbols.push(Symbol { dynamic: false, name: format!("S{k}"), art: Arc::new(art) }); } let first = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "S0".into(), xf: Affine::IDENTITY }); - let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let envelope = NodeKind::Envelope { content: vec![Arc::new(first)], kind: Box::new(kind), @@ -815,7 +815,7 @@ mod tests { d.symbols.push(Symbol { dynamic: false, name: name.into(), art: art.clone() }); } let content = ["A", "B", "C"].map(|s| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: s.into(), xf: Affine::IDENTITY }))); - let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let envelope = NodeKind::Envelope { content: content.to_vec(), kind: Box::new(kind), diff --git a/crates/render/src/lru.rs b/crates/render/src/lru.rs index 54ab4e51ed..85f327b89b 100644 --- a/crates/render/src/lru.rs +++ b/crates/render/src/lru.rs @@ -243,10 +243,14 @@ pub(crate) fn path_bytes(p: &BezPath) -> usize { size_of_val(p.elements()) } -/// Approximate bytes of node `n` and its members: the nodes and their path anchors. +/// Approximate bytes of node `n` and its members: the nodes and their path anchors. Ruler guides +/// are not drawn art and are not counted. pub(crate) fn node_bytes(n: &Node) -> usize { let mut b = 0; n.walk(&mut |c| { + if c.is_ruler_guide() { + return; + } b += size_of::() + NODE_OVERHEAD; if let Some(p) = c.path_data() { b += p.subpaths.iter().map(|s| size_of::() + s.anchors.len() * size_of::()).sum::(); diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index 900a59c836..a4d9fda7af 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -1,4 +1,4 @@ -use super::{Affine, AppearanceItem, Arc, BezPath, Document, Node, NodeKind, StrokeLayer, brush_fx, effects}; +use super::{Affine, AppearanceItem, Arc, Document, Node, NodeKind, Rect, StrokeLayer, brush_fx, effects}; /// Most pixels from the origin that a shape handed to the rasterizer may reach, or a stroke be /// wide. A document's art stays within 4 million points, 2.6 billion pixels at the closest zoom. @@ -6,10 +6,11 @@ use super::{Affine, AppearanceItem, Arc, BezPath, Document, Node, NodeKind, Stro /// for more memory than there is, either of which ends the app: it is left undrawn. const MAX_DEVICE: f64 = 1e10; -/// Can shape `bp` of `n` be drawn through `view`: its control points (finite) within -/// [`MAX_DEVICE`] pixels, and its visible strokes no wider? -pub(crate) fn drawable(bp: &BezPath, view: Affine, n: &Node) -> bool { - let b = view.transform_rect_bbox(bp.control_box()); +/// Can a shape of `n` whose control points have the box `control` (`BezPath::control_box`) be +/// drawn through `view`: its control points (finite) within [`MAX_DEVICE`] pixels, and its visible +/// strokes no wider? +pub(crate) fn drawable(control: Rect, view: Affine, n: &Node) -> bool { + let b = view.transform_rect_bbox(control); let scale = view.determinant().abs().sqrt(); let widest = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(st) = i { Some(st.width) } else { None }).fold(0.0, f64::max); [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_DEVICE) && (widest * scale).is_finite() && widest * scale <= MAX_DEVICE @@ -108,9 +109,11 @@ pub(crate) fn holds_instance(n: &Node) -> bool { } /// Is `a` left out of a frame `doc` draws with `opts`, before any culling: hidden, a template or -/// guide the view hides, drawn hidden, or the instance its symbol is being edited from? +/// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its +/// symbol is being edited from? pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { - let view_item = (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) + let view_item = a.is_ruler_guide() + || (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) } diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 8a152e11f2..8ca670eb3f 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -264,6 +264,25 @@ pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec { out } +/// For each of `to` pixels spread over `from` (both above 0), the `from` pixels under it and the +/// share of it each covers (summing to 1). +fn area_spans(from: usize, to: usize) -> Vec> { + let step = from as f64 / to as f64; + (0..to) + .map(|i| { + let (start, end) = ((i * from) as f64 / to as f64, ((i + 1) * from) as f64 / to as f64); + let first = start.floor() as usize; + let last = (end.ceil() as usize).max(first + 1).min(from); + (first..last) + .filter_map(|j| { + let cover = end.min((j + 1) as f64) - start.max(j as f64); + (cover > 0.0).then_some((j, cover / step)) + }) + .collect() + }) + .collect() +} + /// A rendered image (premultiplied RGBA8, row-major). pub struct Rendered { pub width: u32, @@ -285,6 +304,49 @@ impl Rendered { } out } + /// This image at `width`×`height` pixels: each new pixel is the average of the area of this one + /// under it, the pixels at its edges weighted by how much of them it covers. Colors are averaged + /// premultiplied, so transparent pixels add no color. At the same size it is a copy. An error + /// when a side is 0 or the pixel buffer doesn't match the image size. + pub fn area_resized(&self, width: u32, height: u32) -> Result { + let (sw, sh) = (self.width as usize, self.height as usize); + if sw.checked_mul(sh).and_then(|n| n.checked_mul(4)) != Some(self.pixels.len()) { + return Err("the pixel buffer doesn't match the image size".into()); + } + if sw == 0 || sh == 0 || width == 0 || height == 0 { + return Err(format!("a {sw} × {sh} image can't be resized to {width} × {height} pixels")); + } + if (width, height) == (self.width, self.height) { + return Ok(Rendered { width, height, pixels: self.pixels.clone() }); + } + let (dw, dh) = (width as usize, height as usize); + let len = dw.checked_mul(dh).and_then(|n| n.checked_mul(4)).ok_or_else(|| format!("a {width} × {height} image is too large"))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(len).map_err(|e| format!("a {width} × {height} image: {e}"))?; + let (cols, rows) = (area_spans(sw, dw), area_spans(sh, dh)); + let src: Vec<&[[u8; 4]]> = self.pixels.as_chunks::<4>().0.chunks_exact(sw).collect(); + let mut acc = vec![[0f64; 4]; dw]; + for row in &rows { + acc.fill([0.0; 4]); + for &(y, wy) in row { + let Some(line) = src.get(y) else { continue }; + for (a, col) in acc.iter_mut().zip(&cols) { + for &(x, wx) in col { + if let Some(px) = line.get(x) { + let w = wy * wx; + for (s, v) in a.iter_mut().zip(px) { + *s += w * f64::from(*v); + } + } + } + } + } + for a in &acc { + pixels.extend(a.map(|v| v.round().clamp(0.0, 255.0) as u8)); + } + } + Ok(Rendered { width, height, pixels }) + } /// Encode as PNG without metadata (thumbnails, screenshots, embedded rasters; exports use /// [`encode`]). pub fn to_png(&self) -> Result, String> { diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 003a08807d..dd83e4cee7 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -40,6 +40,14 @@ pub(crate) fn set_paint(ctx: &mut RenderContext, p: &Paint, bounds: Rect, f: &Fr }; g.with_stops(stops.as_slice()) } + GradientKind::Conic => { + // One turn about the origin, carried onto the extent ellipse: its frame starts + // the sweep along the vector, and a mirrored frame reverses it. + ctx.set_paint_transform(geom.conic_frame()); + peniko::Gradient::new_sweep((0.0, 0.0), 0.0, std::f32::consts::TAU).with_stops(stops.as_slice()) + } + // peniko has no diamond gradient: it is drawn as pixels, as a dithered fill is. + GradientKind::Diamond => return crate::dither::set_dithered_paint(ctx, g, bounds, bounds, f.ink, false), _ => { ctx.reset_paint_transform(); let (s, e) = @@ -61,7 +69,19 @@ pub(crate) fn set_paint(ctx: &mut RenderContext, p: &Paint, bounds: Rect, f: &Fr pub(crate) fn set_fill_paint(ctx: &mut RenderContext, p: &Paint, bounds: Rect, f: &Frame) -> bool { match p { Paint::Gradient(g) if g.gradient.dither && g.gradient.kind != GradientKind::Freeform && !g.gradient.stops.is_empty() => { - crate::dither::set_dithered_paint(ctx, g, bounds, f.ink) + crate::dither::set_dithered_paint(ctx, g, bounds, bounds, f.ink, true) + } + _ => set_paint(ctx, p, bounds, f), + } +} + +/// [`set_paint`] for a stroke whose outline (miters, caps and arrowheads included) fits the box +/// `area` gives: a diamond gradient, drawn as pixels, is sampled over that box too, so the parts +/// of the outline past `bounds` get the diamond's colors there. `area` runs only for a diamond. +pub(crate) fn set_stroke_paint(ctx: &mut RenderContext, p: &Paint, bounds: Rect, area: impl FnOnce() -> Rect, f: &Frame) -> bool { + match p { + Paint::Gradient(g) if g.gradient.kind == GradientKind::Diamond && !g.gradient.stops.is_empty() => { + crate::dither::set_dithered_paint(ctx, g, bounds, area(), f.ink, false) } _ => set_paint(ctx, p, bounds, f), } diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index a722c799e2..2372abdbf2 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -361,7 +361,8 @@ impl Renderer { let Some(pe) = &f.doc.pattern_edit else { return false }; let Some(layer) = f.doc.layers.iter().find(|l| l.id == pe.layer) else { return false }; let Some(def) = f.doc.pattern(&pe.pattern) else { return false }; - let children: Vec> = layer.children().cloned().unwrap_or_default(); + // The tile's art: the layer's ruler guides are not part of it. + let children: Vec> = layer.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).cloned().collect(); if layer.visible && !children.is_empty() { let dim = (def.dim_copies / 100.0).clamp(0.0, 1.0); let (before, after) = def.preview_offsets_dimmed_sides(); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 431e0aa97c..fc729c1cc3 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -19,7 +19,7 @@ use super::{ }; #[cfg(test)] -pub(crate) use paint::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; +pub(crate) use paint::{CONTROL_BOXES_MEASURED, SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; mod images; mod nodes; diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 9b59367deb..ca6611ea5f 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -596,6 +596,8 @@ impl Renderer { Some(a) => self.draw_live_body(ctx, f, &a, true), None => self.draw_live_node(ctx, f, n), }, + // The canvas draws ruler guides over the art; the renderer draws nothing for them. + NodeKind::RulerGuide { .. } => {} } } @@ -680,18 +682,20 @@ impl Renderer { self.draw_knockout(ctx, f, children); } else if let Some((_, path)) = self.isolation_path(f) { // Isolation mode, in a container on the way down to the isolated one: each run of - // members around it draws dimmed as one (#833). + // members around it draws dimmed as one (#833). A run of ruler guides alone draws + // nothing, so it gets no dimmed pass. + let draws = |run: &[Arc]| run.iter().any(|c| !c.is_ruler_guide()); let mut rest = children; while let Some(i) = rest.iter().position(|c| path.contains(&c.id)) { let (around, from) = rest.split_at(i); - if !around.is_empty() { + if draws(around) { self.dimmed(ctx, f, &mut |r, c, fr| around.iter().for_each(|n| r.draw_arc(c, fr, n))); } let Some((on_path, after)) = from.split_first() else { break }; self.draw_arc(ctx, f, on_path); rest = after; } - if !rest.is_empty() { + if draws(rest) { self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n))); } } else { diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index fd205496ae..2bf0d165db 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -22,7 +22,7 @@ impl Renderer { } pub(super) fn draw_shape(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, bp: &BezPath, rule: FillRule) { - if !drawable(bp, f.view, n) { + if !drawable(self.control_box(n, bp), f.view, n) { return; } if fx::has_fx(n) { @@ -73,6 +73,19 @@ impl Renderer { } } + /// The box of the control points of shape `bp` of `n`: kept with its path when `bp` is the + /// path kept for `n`'s id ([`crate::kept_paths::KeptPath::control_box`]), else measured. + fn control_box(&self, n: &Node, bp: &BezPath) -> Rect { + if let Some(k) = self.kept.get(&n.id) + && std::ptr::eq(Arc::as_ptr(&k.path), bp) + { + return k.control_box(); + } + #[cfg(test)] + CONTROL_BOXES_MEASURED.with(|c| c.set(c.get() + 1)); + bp.control_box() + } + /// Multiply the folded object opacity into a solid paint. pub(super) fn fold_alpha(&self, ctx: &mut RenderContext, ink: Ink, p: &vectorcraft_color::Paint) { if self.alpha < 1.0 @@ -131,15 +144,27 @@ impl Renderer { let paint_bounds = bounds.inflate(st.width / 2.0, st.width / 2.0); if let Some(g) = st.path_gradient() { self.fill_path_gradient(ctx, f, bp, rule, st, chars, &pieces, width, &g.gradient); - } 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, bp, &pieces.line, st, width) { - Some(o) => ctx.fill_path(&o), - 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); + } else { + let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { + Some(o) => o, + None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)), + }; + // Miters, caps and heads can reach past the paint box: a paint drawn as pixels covers + // them too. + let reach = || { + std::iter::once(&*line) + .chain(pieces.heads.iter().map(|h| &h.outline)) + .filter(|o| !o.elements().is_empty()) + .map(|o| o.bounding_box()) + .fold(paint_bounds, |r, b| r.union(b)) + }; + if paint::set_stroke_paint(ctx, &st.paint, paint_bounds, reach, f) { + self.fold_alpha(ctx, f.ink, &st.paint); + ctx.set_fill_rule(peniko::Fill::NonZero); + ctx.fill_path(&line); + for head in &pieces.heads { + ctx.fill_path(&head.outline); + } } } if inside { @@ -471,6 +496,9 @@ thread_local! { /// 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) }; + /// How many shapes' control boxes [`Renderer::draw_shape`] has measured from their path on this + /// thread. + pub(crate) static CONTROL_BOXES_MEASURED: 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. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index d5c129e5c1..83f6131071 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -5,6 +5,7 @@ use vectorcraft_geom::shapes; mod adjust; mod alternate; +mod arearesize; mod bitmapglyphs; mod blend; mod changed; diff --git a/crates/render/src/tests/arearesize.rs b/crates/render/src/tests/arearesize.rs new file mode 100644 index 0000000000..a53c05dc58 --- /dev/null +++ b/crates/render/src/tests/arearesize.rs @@ -0,0 +1,66 @@ +//! `Rendered::area_resized`: area averages of premultiplied pixels at any size, edge pixels by +//! their share, a copy at the same size, and errors instead of malformed images. + +use crate::*; + +fn image(width: u32, height: u32, pixels: &[[u8; 4]]) -> Rendered { + Rendered { width, height, pixels: pixels.concat() } +} + +#[test] +fn whole_blocks_average_into_one_pixel() { + let a = [200, 100, 0, 255]; + let b = [0, 100, 200, 255]; + let img = image(4, 2, &[a, b, a, a, a, b, a, b]); + let out = img.area_resized(2, 1).unwrap(); + assert_eq!((out.width, out.height), (2, 1)); + assert_eq!(out.pixels, [100, 100, 100, 255, 150, 100, 50, 255]); +} + +/// Three pixels into two: each new pixel takes one whole old pixel and half of the middle one. +#[test] +fn edge_pixels_count_by_the_share_they_cover() { + let img = image(3, 1, &[[0, 0, 0, 255], [255, 255, 255, 255], [90, 90, 90, 255]]); + let out = img.area_resized(2, 1).unwrap(); + // (0 + 255 / 2) / 1.5 = 85, (255 / 2 + 90) / 1.5 = 145. + assert_eq!(out.pixels, [85, 85, 85, 255, 145, 145, 145, 255]); +} + +/// A transparent pixel carries no color into its opaque neighbor: the average is half red, half +/// clear, still pure red once un-premultiplied. +#[test] +fn transparent_pixels_add_no_color() { + let img = image(2, 1, &[[0, 0, 0, 0], [255, 0, 0, 255]]); + let out = img.area_resized(1, 1).unwrap(); + assert_eq!(out.pixels, [128, 0, 0, 128]); + assert_eq!(out.to_straight(), [255, 0, 0, 128]); +} + +#[test] +fn the_same_size_is_a_copy() { + let px: Vec<[u8; 4]> = (0..12u8).map(|i| [i * 20, 255 - i * 20, i, 255]).collect(); + let img = image(4, 3, &px); + let out = img.area_resized(4, 3).unwrap(); + assert_eq!(out.pixels, img.pixels); +} + +/// A solid image stays exactly its color at any smaller size, with no rounding drift at +/// fractional spans. +#[test] +fn a_solid_color_stays_exact() { + let px = vec![[12, 34, 56, 255]; 1000 * 7]; + let out = image(1000, 7, &px).area_resized(128, 3).unwrap(); + assert_eq!((out.width, out.height), (128, 3)); + assert!(out.pixels.as_chunks::<4>().0.iter().all(|p| *p == [12, 34, 56, 255])); +} + +#[test] +fn bad_sizes_are_errors() { + let img = image(2, 2, &[[0, 0, 0, 255]; 4]); + assert!(img.area_resized(0, 1).is_err()); + assert!(img.area_resized(1, 0).is_err()); + let short = Rendered { width: 2, height: 2, pixels: vec![0; 12] }; + assert!(short.area_resized(1, 1).err().is_some_and(|e| e.contains("doesn't match"))); + let empty = Rendered { width: 0, height: 5, pixels: Vec::new() }; + assert!(empty.area_resized(1, 1).is_err()); +} diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 8f6d68f575..0e7864b0b9 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -338,7 +338,7 @@ fn enveloped_type_redraws_when_its_font_becomes_available() { let shown = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Word".into(), xf: Affine::translate((150.0, 120.0)) }); let l = d.layers[0].id; for (i, content) in [typed, shown].into_iter().enumerate() { - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let envelope = NodeKind::Envelope { content: vec![Arc::new(content)], kind: Box::new(kind), @@ -376,7 +376,7 @@ fn enveloped_type_under_effects_redraws_when_its_font_becomes_available() { let mut d = Document::new(300.0, 150.0); let style = CharStyle { size: 50.0, font_family: family.into(), ..Default::default() }; let typed = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 80.0), "Hamburg", style)))); - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let envelope = NodeKind::Envelope { content: vec![Arc::new(typed)], kind: Box::new(kind), @@ -420,7 +420,7 @@ fn a_renderer_maps_enveloped_type_from_its_glyphs_in_the_current_font() { const FAMILY: &str = "Mapped Serif 4"; let style = CharStyle { size: 50.0, font_family: FAMILY.into(), ..Default::default() }; let t = TextObject::point(Point::new(10.0, 60.0), "Hamburg", style); - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let envelope = Node::new( vectorcraft_doc::NodeId(1), NodeKind::Envelope { diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index a2f8b3ad85..e7097c4850 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -72,8 +72,8 @@ 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 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. + // twice the segments of a run, and the boxes and miter tips kept, run by run, and the control + // box 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"); @@ -83,6 +83,7 @@ fn check(r: &mut Renderer, d: &Document, id: NodeId, what: &str) { } let (runs, again, _) = k.runs(); assert!(runs == again, "{what}: the same boxes and tips as measured again"); + assert_eq!(k.control_box(), k.path.control_box(), "{what}: the same control box as measured again"); } /// Check `d` as [`check`] does, then the document before the edit (undone) and `d` again (redone). @@ -463,7 +464,7 @@ fn random_edit(g: &mut Seeded, p: &mut PathData) -> String { /// 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. +/// tips of `st` measured again over its runs, and the same bounds, tips and control box 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")); @@ -478,6 +479,7 @@ fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc, st: &S 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"); + assert_eq!(k.control_box(), fresh.path.control_box(), "{what}: the same control box"); } #[test] @@ -578,3 +580,27 @@ fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { check(&mut r, &d, id, "one anchor moved"); assert_eq!(kept(&r), before, "the kept path changed in place"); } + +#[test] +fn a_long_path_is_drawn_without_measuring_all_of_its_control_points_in_each_frame() { + 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 empty = { + let mut e = d.clone(); + Arc::make_mut(&mut e.layers[0]).children_mut().unwrap().clear(); + render(&mut Renderer::new(), &e).pixels + }; + let measured = || crate::renderer::CONTROL_BOXES_MEASURED.with(std::cell::Cell::get); + let before = measured(); + let mut r = Renderer::new(); + assert!(render(&mut r, &d).pixels != empty, "the path is drawn"); + render(&mut r, &d); + moved(&mut path_of(&mut d, id).subpaths[0].anchors[1500], Vec2::new(0.0, 40.0)); + check(&mut r, &d, id, "one anchor moved"); + assert_eq!(measured(), before, "drawn from the control box kept with its path"); + // An anchor far past what the rasterizer takes still leaves the path undrawn. + path_of(&mut d, id).subpaths[0].anchors[1500] = corner(12_000.0, 1e11); + assert!(render(&mut r, &d).pixels == empty, "an anchor 1e11 pt away: undrawn"); + assert_eq!(measured(), before, "drawn from the control box kept with its path"); +} diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index 8a6567f399..dc16e6430f 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -92,6 +92,11 @@ fn a_long_profile_stroke_keeps_its_widths_when_outlined_near_the_view() { 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); + // The cropped outline fits cubics through the same samples, but its fit starts at the + // crop rather than at the subpath's end, so a cubic may put its control points + // differently (the same curve). The rasteriser then flattens it into a slightly + // different polygon, which shows as one level on an anti-aliased edge pixel. Anything + // more would be a wrong width. let mismatched: Vec<_> = near .pixels .as_chunks::<4>() @@ -99,7 +104,7 @@ fn a_long_profile_stroke_keeps_its_widths_when_outlined_near_the_view() { .iter() .zip(full.pixels.as_chunks::<4>().0.iter()) .enumerate() - .filter(|(_, (a, b))| a != b) + .filter(|(_, (a, b))| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 1)) .take(8) .map(|(i, (a, b))| (i % SIZE as usize, i / SIZE as usize, a.to_vec(), b.to_vec())) .collect(); diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index d5e6919f0d..f95735baec 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -1252,7 +1252,7 @@ fn art_with_live_objects_draws_pattern_layout_edits() { d.patterns.push(def); let band = vectorcraft_geom::shapes::rectangle(Rect::new(-80.0, -40.0, 80.0, 40.0)); let filled = Node::path(d.alloc_id(), band, vectorcraft_doc::Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0)); - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let options = EnvelopeOptions { distort_appearance: true, distort_pattern_fills: true, ..Default::default() }; let envelope = Node::new( d.alloc_id(), @@ -1398,7 +1398,7 @@ fn live_objects_in_symbol_art_draw_symbol_and_pattern_edits() { /// An envelope of `d` bending `content` with an arc warp (30%); with `patterns`, Distort /// Appearance and Distort Pattern Fills are on, and the tiles of its pattern fills bend with it. fn arc_envelope(d: &mut Document, content: Vec, patterns: bool) -> Node { - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let options = vectorcraft_doc::live::EnvelopeOptions { distort_appearance: patterns, distort_pattern_fills: patterns, ..Default::default() }; let content = content.into_iter().map(Arc::new).collect(); Node::new( diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index fe1e5ee1d1..7e4007c6ac 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -439,7 +439,7 @@ fn transforms_of(t: &Node) -> [(Value, Affine); 3] { /// A 100×100 document holding `content` in an envelope that leaves it as it is (an arc with no /// bend), with Distort Appearance on or off. fn envelope_doc(content: Node, distort_appearance: bool) -> Document { - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let options = vectorcraft_doc::live::EnvelopeOptions { distort_appearance, ..Default::default() }; let envelope = NodeKind::Envelope { content: vec![Arc::new(content)], diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index c3c00a4cf0..3a65b1abe0 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -135,7 +135,7 @@ fn an_enveloped_placed_document_shows_its_file_once_read() { let placed = d.remove(NodeId(50)).unwrap(); let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("a placed document") }; let p = (**p).clone(); - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let envelope = NodeKind::Envelope { content: vec![placed], kind: Box::new(kind), diff --git a/crates/render/tests/it/conic.rs b/crates/render/tests/it/conic.rs new file mode 100644 index 0000000000..300a754d53 --- /dev/null +++ b/crates/render/tests/it/conic.rs @@ -0,0 +1,117 @@ +//! Conic gradients: the pixels sweep clockwise around the center from the vector, with a hard seam +//! where the last stop meets the first, and follow the model's parameter when the extent ellipse +//! is squashed, turned or mirrored, or holds numbers out of range. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, Document}; +use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_testkit::fixtures::DocBuilder; +use vectorcraft_testkit::raster::{Image, render_view}; + +/// A 100 pt square filled with `gradient` placed on `geom`. +fn square(gradient: Gradient, geom: GradientGeom) -> Document { + let mut gp = GradientPaint::new(gradient); + gp.geom = Some(geom); + let mut b = DocBuilder::new(100.0, 100.0); + b.path(shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0), |_| {}); + b.build() +} + +/// A white-to-black conic on `geom`. +fn conic(geom: GradientGeom) -> Document { + square(Gradient { kind: GradientKind::Conic, ..Gradient::default() }, geom) +} + +/// Centered on the square, the sweep starting at `deg` (counterclockwise from the right). +fn at(deg: f64) -> GradientGeom { + GradientGeom::fit(GradientKind::Conic, Rect::new(0.0, 0.0, 100.0, 100.0), deg) +} + +/// Every 7th pixel away from the center and the seam has the white-to-black ramp's gray at the +/// model's parameter there (pixel centers). +fn assert_follows_model(img: &Image, geom: &GradientGeom) { + for y in (3..100).step_by(7) { + for x in (3..100).step_by(7) { + let p = Point::new(x as f64 + 0.5, y as f64 + 0.5); + let t = geom.param_at(GradientKind::Conic, p); + if p.distance(geom.start) < 6.0 || !(0.02..0.98).contains(&t) { + continue; + } + let want = ((1.0 - t) * 255.0).round() as u8; + let got = img.over_white(x, y)[0]; + assert!(got.abs_diff(want) <= 6, "({x},{y}) t={t:.3}: got {got}, want {want}"); + } + } +} + +#[test] +fn the_sweep_runs_clockwise_from_the_vector() { + for deg in [0.0, 90.0, 180.0, 270.0, 33.0] { + let geom = at(deg); + let img = render_view(&conic(geom), 100, 100); + assert_follows_model(&img, &geom); + } + // From a vector pointing right: a quarter turn on (below the center) is three quarters white, + // three quarters on (above it) a quarter white. + let img = render_view(&conic(at(0.0)), 100, 100); + assert!(img.over_white(50, 80)[0].abs_diff(191) <= 6, "{:?}", img.over_white(50, 80)); + assert!(img.over_white(50, 20)[0].abs_diff(64) <= 6, "{:?}", img.over_white(50, 20)); +} + +#[test] +fn the_seam_is_hard_where_the_last_stop_meets_the_first() { + let img = render_view(&conic(at(0.0)), 100, 100); + // Along the vector (right of the center): white just below it, black just above it. + for x in [70, 80, 95] { + assert!(img.over_white(x, 52)[0] > 235, "x {x} below: {:?}", img.over_white(x, 52)); + assert!(img.over_white(x, 47)[0] < 20, "x {x} above: {:?}", img.over_white(x, 47)); + } + // Left of the center the ramp runs on smoothly. + for x in [5, 20, 30] { + assert!(img.over_white(x, 47)[0].abs_diff(img.over_white(x, 52)[0]) < 20, "x {x}"); + } +} + +#[test] +fn a_squashed_turned_or_mirrored_extent_renders_as_its_model() { + let squashed = GradientGeom { start: Point::new(45.0, 55.0), end: Point::new(75.0, 70.0), aspect: 0.4, focal: None }; + assert_follows_model(&render_view(&conic(squashed), 100, 100), &squashed); + // A negative aspect turns the sweep counterclockwise: a quarter turn on is above the center. + let mirrored = GradientGeom { aspect: -1.0, ..at(0.0) }; + let img = render_view(&conic(mirrored), 100, 100); + assert_follows_model(&img, &mirrored); + assert!(img.over_white(50, 20)[0].abs_diff(191) <= 6, "{:?}", img.over_white(50, 20)); +} + +#[test] +fn stop_colors_and_opacity_follow_the_ramp() { + let mut clear_blue = GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)); + clear_blue.opacity = 0.0; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), clear_blue]; + let img = render_view(&square(Gradient::new(GradientKind::Conic, stops), at(0.0)), 100, 100); + // Just past the start: opaque red. Just before the seam: nearly clear, the paper showing. + let start = img.over_white(90, 52); + assert!(start[0] > 235 && start[1] < 30 && start[2] < 30, "{start:?}"); + assert!(img.over_white(90, 47).iter().all(|&c| c > 200), "{:?}", img.over_white(90, 47)); +} + +/// A conic whose extent a file left without length, flat or out of range draws as the model +/// samples it: a sweep about its start from its vector's direction, or from the right when the +/// vector has no length. +#[test] +fn a_conic_without_an_extent_sweeps_from_its_vector() { + let c = Point::new(50.0, 50.0); + for geom in [ + GradientGeom { start: c, end: c, aspect: 1.0, focal: None }, + GradientGeom { start: c, end: Point::new(80.0, 20.0), aspect: 0.0, focal: None }, + GradientGeom { start: c, end: Point::new(80.0, 20.0), aspect: f64::NAN, focal: None }, + GradientGeom { start: c, end: Point::new(80.0, 20.0), aspect: f64::INFINITY, focal: None }, + GradientGeom { start: c, end: c, aspect: -1.0, focal: None }, + ] { + let img = render_view(&conic(geom), 100, 100); + assert_follows_model(&img, &geom); + } + // Without a vector, from the right: a quarter turn on is below the center. + let img = render_view(&conic(GradientGeom { start: c, end: c, aspect: 1.0, focal: None }), 100, 100); + assert!(img.over_white(50, 80)[0].abs_diff(191) <= 6, "{:?}", img.over_white(50, 80)); +} diff --git a/crates/render/tests/it/diamond.rs b/crates/render/tests/it/diamond.rs new file mode 100644 index 0000000000..e3092f45c3 --- /dev/null +++ b/crates/render/tests/it/diamond.rs @@ -0,0 +1,117 @@ +//! Diamond gradients: the pixels run from the center out to a square with a corner at the end of +//! the vector, and follow the model's parameter when the square is stretched or turned, on fills +//! and strokes; a stroke gets no dither noise, and a diamond without an extent draws its last stop. + +use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; +use vectorcraft_doc::{Appearance, Document}; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_testkit::fixtures::DocBuilder; +use vectorcraft_testkit::raster::{Image, render_view}; + +/// A white-to-black diamond on `geom`, dithered when `dither`. +fn paint(geom: GradientGeom, dither: bool) -> Paint { + let mut gp = GradientPaint::new(Gradient { kind: GradientKind::Diamond, dither, ..Gradient::default() }); + gp.geom = Some(geom); + Paint::Gradient(Box::new(gp)) +} + +/// A 100 pt square filled with `fill` and stroked `width` wide with `stroke`. +fn square(fill: Paint, stroke: Paint, width: f64) -> Document { + let mut b = DocBuilder::new(100.0, 100.0); + b.path(shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 90.0)), Appearance::basic(fill, stroke, width), |_| {}); + b.build() +} + +/// Every 7th pixel inside `inside` has the white-to-black ramp's gray at the model's parameter +/// there (pixel centers). +fn assert_follows_model(img: &Image, geom: &GradientGeom, inside: Rect) { + for y in (3..100).step_by(7) { + for x in (3..100).step_by(7) { + let p = Point::new(x as f64 + 0.5, y as f64 + 0.5); + if !inside.contains(p) { + continue; + } + let t = geom.param_at(GradientKind::Diamond, p).clamp(0.0, 1.0); + let want = ((1.0 - t) * 255.0).round() as u8; + let got = img.over_white(x, y)[0]; + assert!(got.abs_diff(want) <= 6, "({x},{y}) t={t:.3}: got {got}, want {want}"); + } + } +} + +#[test] +fn a_diamond_fill_follows_the_squares() { + let c = Point::new(50.0, 50.0); + let level = GradientGeom { start: c, end: c + Vec2::new(40.0, 0.0), aspect: 1.0, focal: None }; + let stretched = GradientGeom { aspect: 0.5, ..level }; + let turned = GradientGeom { end: c + Vec2::new(30.0, 30.0), aspect: 0.7, ..level }; + for geom in [level, stretched, turned] { + let img = render_view(&square(paint(geom, false), Paint::None, 0.0), 100, 100); + assert_follows_model(&img, &geom, Rect::new(12.0, 12.0, 88.0, 88.0)); + } + // Level: white at the center, mid gray halfway to a corner of the square, along an axis and + // along a diagonal alike (pixel centers 20 pt from the center, counted along the axes). + let img = render_view(&square(paint(level, false), Paint::None, 0.0), 100, 100); + assert!(img.over_white(50, 50)[0] > 240, "{:?}", img.over_white(50, 50)); + for (x, y) in [(69, 49), (49, 69), (60, 59), (39, 40)] { + assert!(img.over_white(x, y)[0].abs_diff(128) <= 6, "({x},{y}): {:?}", img.over_white(x, y)); + } +} + +/// A stroke follows the squares too, without the noise dither puts on fills. +#[test] +fn a_diamond_stroke_follows_the_squares_without_dither() { + let c = Point::new(50.0, 50.0); + let geom = GradientGeom { start: c, end: c + Vec2::new(60.0, 0.0), aspect: 1.0, focal: None }; + let doc = square(Paint::None, paint(geom, true), 6.0); + let img = render_view(&doc, 100, 100); + // Along the top edge (y 10, inside the stroke's inner half), the gray follows the model and + // two pixels the same distance from the center are the same. + for x in [20, 35, 50, 65, 80] { + let p = Point::new(x as f64 + 0.5, 10.5); + let want = ((1.0 - geom.param_at(GradientKind::Diamond, p).clamp(0.0, 1.0)) * 255.0).round() as u8; + assert!(img.over_white(x, 10)[0].abs_diff(want) <= 6, "x {x}: {:?} vs {want}", img.over_white(x, 10)); + } + assert_eq!(img.over_white(30, 10), img.over_white(69, 10)); +} + +/// A stroke's miter reaches past its paint box (the path's box grown by half the weight): the +/// diamond's grays run on there, as the model gives them, instead of repeating the box's edge. +#[test] +fn a_diamond_stroke_follows_the_squares_past_its_paint_box() { + let c = Point::new(50.0, 50.0); + let geom = GradientGeom { start: c, end: c + Vec2::new(45.0, 0.0), aspect: 1.0, focal: None }; + let mut ap = Appearance::basic(Paint::None, paint(geom, false), 8.0); + for it in &mut ap.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = it { + s.miter_limit = 10.0; + } + } + let mut b = DocBuilder::new(100.0, 100.0); + let peak = vectorcraft_geom::SubPath::polyline(&[Point::new(20.0, 80.0), Point::new(50.0, 20.0), Point::new(80.0, 80.0)], false); + b.path(vectorcraft_geom::PathData::single(peak), ap, |_| {}); + let img = render_view(&b.build(), 100, 100); + // The miter's tip runs up to y 11.06; the paint box starts at y 16. Rows 13 and 14 are + // covered across pixel column 50. + for y in [13, 14] { + let p = Point::new(50.5, y as f64 + 0.5); + let want = ((1.0 - geom.param_at(GradientKind::Diamond, p).clamp(0.0, 1.0)) * 255.0).round() as u8; + assert!(img.over_white(50, y)[0].abs_diff(want) <= 6, "y {y}: {:?} vs {want}", img.over_white(50, y)); + } +} + +/// Without an extent (no vector, or a flat square) every point is past the square: the last stop. +#[test] +fn a_diamond_without_an_extent_draws_its_last_stop() { + let c = Point::new(50.0, 50.0); + for geom in [ + GradientGeom { start: c, end: c, aspect: 1.0, focal: None }, + GradientGeom { start: c, end: c + Vec2::new(30.0, 0.0), aspect: 0.0, focal: None }, + GradientGeom { start: c, end: c + Vec2::new(f64::INFINITY, 0.0), aspect: 1.0, focal: None }, + ] { + let img = render_view(&square(paint(geom, false), Paint::None, 0.0), 100, 100); + for (x, y) in [(50, 50), (20, 80), (85, 15)] { + assert!(img.over_white(x, y)[0] < 6, "{geom:?} ({x},{y}): {:?}", img.over_white(x, y)); + } + } +} diff --git a/crates/render/tests/it/main.rs b/crates/render/tests/it/main.rs index 67afd69936..9a9e059fba 100644 --- a/crates/render/tests/it/main.rs +++ b/crates/render/tests/it/main.rs @@ -2,7 +2,9 @@ // Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod conic; mod dash_align; +mod diamond; mod golden; mod gradient_alpha; mod gradient_text; diff --git a/crates/scriptcheck/Cargo.toml b/crates/scriptcheck/Cargo.toml index d0101be96a..35df44d84c 100644 --- a/crates/scriptcheck/Cargo.toml +++ b/crates/scriptcheck/Cargo.toml @@ -9,5 +9,10 @@ rust-version.workspace = true [lints] workspace = true +[dependencies] +# Unicode 17.0 general categories for names (lex.rs). 0.1.5 adds the Unicode-3.0 license, which is +# not on the license allowlist, so the version is exact. +unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] } + [dev-dependencies] proptest = { workspace = true } diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 1e5b21fc2b..b8f887ff37 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -88,12 +88,25 @@ pub(crate) struct Scan { /// Scan `src` (already through [`unescaped`]): the script itself (`file` none) or a file it includes /// (`file`: its path inside the script's folder), with the names it declares (`declared`, from /// [`declarations`] on the same `src`), the `#includepath` folders `paths` in force at its start and -/// its variables holding what `known` says. -pub(crate) fn scan<'s>(src: &'s str, declared: &Declared<'s>, file: Option<&str>, paths: Rc<[String]>, known: &Known, acc: &mut Acc) -> Scan { +/// its variables holding what `known` says. Each of the `\u{…}` escapes `braced` that [`unescaped`] +/// read is syntax later than ECMAScript 3, reported when the scan reaches the escape's line. +pub(crate) fn scan<'s>( + src: &'s str, + declared: &Declared<'s>, + braced: &[Braced], + file: Option<&str>, + paths: Rc<[String]>, + known: &Known, + acc: &mut Acc, +) -> Scan { let mut lexer = Lexer::new(src, acc.limits.nesting); let mut a = Analyzer::new(acc, file, paths, known, declared); let mut breaks = LineBreaks::default(); + let mut braced = braced.iter().peekable(); for t in lexer.by_ref() { + while let Some((line, escape)) = braced.next_if(|(line, _)| *line <= t.line) { + a.acc.problem(report::NEWER_SYNTAX, Some(*line), file, Some(escape)); + } if let Some(code) = t.problem { a.problem(code, t.line); } @@ -103,6 +116,9 @@ pub(crate) fn scan<'s>(src: &'s str, declared: &Declared<'s>, file: Option<&str> Read::Token(sig) => a.token(sig), } } + for (line, escape) in braced { + a.acc.problem(report::NEWER_SYNTAX, Some(*line), file, Some(escape)); + } if let Some(line) = lexer.unclosed_xml { a.problem(report::UNTERMINATED_XML, line); } @@ -115,28 +131,61 @@ pub(crate) fn scan<'s>(src: &'s str, declared: &Declared<'s>, file: Option<&str> Scan { includes, module, lines: lexer.lines(), known } } -/// `src` with the `\uXXXX` escapes in its names written as the characters they stand for (ECMA-262 -/// 3rd edition, section 7.6), and `src` itself when no name has one. An escape for a character no -/// name may hold stays as written. Line breaks don't change, so every line keeps its number. -pub(crate) fn unescaped<'a>(src: Cow<'a, str>, acc: &mut Acc) -> Cow<'a, str> { - match unescape_names(&src, acc) { - Some(out) => Cow::Owned(out), - None => src, +/// A `\u{…}` escape in a name, which ECMAScript 3 does not have: its line and its text. +pub(crate) type Braced = (usize, String); + +/// `src` with the `\uXXXX` and `\u{…}` escapes in its names and private names written as the +/// characters they stand for (ECMA-262, Names and Keywords), and `src` itself when no name has one, +/// with the `\u{…}` escapes read, each listed once per line in a row. An escape for a character a +/// name may not hold where the escape stands stays as written, and so does a private name that +/// starts a line where the name it spells would start a preprocessor line. Line breaks don't +/// change, so every line keeps its number. +pub(crate) fn unescaped<'a>(src: Cow<'a, str>, acc: &mut Acc) -> (Cow<'a, str>, Vec) { + let mut braced = vec![]; + match unescape_names(&src, acc, &mut braced) { + Some(out) => (Cow::Owned(out), braced), + None => (src, braced), } } -fn unescape_names(src: &str, acc: &mut Acc) -> Option { +fn unescape_names(src: &str, acc: &mut Acc, braced: &mut Vec) -> Option { if !src.contains("\\u") { return None; } let mut out = String::with_capacity(src.len()); let mut changed = false; let mut lexer = Lexer::new(src, acc.limits.nesting); - for t in lexer.by_ref() { - if t.kind == T::Ident && t.text.contains("\\u") { - let name = unescape_name(t.text); - changed |= name != t.text; - out.push_str(&name); + // One more than the report keeps, so that the report is marked truncated. + let room = acc.limits.entries.saturating_add(1); + // Only blanks since the last line break (or the start). + let mut line_start = true; + let mut found = vec![]; + while let Some(t) = lexer.next() { + // A private name is `#` and a name. + let (mark, name) = match t.kind { + T::Ident => ("", t.text), + T::Other => t.text.strip_prefix('#').map_or(("", ""), |name| ("#", name)), + _ => ("", ""), + }; + let starts_line = line_start; + line_start = t.kind == T::Newline || (line_start && t.kind == T::Space); + if name.contains("\\u") { + found.clear(); + let written = unescape_name(name, t.line, &mut found, room); + for escape in found.drain(..) { + if braced.last() != Some(&escape) && braced.len() < room { + braced.push(escape); + } + } + // A private name that starts a line stays as written where the name it spells would + // start a preprocessor line. + if mark == "#" && starts_line && !lexer.private_line(&written) { + out.push_str(t.text); + continue; + } + changed |= written != name; + out.push_str(mark); + out.push_str(&written); } else { out.push_str(t.text); } @@ -145,28 +194,31 @@ fn unescape_names(src: &str, acc: &mut Acc) -> Option { changed.then_some(out) } -/// The name `text` with each `\uXXXX` escape for a character a name may hold written as that -/// character. -fn unescape_name(text: &str) -> String { +/// The name `text`, on `line`, with each escape for a character a name may hold where it stands +/// written as that character: a character a name may start with first, and one a name may hold +/// after that. Each `\u{…}` escape read goes into `braced`, unless the last one there is the same +/// escape on the same line or `braced` holds `room` of them. +fn unescape_name(text: &str, line: usize, braced: &mut Vec, room: usize) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; while let Some(i) = rest.find("\\u") { out.push_str(rest.get(..i).unwrap_or_default()); - let after = rest.get(i + 2..).unwrap_or_default(); - let c = after - .get(..4) - .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit())) - .and_then(|hex| u32::from_str_radix(hex, 16).ok()) - .and_then(char::from_u32) - .filter(|&c| crate::lex::ident_part(c)); + let at = rest.get(i..).unwrap_or_default(); + let first = out.is_empty(); + let c = crate::lex::escape(at).filter(|&(c, _)| if first { crate::lex::ident_start(c) } else { crate::lex::ident_part(c) }); match c { - Some(c) => { + Some((c, len)) => { out.push(c); - rest = after.get(4..).unwrap_or_default(); + let source = at.get(..len).unwrap_or_default(); + let repeated = braced.last().is_some_and(|(l, s)| *l == line && s == source); + if source.starts_with("\\u{") && !repeated && braced.len() < room { + braced.push((line, source.to_string())); + } + rest = at.get(len..).unwrap_or_default(); } None => { out.push_str("\\u"); - rest = after; + rest = at.get(2..).unwrap_or_default(); } } } diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 7ee71c9eea..8954736d25 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -152,7 +152,7 @@ features! { DirectiveInclude "directive.include" Language, DirectiveOther "directive.other" Language, DirectiveTarget "directive.target" Language, - DirectiveTargetengine "directive.targetengine" HostOnly, + DirectiveTargetengine "directive.targetengine" Language, Dollar "dollar" Language, DollarEnv "dollar.env" Files, DollarEvalFile "dollar.evalFile" Files, diff --git a/crates/scriptcheck/src/includes.rs b/crates/scriptcheck/src/includes.rs index f6e9c82b09..b4a7be7219 100644 --- a/crates/scriptcheck/src/includes.rs +++ b/crates/scriptcheck/src/includes.rs @@ -141,9 +141,9 @@ pub(crate) fn follow( read.insert(path.clone(), (status, Some(file))); let (text, _) = crate::decode(&b); let mut tallies = Acc::new(limits); - let text = analyze::unescaped(text, &mut tallies); + let (text, _) = analyze::unescaped(text, &mut tallies); let declared = analyze::declarations(&text, &mut tallies); - let scan = analyze::scan(&text, &declared, Some(&path), Rc::clone(&inc.paths), known, &mut tallies); + let scan = analyze::scan(&text, &declared, &[], Some(&path), Rc::clone(&inc.paths), known, &mut tallies); acc.steps = acc.steps.saturating_add(tallies.steps); known.add(scan.known, limits.entries); checked.push(ReadFile { path: path.clone(), bytes: b, paths: Rc::clone(&inc.paths) }); diff --git a/crates/scriptcheck/src/lex.rs b/crates/scriptcheck/src/lex.rs index be66dd4b1d..a9a805d87c 100644 --- a/crates/scriptcheck/src/lex.rs +++ b/crates/scriptcheck/src/lex.rs @@ -8,6 +8,10 @@ //! level and the levels of XML literals and their code are kept on stacks capped at the nesting //! limit. +use std::cmp::Ordering; + +use unicode_properties::{GeneralCategory as G, UnicodeGeneralCategory}; + use crate::catalog; use crate::report::{TOO_DEEP, UNTERMINATED_COMMENT, UNTERMINATED_REGEXP, UNTERMINATED_STRING, UNTERMINATED_TEMPLATE}; @@ -37,7 +41,9 @@ pub(crate) enum T { /// end or the next `{`. XmlMore, Punct, - /// A character no token starts with, or `#` and a name away from the start of a line. + /// A character no token starts with, or a private name: `#` and a name away from the start of a + /// line, or at its start where the name starts with an escape, or inside braces where the name + /// is not a directive's. Other, } @@ -130,13 +136,121 @@ fn is_blank(c: char) -> bool { !is_break(c) && (c.is_whitespace() || c == '\u{feff}') } -fn ident_start(c: char) -> bool { - c == '$' || c == '_' || c.is_ascii_alphabetic() || (!c.is_ascii() && c.is_alphabetic()) +/// A character a name may start with: a Unicode `ID_Start` character, `$` or `_` (the Names and +/// Keywords clause of current ECMA-262 editions). `ID_Start` is the letters (categories Lu, Ll, Lt, +/// Lm, Lo and Nl) and `Other_ID_Start`, less `Pattern_Syntax` and `Pattern_White_Space` (Unicode +/// Standard Annex #31). The categories come from Unicode 17.0. +pub(crate) fn ident_start(c: char) -> bool { + match c { + '$' | '_' => true, + _ if c.is_ascii() => c.is_ascii_alphabetic(), + _ if is_other_id_start(c) => true, + _ => { + matches!( + c.general_category(), + G::UppercaseLetter | G::LowercaseLetter | G::TitlecaseLetter | G::ModifierLetter | G::OtherLetter | G::LetterNumber + ) && !is_pattern_syntax(c) + } + } } -/// A character a name may hold after its first. +/// A character a name may hold after its first: a Unicode `ID_Continue` character or `$`. +/// `ID_Continue` adds to `ID_Start` the decimal digits (Nd), combining marks (Mn, Mc), connector +/// punctuation (Pc, which holds `_`) and `Other_ID_Continue` (which holds the zero width non-joiner +/// and joiner), less `Pattern_Syntax` and `Pattern_White_Space`. pub(crate) fn ident_part(c: char) -> bool { - ident_start(c) || c.is_ascii_digit() || (!c.is_ascii() && c.is_alphanumeric()) + match c { + '0'..='9' => true, + _ if ident_start(c) => true, + _ if c.is_ascii() => false, + _ if is_other_id_continue(c) => true, + _ => matches!(c.general_category(), G::NonspacingMark | G::SpacingMark | G::DecimalNumber | G::ConnectorPunctuation) && !is_pattern_syntax(c), + } +} + +/// The character the escape at the start of `s` stands for and the escape's length in bytes: `\u` +/// and four hexadecimal digits, or `\u{…}` with one or more hexadecimal digits of a value up to +/// U+10FFFF, leading zeros allowed (ECMA-262, UnicodeEscapeSequence and CodePoint). `None` when `s` +/// starts with neither, or when the escape gives a lone surrogate. +pub(crate) fn escape(s: &str) -> Option<(char, usize)> { + let rest = s.strip_prefix("\\u")?; + let Some(braced) = rest.strip_prefix('{') else { + let c = rest + .get(..4) + .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit())) + .and_then(|hex| u32::from_str_radix(hex, 16).ok()) + .and_then(char::from_u32)?; + return Some((c, 6)); + }; + // The value stops growing past U+10FFFF, so any number of digits is read once and never + // overflows. + let mut value: u32 = 0; + for (i, b) in braced.bytes().enumerate() { + match b { + b'}' if i > 0 => return char::from_u32(value).map(|c| (c, i + 4)), + _ => { + let digit = char::from(b).to_digit(16)?; + value = (value * 16 + digit).min(0x11_0000); + } + } + } + None +} + +/// `Other_ID_Start` (Unicode PropList 17.0): characters kept in `ID_Start` though their category is +/// not a letter. +fn is_other_id_start(c: char) -> bool { + matches!(c, '\u{1885}' | '\u{1886}' | '\u{2118}' | '\u{212E}' | '\u{309B}' | '\u{309C}') +} + +/// `Other_ID_Continue` (Unicode PropList 17.0): characters kept in `ID_Continue` though their +/// category is not a letter, mark, digit or connector. +fn is_other_id_continue(c: char) -> bool { + matches!(c, '\u{B7}' | '\u{387}' | '\u{1369}'..='\u{1371}' | '\u{19DA}' | '\u{200C}' | '\u{200D}' | '\u{30FB}' | '\u{FF65}') +} + +/// Non-ASCII `Pattern_Syntax` ranges (Unicode PropList). Unicode does not change this set, and no +/// identifier character belongs to it. `Pattern_White_Space` outside ASCII (U+0085, U+200E, U+200F, +/// U+2028 and U+2029) holds no letter, mark, digit or connector, so the category checks leave it out. +const PATTERN_SYNTAX: [(char, char); 23] = [ + ('\u{A1}', '\u{A7}'), + ('\u{A9}', '\u{A9}'), + ('\u{AB}', '\u{AC}'), + ('\u{AE}', '\u{AE}'), + ('\u{B0}', '\u{B1}'), + ('\u{B6}', '\u{B6}'), + ('\u{BB}', '\u{BB}'), + ('\u{BF}', '\u{BF}'), + ('\u{D7}', '\u{D7}'), + ('\u{F7}', '\u{F7}'), + ('\u{2010}', '\u{2027}'), + ('\u{2030}', '\u{203E}'), + ('\u{2041}', '\u{2053}'), + ('\u{2055}', '\u{205E}'), + ('\u{2190}', '\u{245F}'), + ('\u{2500}', '\u{2775}'), + ('\u{2794}', '\u{2BFF}'), + ('\u{2E00}', '\u{2E7F}'), + ('\u{3001}', '\u{3003}'), + ('\u{3008}', '\u{3020}'), + ('\u{3030}', '\u{3030}'), + ('\u{FD3E}', '\u{FD3F}'), + ('\u{FE45}', '\u{FE46}'), +]; + +/// Whether a non-ASCII character is `Pattern_Syntax`. +fn is_pattern_syntax(c: char) -> bool { + PATTERN_SYNTAX + .binary_search_by(|&(lo, hi)| { + if hi < c { + Ordering::Less + } else if lo > c { + Ordering::Greater + } else { + Ordering::Equal + } + }) + .is_ok() } /// After `<`, the start of an XML literal: a name, `>` (a list), `!` (a comment or CDATA), `?` (a @@ -300,26 +414,67 @@ impl<'s> Lexer<'s> { } } - /// The rest of a name (its first character included): letters, digits, `$`, `_` and `\u` - /// escapes. + /// The rest of a name (its first character included): the characters [`ident_part`] allows, + /// written out or as `\uXXXX` or `\u{…}` escapes ([`escape`]). An escape for any other + /// character, or a malformed one, ends the name. Each character of an escape is a step. fn name(&mut self) { loop { match self.peek() { - Some('\\') if self.peek_at(1) == Some('u') => { - self.skip(2); - for _ in 0..4 { - match self.peek() { - Some(h) if h.is_ascii_hexdigit() => self.bump(h), - _ => break, - } + Some('\\') => match escape(self.rest()) { + Some((c, len)) if ident_part(c) => { + self.pos += len; + self.steps += len; } - } + _ => break, + }, Some(c) if ident_part(c) => self.bump(c), _ => break, } } } + /// A name starts right after the `#` here: its first character written out, or an escape for a + /// character a name may start with. + fn private_name_follows(&self) -> bool { + let after = self.rest().get(1..).unwrap_or_default(); + match after.chars().next() { + Some('\\') => escape(after).is_some_and(|(c, _)| ident_start(c)), + Some(c) => ident_start(c), + None => false, + } + } + + /// The `#` at the start of this line starts a private name, not a preprocessor line: the name + /// starts with an escape, which no directive's name holds, or [`Lexer::private_line`] holds for + /// it. + fn private_at_line_start(&self) -> bool { + if !self.private_name_follows() { + return false; + } + let after = self.rest().get(1..).unwrap_or_default(); + after.starts_with('\\') || self.private_line(after) + } + + /// A line that starts with `#` and then `rest` is a private name here, not a preprocessor line: + /// the line is inside braces or in the code of an XML literal, and the name `rest` starts with + /// is not a directive's. The name runs over every character a name may hold, written out or as + /// an escape, so `#include$size` is not `#include`. + pub fn private_line(&self, rest: &str) -> bool { + let in_code = !self.braces.is_empty() || self.deeper_braces > 0 || !self.xml.is_empty(); + let mut end = 0; + while let Some(more) = rest.get(end..) { + let len = match more.chars().next() { + Some('\\') => escape(more).filter(|&(c, _)| ident_part(c)).map(|(_, len)| len), + Some(c) if ident_part(c) => Some(c.len_utf8()), + _ => None, + }; + let Some(len) = len else { break }; + end += len; + } + let name = rest.get(..end).unwrap_or_default(); + in_code && !catalog::DIRECTIVES.iter().any(|d| d.eq_ignore_ascii_case(name)) + } + fn digits(&mut self, ok: fn(char) -> bool) { while let Some(c) = self.peek().filter(|&c| ok(c) || c == '_') { self.bump(c); @@ -785,10 +940,10 @@ impl<'s> Iterator for Lexer<'s> { } else if self.starts("/*") { problem = self.block_comment(); T::Comment - } else if c == '#' && self.line_start { + } else if c == '#' && self.line_start && !self.private_at_line_start() { self.until_line_break(); T::Directive - } else if c == '#' && self.peek_at(1).is_some_and(ident_start) { + } else if c == '#' && self.private_name_follows() { self.bump('#'); self.name(); T::Other @@ -820,7 +975,7 @@ impl<'s> Iterator for Lexer<'s> { self.close_level(); self.bump('}'); return Some(self.markup_token(start, line, T::XmlMore, stmt, expr)); - } else if ident_start(c) || (c == '\\' && self.peek_at(1) == Some('u')) { + } else if ident_start(c) || (c == '\\' && escape(self.rest()).is_some_and(|(c, _)| ident_start(c))) { self.name(); T::Ident } else if c.is_ascii_digit() || (c == '.' && self.peek_at(1).is_some_and(|d| d.is_ascii_digit())) { diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 0c62419f1c..2bd8c60fba 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -166,14 +166,14 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits: if invalid { acc.problem(report::NOT_UTF8, None, None, None); } - let text = analyze::unescaped(text, &mut acc); + let (text, braced) = analyze::unescaped(text, &mut acc); let declared = analyze::declarations(&text, &mut acc); let none = analyze::Known::default(); // With a loader, this first scan finds the includes and what the script's variables hold; its // tallies are left out. let mut tallies = report::Acc::new(limits); let pre = acc.clone(); - let scan = analyze::scan(&text, &declared, None, std::rc::Rc::from([]), &none, if loader.is_some() { &mut tallies } else { &mut acc }); + let scan = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &none, if loader.is_some() { &mut tallies } else { &mut acc }); acc.steps = acc.steps.saturating_add(tallies.steps); if scan.module { // A module's report holds its kind and its lines, and none of what the scan found. @@ -183,7 +183,7 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits: return acc.finish(Kind::Module, scan.lines); } let Some(loader) = loader else { - let mut acc = settle(acc, pre, &text, &declared, scan.known); + let mut acc = settle(acc, pre, &text, &declared, &braced, scan.known); includes::not_read(&mut acc, scan.includes); return acc.finish(Kind::Script, scan.lines); }; @@ -191,17 +191,23 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits: let read = includes::follow(&mut acc, scan.includes, loader, name, bytes.len(), &mut known); // Each file's text and the names it declares are worked out once for all the scans below. let decoded: Vec<_> = read.iter().map(|file| decode(&file.bytes)).collect(); - let texts: Vec<_> = decoded.into_iter().map(|(text, invalid)| (analyze::unescaped(text, &mut acc), invalid)).collect(); - let declarations: Vec<_> = texts.iter().map(|(text, _)| analyze::declarations(text, &mut acc)).collect(); + let texts: Vec<_> = decoded + .into_iter() + .map(|(text, invalid)| { + let (text, braced) = analyze::unescaped(text, &mut acc); + (text, braced, invalid) + }) + .collect(); + let declarations: Vec<_> = texts.iter().map(|(text, ..)| analyze::declarations(text, &mut acc)).collect(); // A variable may get what it holds from another file's variable: the files are scanned again, // each with what is known so far, while that grows, at most three more times. for _ in 0..3 { let before = known.len(); let mut tallies = report::Acc::new(limits); - let more = analyze::scan(&text, &declared, None, std::rc::Rc::from([]), &known, &mut tallies).known; + let more = analyze::scan(&text, &declared, &[], None, std::rc::Rc::from([]), &known, &mut tallies).known; known.add(more, limits.entries); - for ((file, (text, _)), declared) in read.iter().zip(&texts).zip(&declarations) { - let more = analyze::scan(text, declared, Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut tallies).known; + for ((file, (text, ..)), declared) in read.iter().zip(&texts).zip(&declarations) { + let more = analyze::scan(text, declared, &[], Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut tallies).known; known.add(more, limits.entries); } acc.steps = acc.steps.saturating_add(tallies.steps); @@ -210,12 +216,12 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits: } } // The scans for the report: every file starts with what any file's variables hold. - let lines = analyze::scan(&text, &declared, None, std::rc::Rc::from([]), &known, &mut acc).lines; - for ((file, (text, invalid)), declared) in read.iter().zip(&texts).zip(&declarations) { + let lines = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &known, &mut acc).lines; + for ((file, (text, braced, invalid)), declared) in read.iter().zip(&texts).zip(&declarations) { if *invalid { acc.problem(report::NOT_UTF8, None, Some(&file.path), None); } - analyze::scan(text, declared, Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut acc); + analyze::scan(text, declared, braced, Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut acc); } acc.finish(Kind::Script, lines) } @@ -230,6 +236,7 @@ fn settle<'l>( pre: report::Acc<'l>, text: &str, declared: &analyze::Declared<'_>, + braced: &[analyze::Braced], mut known: analyze::Known, ) -> report::Acc<'l> { if known.len() == 0 { @@ -240,7 +247,7 @@ fn settle<'l>( for _ in 0..3 { let before = known.len(); let mut acc = pre.clone(); - let more = analyze::scan(text, declared, None, std::rc::Rc::from([]), &known, &mut acc).known; + let more = analyze::scan(text, declared, braced, None, std::rc::Rc::from([]), &known, &mut acc).known; known.add(more, entries); if known.len() == before { acc.steps = acc.steps.saturating_add(spent); @@ -249,7 +256,7 @@ fn settle<'l>( spent = spent.saturating_add(acc.steps.saturating_sub(pre.steps)); } let mut acc = pre; - analyze::scan(text, declared, None, std::rc::Rc::from([]), &known, &mut acc); + analyze::scan(text, declared, braced, None, std::rc::Rc::from([]), &known, &mut acc); acc.steps = acc.steps.saturating_add(spent); acc } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index e7ead63a4f..853f212c11 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -209,7 +209,7 @@ fn directives_are_read_at_the_start_of_a_line_in_both_forms() { let includes: Vec<_> = r.includes.iter().map(|i| (i.value.as_str(), i.line, i.status)).collect(); assert_eq!(includes, [("lib/a.jsxinc", 3, IncludeStatus::NotRead)]); assert_eq!(problems(&r), [("unknownDirective", Some(8), Some("#pragma")), ("unknownDirective", Some(9), Some("#!"))]); - assert_eq!(r.needs, [Need::Language, Need::HostOnly]); + assert_eq!(r.needs, [Need::Language], "VectorCraft runs #targetengine"); } #[test] @@ -268,6 +268,253 @@ fn names_written_with_escapes_are_read_as_the_names_they_spell() { assert_eq!(r.lines, 3); } +/// `src` with the escapes in its names written as the characters they stand for. +fn unescaped(src: &str) -> String { + let limits = Limits::default(); + crate::analyze::unescaped(std::borrow::Cow::Borrowed(src), &mut crate::report::Acc::new(&limits)).0.into_owned() +} + +#[test] +fn names_are_made_of_the_unicode_identifier_characters() { + // U+2118 (Other_ID_Start) starts a name, and U+203F (connector punctuation), U+00B7 + // (Other_ID_Continue) and the zero width non-joiner and joiner continue one. + // Unicode 17.0 assigned the letter U+088F and the combining mark U+1ACF. + for name in ["\u{2118}a", "a\u{203F}b", "a\u{B7}b", "a\u{200C}b", "a\u{200D}b", "_\u{2118}", "$_a1", "\u{E9}t\u{E9}", "\u{88F}", "_\u{1ACF}"] { + assert_eq!(tokens(name), [(T::Ident, name)], "{name:?}"); + } + for (src, want) in [ + // Characters that only continue a name, and digits, don't start one. + ("\u{203F}a", [(T::Other, "\u{203F}"), (T::Ident, "a")]), + ("\u{1ACF}a", [(T::Other, "\u{1ACF}"), (T::Ident, "a")]), + ("\u{B7}a", [(T::Other, "\u{B7}"), (T::Ident, "a")]), + ("\u{200C}a", [(T::Other, "\u{200C}"), (T::Ident, "a")]), + ("0a", [(T::Number, "0"), (T::Ident, "a")]), + // A superscript digit (category No) and a letter that is Pattern_Syntax are in no name. + ("a\u{B2}", [(T::Ident, "a"), (T::Other, "\u{B2}")]), + ("a\u{2E2F}", [(T::Ident, "a"), (T::Other, "\u{2E2F}")]), + ("\u{2E2F}a", [(T::Other, "\u{2E2F}"), (T::Ident, "a")]), + // `#` and a name away from the start of a line, and a regular expression's flags. + ("a #\u{2118}b", [(T::Ident, "a"), (T::Other, "#\u{2118}b")]), + ("=/a/g\u{B2}", [(T::RegExp, "/a/g"), (T::Other, "\u{B2}")]), + ] { + let mut got = tokens(src); + if src.starts_with('=') { + got.remove(0); + } + assert_eq!(got, want, "{src:?}"); + } + assert_eq!(tokens("a #\u{B2}"), [(T::Ident, "a"), (T::Other, "#"), (T::Other, "\u{B2}")]); + assert_eq!(tokens("=/a/g\u{200D}"), [(T::Punct, "="), (T::RegExp, "/a/g\u{200D}")]); + // The code in an XML literal's braces reads names by the same rule. + assert!(tokens("var x = {\u{2118}b + c\u{203F}d};").iter().filter(|t| t.0 == T::Ident).any(|t| t.1 == "c\u{203F}d")); + assert!(tokens("var x = {\u{2118}b};").contains(&(T::Ident, "\u{2118}b"))); +} + +#[test] +fn an_escape_stands_for_a_character_only_where_a_name_may_hold_it() { + for (src, want) in [ + ("\\u2118a", "\u{2118}a"), + ("a\\u203Fb", "a\u{203F}b"), + ("a\\u00B7b", "a\u{B7}b"), + ("a\\u200Cb", "a\u{200C}b"), + ("a\\u200Db", "a\u{200D}b"), + ("a\\u0030", "a0"), + ("\\u0024\\u005F", "$_"), + ("\\u088F", "\u{88F}"), + ("_\\u1ACF", "_\u{1ACF}"), + // Not at the start of a name. + ("\\u0030abc", "\\u0030abc"), + ("\\u1ACFa", "\\u1ACFa"), + ("\\u203Fa", "\\u203Fa"), + ("\\u00B7a", "\\u00B7a"), + // In no name. + ("a\\u00B2", "a\\u00B2"), + ("a\\u2E2F", "a\\u2E2F"), + ("\\u2E2F", "\\u2E2F"), + // Malformed escapes and a lone surrogate. + ("\\u", "\\u"), + ("a\\u12;", "a\\u12;"), + ("a\\uZZZZ", "a\\uZZZZ"), + ("a\\uD800", "a\\uD800"), + ("", ""), + ] { + assert_eq!(unescaped(src), want, "{src:?}"); + } + let r = report("\\u0061pp.a\\u203Fb;\napp.\\u2118c;\n"); + let members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(members, ["app.a\u{203F}b", "app.\u{2118}c"]); + // An escape a name may not hold where it stands, or a malformed one, is not part of a name. + for (src, want) in [ + ("\\u0030a", [(T::Other, "\\"), (T::Ident, "u0030a")]), + ("a\\u00B2", [(T::Ident, "a"), (T::Other, "\\")]), + ("a\\u12", [(T::Ident, "a"), (T::Other, "\\")]), + ("a\\uD800", [(T::Ident, "a"), (T::Other, "\\")]), + ] { + assert_eq!(tokens(src).get(..2), Some(&want[..]), "{src:?}"); + } + assert_eq!(tokens("a\\u0030\\u200C"), [(T::Ident, "a\\u0030\\u200C")]); + let r = report("app.\\u0030abc;\napp.a\\u00B2;\n"); + assert!(r.members.iter().all(|m| !m.name.contains('\\') && !m.name.contains("0abc")), "{:?}", r.members); +} + +#[test] +fn malformed_escapes_in_bulk_are_read_once_through() { + let src = format!("{}\n{}\nalert(1);\n", "\\u\\uD800\\u12\\u0030\\u2118".repeat(20_000), "a\u{203F}".repeat(20_000)); + let r = report(&src); + assert_eq!(r.lines, 3); + assert_eq!(feature(&r, "notify").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len()); + // Braced escapes: long runs of digits, closed and not, and ones that end at once. + let zeros = "0".repeat(100_000); + let src = format!( + "a\\u{{{zeros}62}};\n\\u{{{}\n{}\n{}\nalert(1);\n", + "f".repeat(100_000), + "\\u{".repeat(20_000), + "\\u{0000000061}\\u{110000}\\u{}\\u{D800}#\\u{61}".repeat(10_000) + ); + let r = report(&src); + assert_eq!(r.lines, 5); + assert_eq!(feature(&r, "notify").map(|f| f.lines.as_slice()), Some(&[5][..])); + assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len()); +} + +#[test] +fn braced_escapes_in_names_are_read_by_their_value() { + for (src, want) in [ + ("\\u{61}pp", "app"), + ("a\\u{62}c", "abc"), + ("\\u{0000000061}", "a"), + ("\\u{2118}\\u{203F}", "\u{2118}\u{203F}"), + ("a\\u{1D7CE}", "a\u{1D7CE}"), + ("\\u{1D49C}", "\u{1D49C}"), + // Not at the start of a name, in no name, out of range, empty, a surrogate and not closed. + ("\\u{30}a", "\\u{30}a"), + ("a\\u{1F600}", "a\\u{1F600}"), + ("a\\u{110000}", "a\\u{110000}"), + ("a\\u{FFFFFFFFFFFFFFFFFFFF}b", "a\\u{FFFFFFFFFFFFFFFFFFFF}b"), + ("a\\u{}b", "a\\u{}b"), + ("a\\u{D800}", "a\\u{D800}"), + ("a\\u{61", "a\\u{61"), + ("a\\u{6 1}", "a\\u{6 1}"), + ] { + assert_eq!(unescaped(src), want, "{src:?}"); + } + assert_eq!(tokens("\\u{61}pp.x"), [(T::Ident, "\\u{61}pp"), (T::Punct, "."), (T::Ident, "x")]); + assert_eq!(tokens("a\\u{0000000062}"), [(T::Ident, "a\\u{0000000062}")]); + assert_eq!(tokens("a\\u{1F600}").get(..2), Some(&[(T::Ident, "a"), (T::Other, "\\")][..])); +} + +#[test] +fn braced_name_escape_reports_later_syntax_and_member() { + let r = report("\\u{61}pp.activeDocument.acmeName;\nvar a\\u{62}c = 1, \\u{0000000061}pp2 = 2;\n\\u{61}pp.x + \\u{61}pp.y;\n"); + let members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(members, ["app.activeDocument.acmeName", "app.x", "app.y"]); + assert_eq!( + problems(&r), + [ + ("newerSyntax", Some(1), Some("\\u{61}")), + ("newerSyntax", Some(2), Some("\\u{62}")), + ("newerSyntax", Some(2), Some("\\u{0000000061}")), + ("newerSyntax", Some(3), Some("\\u{61}")), + ] + ); + // An escape that isn't a name's character, or isn't closed, makes no name and no report of one. + for src in [ + "\\u{1F600}pp.activeDocument;", + "\\u{110000}pp.activeDocument;", + "\\u{}pp.activeDocument;", + "\\u{D800}pp.activeDocument;", + "\\u{61pp.activeDocument;", + ] { + let r = report(src); + assert!(r.members.iter().all(|m| !m.name.starts_with("app")), "{src:?}: {:?}", r.members); + assert!(r.problems.iter().all(|p| p.detail.as_deref().is_none_or(|d| !d.starts_with("\\u{"))), "{src:?}: {:?}", r.problems); + } + // In an included file, the report names the file. + let mut m = mem(&[("lib.jsxinc", "\\u{61}pp.name;\n")]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\n", Some(&mut m), &Limits::default()); + let found: Vec<_> = r.problems.iter().map(|p| (p.code, p.line, p.file.as_deref(), p.detail.as_deref())).collect(); + assert_eq!(found, [("newerSyntax", Some(1), Some("lib.jsxinc"), Some("\\u{61}"))]); +} + +#[test] +fn private_names_with_escaped_starts_are_single_tokens() { + assert_eq!(tokens("a #\\u0061b"), [(T::Ident, "a"), (T::Other, "#\\u0061b")]); + assert_eq!(tokens("this.#\\u0061pp"), [(T::Ident, "this"), (T::Punct, "."), (T::Other, "#\\u0061pp")]); + assert_eq!(tokens("o.#\\u{61}b"), [(T::Ident, "o"), (T::Punct, "."), (T::Other, "#\\u{61}b")]); + // An escape for a character no name starts with leaves `#` on its own. + assert_eq!(tokens("a #\\u0030b").get(..3), Some(&[(T::Ident, "a"), (T::Other, "#"), (T::Other, "\\")][..])); + let r = report("var q = this.#\\u0061pp;\nvar r = o.#\\u{61}b;\n"); + assert!(r.members.is_empty(), "{:?}", r.members); + assert_eq!( + problems(&r), + [("newerSyntax", Some(1), Some("#app")), ("newerSyntax", Some(2), Some("\\u{61}")), ("newerSyntax", Some(2), Some("#ab"))] + ); +} + +#[test] +fn private_name_reports_decoded_construct() { + let r = report("var q = this.#hid\\u0064en;\nvar r = this.#\\u0061\\u0062;\n"); + assert_eq!(problems(&r), [("newerSyntax", Some(1), Some("#hidden")), ("newerSyntax", Some(2), Some("#ab"))]); +} + +#[test] +fn private_name_at_line_start_is_not_a_directive() { + let r = report(concat!( + "class Box {\n", + " #size = 1;\n", + " #\\u0061rea = 2;\n", + " #include 'a.jsxinc'\n", + " #\\u0069nclude = 4;\n", + " #\\u{69}nclude = 5;\n", + "}\n", + "#\\u0062ox = 3;\n", + "#pragma once\n", + "#target acme\n", + )); + let directives: Vec<_> = r.directives.iter().map(|d| (d.name, d.line)).collect(); + assert_eq!(directives, [("include", 4), ("target", 10)]); + // Where the name a private name's escapes spell would start a preprocessor line, the report + // gives the name as written. + assert_eq!( + problems(&r), + [ + ("newerSyntax", Some(1), Some("class")), + ("newerSyntax", Some(2), Some("#size")), + ("newerSyntax", Some(3), Some("#area")), + ("newerSyntax", Some(5), Some("#\\u0069nclude")), + ("newerSyntax", Some(6), Some("\\u{69}")), + ("newerSyntax", Some(6), Some("#\\u{69}nclude")), + ("newerSyntax", Some(8), Some("#\\u0062ox")), + ("unknownDirective", Some(9), Some("#pragma")), + ] + ); +} + +#[test] +fn private_name_that_starts_with_a_directive_name_is_not_a_directive() { + let r = report(concat!( + "class Box {\n", + " #include$size = 1;\n", + " #include\u{e9} = 2;\n", + " #include\\u0041 = 3;\n", + " #include\\u{41} = 4;\n", + " #INCLUDE 'a.jsxinc'\n", + "}\n", + )); + let directives: Vec<_> = r.directives.iter().map(|d| (d.name, d.line)).collect(); + assert_eq!(directives, [("include", 6)]); +} + +#[test] +fn xml_code_uses_escaped_names() { + let r = report("var x = {\\u{61}pp.activeDocument};\nvar y = \\u0061pp.z \\u{61};\n"); + let members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(members, ["app.activeDocument"]); + assert_eq!(problems(&r), [("newerSyntax", Some(1), Some("\\u{61}"))]); + assert!(tokens("var x = {this.#\\u0061b};").contains(&(T::Other, "#\\u0061b"))); +} + #[test] fn the_scripts_own_platform_names_are_not_the_platforms() { let r = report(concat!( @@ -1492,7 +1739,7 @@ fn include_lines_share_the_folders_of_the_include_path_before_them() { let limits = Limits::default(); let mut acc = report::Acc::new(&limits); let declared = analyze::declarations(&src, &mut acc); - let scan = analyze::scan(&src, &declared, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); + let scan = analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); let (first, rest) = scan.includes.split_first().unwrap(); assert_eq!((first.paths.len(), rest.len()), (64, 999)); assert!(rest.iter().all(|i| std::rc::Rc::ptr_eq(&i.paths, &first.paths)), "one list of folders, not a copy for each line"); diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index bdabab2acd..ada9a4375c 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -555,8 +555,8 @@ impl Rules<'_> { } } - /// A linear or radial gradient over `b` at `opacity`, with the stops SVG export writes - /// (midpoints as stops of their own). `None` for freeform gradients. + /// A linear, radial, conic or diamond gradient over `b` at `opacity`, with the stops SVG export + /// writes (midpoints as stops of their own). `None` for freeform gradients. fn gradient(&mut self, g: &GradientPaint, b: Rect, opacity: f32) -> Option { let geom = g.resolve(b); let stops = |pos: &dyn Fn(f32) -> f64| { @@ -580,9 +580,12 @@ impl Rules<'_> { let pos = |t: f32| if line > 1e-9 { (from + t as f64 * length) / line + 0.5 } else { t as f64 }; Some(format!("linear-gradient({}deg, {})", fmt_num(angle, 2), stops(&pos))) } - GradientKind::Radial => { + // CSS has no diamond gradient: the ellipse through the square's corners stands in. + GradientKind::Radial | GradientKind::Diamond => { let r = (geom.end - geom.start).hypot(); - if geom.focal.is_some() { + if g.gradient.kind == GradientKind::Diamond { + self.warn("diamond gradients are written as radial gradients through their corners"); + } else if geom.focal.is_some() { self.warn("radial gradients start at their centre (an off-centre focal point is left out)"); } let shape = if (geom.aspect - 1.0).abs() < 1e-9 { @@ -593,6 +596,27 @@ impl Rules<'_> { let at = format!("at {} {}", self.len(geom.start.x - b.x0), self.len(geom.start.y - b.y0)); Some(format!("radial-gradient({shape} {at}, {})", stops(&|t| t as f64))) } + GradientKind::Conic => { + // CSS sweeps clockwise from the `from` angle, 0deg straight up + // (https://www.w3.org/TR/css-images-4/#conic-gradients): the vector's direction is + // where the sweep starts. A mirrored sweep turns the other way, so its stops are + // written mirrored about the seam; CSS has no elliptical sweep. + let frame = geom.conic_frame(); + let v = frame * Point::new(1.0, 0.0) - frame * Point::ORIGIN; + let from = v.x.atan2(-v.y).to_degrees().rem_euclid(360.0); + if (geom.aspect.abs() - 1.0).abs() > 1e-9 && geom.unit_frame().is_some() { + self.warn("conic gradients are written circular (an elliptical sweep is left out)"); + } + let mut stops: Vec<(f32, Color, f32)> = g.gradient.expanded().map(|(t, c, o, _)| (t, c, o)).collect(); + if geom.is_mirrored() { + stops.reverse(); + stops.iter_mut().for_each(|s| s.0 = 1.0 - s.0); + } + let stops: Vec = + stops.iter().map(|(t, c, o)| format!("{} {}%", color_css(c, o * opacity), fmt_num(f64::from(*t) * 100.0, 2))).collect(); + let at = format!("at {} {}", self.len(geom.start.x - b.x0), self.len(geom.start.y - b.y0)); + Some(format!("conic-gradient(from {}deg {at}, {})", fmt_num(from, 2), stops.join(", "))) + } GradientKind::Freeform => None, } } @@ -609,12 +633,9 @@ impl Rules<'_> { if n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()) { art.unsupported("fills or strokes on the type object"); } - // Area type that Shrink Text to Fit scales down is written in the styles it draws in. - let fitted = matches!((&t.kind, t.area.fit), (TextKind::Area { .. }, vectorcraft_doc::AreaFit::ShrinkText { .. })) - .then(|| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale) - .filter(|f| *f != 1.0) - .map(|f| vectorcraft_text::scaled(t, f)); - let t = fitted.as_ref().unwrap_or(t); + // Type that Shrink Text to Fit or Dynamic Text scales is written in the styles it draws in. + let fitted = vectorcraft_text::drawn(t); + let t = &*fitted; let st = t.first_style(); if t.runs.iter().any(|r| r.style != st) { self.warn("type with several character styles is written in its first one"); diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index eed8ecd335..8eb18626f3 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -188,7 +188,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: // An artboard exported on its own is named after it (#3544), else after the document. // A name that is blank once the characters XML can't hold are dropped falls back too. let board = opts.artboard.filter(|_| opts.artboard_title).and_then(|i| doc.artboards.get(i)).map(|a| xml_text(&a.name)); - let title = board.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| xml_text(&doc.title)); + let title = board.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| xml_text(doc.info_title())); if !title.is_empty() { out.push_str(&w.indent(1)); out.push_str(&format!("{title}{nl}")); diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 129bd83e28..c5a98aebf1 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -121,6 +121,21 @@ impl Reuse { } } +/// Are `children` the pieces of a raster mesh warp ([`vectorcraft_doc::live::mesh_warp_image`]): +/// more than one, each a clip group of a triangle and one and the same image? +fn image_pieces(children: &[std::sync::Arc]) -> bool { + let mut first: Option<(&str, u32, u32)> = None; + children.len() > 1 + && children.iter().all(|c| { + let NodeKind::Group { children, clip: true } = &c.kind else { return false }; + let [clip, im] = children.as_slice() else { return false }; + let (NodeKind::Path { path, .. }, NodeKind::Image(im)) = (&clip.kind, &im.kind) else { return false }; + let triangle = path.subpaths.len() == 1 && path.anchor_count() == 3; + let image = (im.key.as_str(), im.width, im.height); + triangle && *first.get_or_insert(image) == image + }) +} + /// Art about to be written moved by `m.inverse()` (a symbol instance's): map what the canvas /// leaves on the page by `m` first, so it stays there. That is every pattern paint's placement /// and the art of unlinked opacity masks. @@ -226,7 +241,7 @@ impl Writer<'_> { if let (Some(g), Some(b)) = (pixel_gradient(&f.paint, true), bounds) { p.extend((f.opacity < 1.0).then(|| ("opacity", fmt_num(f.opacity as f64, 3)))); p.extend(blend); - self.raster_paint(g, b, &[d.to_string()], rule, &p, "", true); + self.raster_paint(g, b, b, &[d.to_string()], rule, &p, "", true); } else { self.fill_props(f, rule, bounds, &mut p); p.extend(blend); @@ -263,13 +278,19 @@ impl Writer<'_> { let clip = self.path_d(&PathData::from_bezpath(&outline), self.xf); p.extend(opacity); p.extend(blend); - self.raster_paint(g, b, &[clip], FillRule::NonZero, &p, &side, false); + let reach = + if outline.elements().is_empty() { b } else { b.union(vectorcraft_geom::kurbo::Shape::bounding_box(&outline)) }; + self.raster_paint(g, b, reach, &[clip], FillRule::NonZero, &p, &side, false); } (WrittenShape::Fill(outlines), Some((g, b))) if s.path_gradient().is_none() => { let clip: Vec = outlines.iter().map(|o| self.path_d(&PathData::from_bezpath(o), self.xf)).collect(); p.extend(opacity); p.extend(blend); - self.raster_paint(g, b, &clip, FillRule::NonZero, &p, &side, false); + let reach = outlines + .iter() + .filter(|o| !o.elements().is_empty()) + .fold(b, |r, o| r.union(vectorcraft_geom::kurbo::Shape::bounding_box(o))); + self.raster_paint(g, b, reach, &clip, FillRule::NonZero, &p, &side, false); } (WrittenShape::Stroke { width }, _) => { p.push(("fill", "none".into())); @@ -633,6 +654,10 @@ impl Writer<'_> { /// An object, inside `` when it links to a URL (Attributes panel). pub(super) fn node(&mut self, n: &Node) { + // Ruler guides are not written, not even as a link. + if n.is_ruler_guide() { + return; + } let layer = usize::from(n.is_layer()); self.layer_nest += layer; match n.url().filter(|_| n.visible && !self.anonymous) { @@ -668,6 +693,10 @@ impl Writer<'_> { match &n.kind { NodeKind::Layer { template: true, .. } => {} NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { + // The pieces a Warp effect cuts an image into share its pixels, as an envelope's do. + if image_pieces(children) { + self.share_images(n); + } let id = self.id_attr(n); let a = self.attrs(&self.group_props(n)); self.line(&format!("")); @@ -717,7 +746,7 @@ impl Writer<'_> { self.line(""); } } - NodeKind::Path { guide: true, .. } => {} + NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => {} NodeKind::Path { path, rule, .. } => { if path.is_empty() { return; diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index fb06f80057..7c30f23f5a 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -88,7 +88,7 @@ fn dublin_core(doc: &Document) -> Vec<(&'static str, String)> { let info = &doc.metadata; let mut terms = vec![("format", "image/svg+xml".to_string())]; let created = info.created.map(vectorcraft_doc::metadata::iso8601).unwrap_or_default(); - let fields = [("title", doc.title.as_str()), ("creator", info.author.as_str()), ("description", info.description.as_str())]; + let fields = [("title", doc.info_title()), ("creator", info.author.as_str()), ("description", info.description.as_str())]; let rights = [("rights", info.copyright_notice.as_str()), ("rights", info.copyright_url.as_str()), ("date", created.as_str())]; let keywords = info.keywords.iter().map(|k| ("subject", k.as_str())); terms.extend(fields.into_iter().chain(keywords).chain(rights).filter(|(_, v)| !v.trim().is_empty()).map(|(k, v)| (k, v.to_string()))); @@ -170,6 +170,10 @@ impl Writer<'_> { } let mut named: Vec<(NodeId, String)> = Vec::new(); self.doc.walk(|n| { + // Ruler guides are not written, so their names reserve no id. + if n.is_ruler_guide() { + return; + } if let Some(name) = &n.name { named.push((n.id, sanitize_id(name))); } diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 740d1b78f7..e982ab315c 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -264,13 +264,28 @@ impl Writer<'_> { // Object fills and strokes are images (see `raster_paint`); characters' paints aren't. self.warn("freeform gradients on characters are written as linear gradients"); } + if g.gradient.kind == GradientKind::Conic { + // SVG has no conic gradient; object fills and strokes are wedges or images (see + // `raster_paint`). + self.warn("conic gradients on characters are written as linear gradients"); + } + if g.gradient.kind == GradientKind::Diamond { + // Object fills and strokes are four linear gradients or images (see `raster_paint`). + self.warn("diamond gradients on characters are written as radial gradients"); + } let mut geom = g.resolve(bounds); geom.transform(self.xf, g.gradient.kind); + if g.gradient.kind != GradientKind::Radial { + // Only a radial gradient has a focal point (a plug-in's or a file's other kinds can + // carry one that draws nothing). + geom.focal = None; + } let (s, e) = (geom.start, geom.end); // An off-centre focal point: `fx`/`fy`, in the gradient's own (unsquashed) space. let focal = |w: &Self, f: Point| format!(" fx=\"{}\" fy=\"{}\"", w.num(f.x), w.num(f.y)); let (tag, prefix, attrs) = match g.gradient.kind { - GradientKind::Radial => { + // A diamond's circle runs through its square's corners. + GradientKind::Radial | GradientKind::Diamond => { let r = self.num((e - s).hypot()); let attrs = if (geom.aspect - 1.0).abs() < 1e-9 { let f = geom.focal.map(|f| focal(self, f)).unwrap_or_default(); @@ -283,7 +298,7 @@ impl Writer<'_> { }; ("radialGradient", "radial-gradient", attrs) } - GradientKind::Linear | GradientKind::Freeform => ( + GradientKind::Linear | GradientKind::Freeform | GradientKind::Conic => ( "linearGradient", "linear-gradient", format!(" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"", self.num(s.x), self.num(s.y), self.num(e.x), self.num(e.y)), @@ -427,39 +442,84 @@ impl Writer<'_> { /// A gradient `g` painted over `bounds` (the space [`Self::xf`] maps into user space) that is /// drawn as pixels ([`GradientPaint::draws_as_pixels`]) when it paints a fill (`fill`) or a - /// stroke: an `` over its painted box, clipped to `clip` (outlines in user space filled - /// by `rule`), in a group with `props` and the `side` attribute. A freeform gradient's colour + /// stroke: an `` over its painted box and over `area` (a stroke's outline, whose miters, + /// caps and arrowheads can reach past the box), clipped to `clip` (outlines in user space + /// filled by `rule`), in a group with `props` and the `side` attribute. A freeform gradient's + /// image covers the painted box only. A freeform gradient's colour /// field, which SVG can't express, is sampled as the canvas samples it (at twice the box's size - /// in points); a linear or radial gradient at the document's raster effects resolution (at most - /// [`MAX_GRADIENT_PX`] a side), with dither's noise on a fill. Nothing is written for an empty - /// box. + /// in points); a linear, radial, conic or diamond gradient at the document's raster effects resolution + /// (at most [`MAX_GRADIENT_PX`] a side), with dither's noise on a fill. Nothing is written for + /// an empty box. + /// + /// A conic gradient (SVG has none) with opaque stops that isn't drawn as pixels is written as + /// [`CONIC_WEDGES`] solid wedges around its center in the same clip group instead, each + /// running on to the seam under the next ([`vectorcraft_color::GradientGeom::conic_wedges`]): + /// vector art with a sharp seam. With translucent stops, where wedges drawn over each other + /// would add up their opacity, it is an image. + /// + /// A diamond gradient (SVG has none) with opaque stops that isn't drawn as pixels is written + /// as four linear gradients in the same clip group, one for each quadrant of its frame and + /// equal to the diamond there, overlapping so no hairline shows between them + /// ([`vectorcraft_color::GradientGeom::diamond_quadrants`]). With translucent stops, where + /// the overlaps would add up their opacity, or without an extent, it is an image. #[allow(clippy::too_many_arguments)] - pub(super) fn raster_paint(&mut self, g: &GradientPaint, bounds: Rect, clip: &[String], rule: FillRule, props: &Props, side: &str, fill: bool) { + pub(super) fn raster_paint( + &mut self, + g: &GradientPaint, + bounds: Rect, + area: Rect, + clip: &[String], + rule: FillRule, + props: &Props, + side: &str, + fill: bool, + ) { use vectorcraft_color::freeform::{grid_size, painted_box, spread_scale}; let Some(b) = painted_box(bounds) else { return }; let freeform = g.gradient.kind == GradientKind::Freeform; - let (rgba, cols, rows): (Vec, u16, u16) = if freeform { - let (cols, rows) = grid_size(b, 2.0 * b.width().max(b.height())); - let field = g.freeform_on(b).model_field(spread_scale(b)); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - (field.display_grid(b, cols, rows).flat_map(|([r, g, bl], a)| [q(r), q(g), q(bl), q(a)]).collect(), cols, rows) + // The box the paint covers: the painted box, and a stroke's outline, whose miters, caps + // and arrowheads can reach past it (a freeform gradient's field covers the painted box). + let cover = if freeform { b } else { Some(b.union(area.abs())).filter(|r| r.is_finite()).unwrap_or(b) }; + let conic = g.gradient.kind == GradientKind::Conic; + let opaque = g.gradient.stops.iter().all(|s| s.opacity >= 1.0); + let wedges = conic && !g.draws_as_pixels(fill) && opaque; + let quadrants = (g.gradient.kind == GradientKind::Diamond && !g.draws_as_pixels(fill) && opaque) + .then(|| g.resolve(bounds).diamond_quadrants(cover)) + .flatten(); + let href = if wedges { + self.warn("conic gradients are written as solid wedges clipped to their shapes"); + None + } else if quadrants.is_some() { + self.warn("diamond gradients are written as four linear gradients clipped to their shapes"); + None } else { - let k = self.doc.raster_effects_ppi / 72.0; - let along = |len: f64| (len * k).ceil().clamp(1.0, MAX_GRADIENT_PX) as u16; - let (cols, rows) = (along(b.width()), along(b.height())); - (g.pixels(b, b, cols, rows, fill, &Color::to_rgb).flatten().collect(), cols, rows) + let (rgba, cols, rows): (Vec, u16, u16) = if freeform { + let (cols, rows) = grid_size(b, 2.0 * b.width().max(b.height())); + let field = g.freeform_on(b).model_field(spread_scale(b)); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + (field.display_grid(b, cols, rows).flat_map(|([r, g, bl], a)| [q(r), q(g), q(bl), q(a)]).collect(), cols, rows) + } else { + let k = self.doc.raster_effects_ppi / 72.0; + let along = |len: f64| (len * k).ceil().clamp(1.0, MAX_GRADIENT_PX) as u16; + let (cols, rows) = (along(cover.width()), along(cover.height())); + (g.pixels(b, cover, cols, rows, fill, &Color::to_rgb).flatten().collect(), cols, rows) + }; + let mut png = Vec::new(); + let Some(img) = image::RgbaImage::from_raw(u32::from(cols), u32::from(rows), rgba) else { return }; + if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + return; + } + self.warn(if freeform { + "freeform gradients are written as images clipped to their shapes" + } else if conic { + "conic gradients with translucent stops, dither or the Perceptual method are written as images clipped to their shapes" + } else if g.gradient.kind == GradientKind::Diamond { + "diamond gradients with translucent stops, dither, the Perceptual method or no extent are written as images clipped to their shapes" + } else { + "linear and radial gradients drawn as pixels are written as images clipped to their shapes" + }); + Some(self.blob_href(&ImageBlob::new("image/png", png))) }; - let mut png = Vec::new(); - let Some(img) = image::RgbaImage::from_raw(u32::from(cols), u32::from(rows), rgba) else { return }; - if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { - return; - } - self.warn(if freeform { - "freeform gradients are written as images clipped to their shapes" - } else { - "linear and radial gradients drawn as pixels are written as images clipped to their shapes" - }); - let href = self.blob_href(&ImageBlob::new("image/png", png)); let cid = self.fresh_id("clip-path"); let r = if rule == FillRule::EvenOdd { " clip-rule=\"evenodd\"" } else { "" }; self.def(1, &format!("")); @@ -477,12 +537,35 @@ impl Writer<'_> { self.line(&format!("")); } self.depth += 1; - let (x, y, w, h) = (self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height())); - let tr = if self.xf == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(self.xf)) }; - self.line(&format!( - "", - xml_escape(&href) - )); + match href { + Some(href) => { + let (x, y, w, h) = (self.num(cover.x0), self.num(cover.y0), self.num(cover.width()), self.num(cover.height())); + let tr = if self.xf == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(self.xf)) }; + self.line(&format!( + "", + xml_escape(&href) + )); + } + None => match quadrants { + Some(quadrants) => { + let gradient = vectorcraft_color::Gradient { kind: GradientKind::Linear, ..g.gradient.clone() }; + for (pts, geom) in quadrants { + // Not named after the swatch: four defs, none of them the swatch's gradient. + let linear = GradientPaint { gradient: gradient.clone(), geom: Some(geom), swatch: None, ..g.clone() }; + let id = self.gradient_def(&linear, b); + let d = self.path_d(&PathData::single(vectorcraft_geom::SubPath::polyline(&pts, true)), self.xf); + self.line(&format!("")); + } + } + None => { + let sample = g.gradient.sampler(); + for (pts, t) in g.resolve(bounds).conic_wedges(cover, CONIC_WEDGES, true) { + let d = self.path_d(&PathData::single(vectorcraft_geom::SubPath::polyline(&pts, true)), self.xf); + self.line(&format!("", sample(t as f32).0.to_hex())); + } + } + }, + } self.depth -= 1; self.line(""); if nested { @@ -669,14 +752,19 @@ impl Writer<'_> { } } -/// Most pixels along a side of a linear or radial gradient's image. +/// Most pixels along a side of a linear, radial, conic or diamond gradient's image. const MAX_GRADIENT_PX: f64 = 4096.0; +/// Wedges a conic gradient with opaque stops is written as: one a degree. +const CONIC_WEDGES: usize = 360; + /// The gradient a fill (`fill`) or stroke paint is, if it is drawn as pixels -/// ([`GradientPaint::draws_as_pixels`]; SVG has no freeform gradients, for one). +/// ([`GradientPaint::draws_as_pixels`]; SVG has no freeform gradients, for one) or is a conic or +/// diamond gradient (SVG has neither: [`Writer::raster_paint`] draws a conic as wedges or an +/// image, a diamond as four linear gradients or an image). pub(super) fn pixel_gradient(p: &Paint, fill: bool) -> Option<&GradientPaint> { match p { - Paint::Gradient(g) if g.draws_as_pixels(fill) => Some(g), + Paint::Gradient(g) if g.draws_as_pixels(fill) || matches!(g.gradient.kind, GradientKind::Conic | GradientKind::Diamond) => Some(g), _ => None, } } diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 19bbbd5bef..e5a5248400 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -258,6 +258,19 @@ impl Writer<'_> { self.warn("type on a path with glyphs hanging outside its brackets is outlined to keep its look"); return self.text_outlines(n, t); } + // The space before the first character is written as its `dx`; one before a character + // after a line break, which the `` writes as a space, keeps its look as outlines. + let plain = t.plain_text(); + let mut at = 0; + let spaced_break = t.runs.iter().any(|r| { + let start = at; + at += r.text.len(); + r.style.kerning_before != 0.0 && (start..at).any(|b| b > 0 && vectorcraft_text::line_start_space(&plain, b, &r.style, false) != 0.0) + }); + if spaced_break { + self.warn("type on a path with space before a character after a line break is outlined to keep its look"); + return self.text_outlines(n, t); + } // A `` holds the characters of the text, not the bullets or numbers drawn // before them. if !lay.markers.is_empty() { @@ -534,8 +547,11 @@ impl Writer<'_> { // The element's user space is the document's; gradients span the laid-out text. let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); self.note_fonts(t, &lay); + // The styles the layout draws the text in: Dynamic Text scales its sizes, leading and baseline shifts. + let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); + let drawn = fitted.as_ref().unwrap_or(t); let space = (lay.bounds, self.xf * t.xf); - let base = self.char_props(&t.first_style(), space); + let base = self.char_props(&drawn.first_style(), space); let mut props = base.clone(); let (from, to) = t.kind.path_span().unwrap_or((start, 1.0)); // The anchor sits where the layout aligns the line within its span. @@ -556,10 +572,17 @@ impl Writer<'_> { let a = self.attrs(&props); let offset = fmt_num(at * 100.0, 3); let mut s = format!(""); - for run in &t.runs { + let plain = drawn.plain_text(); + let first = drawn.runs.iter().position(|r| !r.text.is_empty()); + for (i, run) in drawn.runs.iter().enumerate() { let mut diff = run_diff(&base, self.char_props(&run.style, space)); diff.extend(direction_props(&run.style)); - let a = self.attrs(&diff); + let mut a = self.attrs(&diff); + // The space before the first character (`kerningBefore`) moves it along the path. + let before = if first == Some(i) { vectorcraft_text::line_start_space(&plain, 0, &run.style, false) } else { 0.0 }; + if before != 0.0 && before.is_finite() { + a.push_str(&format!(" dx=\"{}\"", fmt_num(before, self.opts.decimals))); + } s.push_str(&format!("{}", xml_text(&run.text.replace('\n', " ")))); } s.push_str(""); @@ -690,8 +713,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let split_words = !fewer && !matches!(style.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right); // Each cluster's advance and drawing offset as a reader gives them, by its byte offset. // Justification…'s Desired word and letter spacing and glyph scaling move characters from - // where a reader draws them, on every line. - let spaced = !fewer && !style.justification.desired_is_default(); + // where a reader draws them, on every line (Block's word gap among them). + let spaced = !fewer && !t.layout_justification(style).desired_is_default(); let reader = if split_words || spaced || (!fewer && !style.mojikumi.is_none()) { Some(&*kerned.get_or_insert_with(|| reader_advances(t, lay, true))) } else { @@ -748,6 +771,14 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let x = g.xf.translation().x - offset; (advance, if (x - g.origin.x).abs() > PLACE_TOLERANCE { x } else { g.origin.x }) } + // The space before a line's first character (`kerningBefore`) is in its advance and + // moves it along the line: a reader sets it that far along, without it. (Shrink + // Text to Fit scales it with the sizes.) + None if !lay.vertical && !g.rtl && g.len > 0 && run.style.kerning_before != 0.0 => { + let before = vectorcraft_text::line_start_space(&plain, g.byte, &run.style, false) * lay.fit_scale; + let before = if before.is_finite() { before } else { 0.0 }; + (g.advance - before, g.origin.x + before) + } None => (g.advance, g.origin.x), }; let src: String = source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(); @@ -835,10 +866,13 @@ fn reader_advances(t: &TextObject, lay: &vectorcraft_text::TextLayout, kerning: // A reader spaces words and letters as the font does. p.justification = vectorcraft_doc::JustificationOptions::default(); } - if !kerning { - for r in &mut set.runs { + for r in &mut set.runs { + if !kerning { r.style.kerning.get_or_insert(0.0); } + // A reader puts no space before a line's first character (`kerningBefore`): the segment + // starts that much further along instead. + r.style.kerning_before = 0.0; } let relaid; let glyphs = if set == *t { diff --git a/crates/svg/src/glyph.rs b/crates/svg/src/glyph.rs index c019f9b0a8..22697f58a3 100644 --- a/crates/svg/src/glyph.rs +++ b/crates/svg/src/glyph.rs @@ -44,18 +44,20 @@ pub fn glyph_art(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Opti // usvg resolves `context-fill` and `context-stroke` only for markers. let svg = svg.replace("context-fill", &hex(fill)).replace("context-stroke", &stroke.map_or_else(|| "none".into(), hex)); let (doc, _) = crate::import::import(&svg, &ImportOptions::default(), crate::MAX_NODES).ok()?; + // A layer's art, its ruler guides left out. + let art_of = |l: &Node| l.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).cloned().collect::>(); let mut art = if whole { - Node::group(NodeId(0), doc.layers.iter().map(|l| Arc::new(Node::group(NodeId(0), l.children().cloned().unwrap_or_default()))).collect()) + Node::group(NodeId(0), doc.layers.iter().map(|l| Arc::new(Node::group(NodeId(0), art_of(l)))).collect()) } else { // The glyph, top-level, is a layer when a ``, else an object named after its id. let named = |n: &Node| n.name.as_deref() == Some(id.as_str()); match doc.layers.iter().find(|l| named(l)) { - Some(layer) => Node::group(NodeId(0), layer.children().cloned().unwrap_or_default()), + Some(layer) => Node::group(NodeId(0), art_of(layer)), None => { let mut found = None; for layer in &doc.layers { layer.walk(&mut |n| { - if found.is_none() && named(n) { + if found.is_none() && !n.is_ruler_guide() && named(n) { found = Some(n.clone()); } }); @@ -199,7 +201,7 @@ fn own_art(n: &Node, doc: &Document) -> Option { im.pixels = Some(Arc::new(blob.clone())); } if let Some(children) = n.children_mut() { - *children = children.iter().filter_map(|c| own_art(c, doc).map(Arc::new)).collect(); + *children = children.iter().filter(|c| !c.is_ruler_guide()).filter_map(|c| own_art(c, doc).map(Arc::new)).collect(); } Some(n) } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 1e852ee531..47fcfbaf14 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -38,7 +38,7 @@ pub(super) use importer::PT_PER_IN; use importer::SymbolMade; pub(super) use layers::DEFAULT_FONT_SIZE; pub(crate) use layers::SUBLAYER; -use layers::{RootUnits, inkscape_pages, promote_sublayers, root_layer_name}; +use layers::{RootUnits, inkscape_pages, promote_sublayers, root_layer_name, root_title}; pub(super) use prepass::Edits; use prepass::{Extras, labels, prepass}; pub use prepass::{MAX_FOREIGN, MAX_FOREIGN_VALUE}; @@ -158,6 +158,9 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul let k = units.k; let mut doc = Document::new(size.width() as f64 * k, size.height() as f64 * k); doc.units = units.unit; + // The file's own title, when it gives one, is the document's File Info title; the document's + // name stays what `Document::new` gave it, for the caller to name after the file. + doc.metadata.title = root_title(xml.root_element()); let mut im = Importer { doc, warnings, diff --git a/crates/svg/src/import/depth.rs b/crates/svg/src/import/depth.rs index 2cdccc9dad..0586deaf6f 100644 --- a/crates/svg/src/import/depth.rs +++ b/crates/svg/src/import/depth.rs @@ -220,7 +220,14 @@ fn prescan_with(svg: &str, most: usize) -> Prescan<'_> { /// `most`. Without recursion. pub(super) fn height(xml: &roxmltree::Document, most: usize) -> Option { let elements = || xml.descendants().filter(|n| n.is_element()); - let ids: HashMap<&str, XNode> = elements().filter_map(|n| Some((n.attribute("id")?, n))).collect(); + // The first element of an id, as usvg resolves references: a later one of the same id would + // hide a deep target behind a shallow one. + let mut ids: HashMap<&str, XNode> = HashMap::new(); + for n in elements() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } let css = Styles::new(xml); // How deep each element's own tree goes, itself included; 0 while it is being worked out: a // reference back to it then is a loop, which usvg leaves out. @@ -394,6 +401,16 @@ mod tests { assert!(!deep(&svg(&format!("{defs}{art}")))); } + #[test] + fn a_reference_follows_the_first_element_of_its_id() { + // A chain of ``s as deep as the cap, each link's id given again later to an empty group: + // usvg follows the first, so the chain is deep. + let chain: String = (1..MAX_ELEMENT_DEPTH).map(|i| format!("", i - 1)).collect(); + let shallow: String = (1..MAX_ELEMENT_DEPTH).map(|i| format!("")).collect(); + let top = format!("", MAX_ELEMENT_DEPTH - 1); + assert!(deep(&svg(&format!("{chain}{shallow}{top}")))); + } + #[test] fn a_loop_of_references_is_not_deep() { assert!(!deep(&svg(""))); diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 9de3bebcdf..1a4c06f0e6 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -49,11 +49,12 @@ pub(in crate::import) struct Files { /// How usvg holds the bytes of a raster of one format (`ImageKind::PNG`…). type RasterKind = fn(Arc>) -> ImageKind; +#[derive(Clone)] enum Source { /// A raster file of the kind usvg reads it as. Raster(RasterKind, Arc>), /// An SVG file's text (unpacked when it is SVGZ), parsed by usvg as an image. - Svg(String), + Svg(Arc), } /// A linked raster image (or the placeholder of a missing one). @@ -133,14 +134,29 @@ impl Files { pub(in crate::import) fn read(svg: &str, xml: &roxmltree::Document, opts: &ImportOptions, edits: &mut Edits, warnings: &mut Vec) -> Self { let mut files = Files::default(); let mut placeholder = None; + // What each file read gave, by the file: hrefs spelled differently (`a.png`, `./a.png`, + // `%61.png`) share one read and one copy of its bytes. + let mut by_file: HashMap> = HashMap::new(); for n in xml.descendants().filter(|n| n.is_element() && n.tag_name().name() == "image") { let Some(h) = href(n).filter(|h| !h.trim_start().starts_with("data:")) else { continue }; if !files.sources.contains_key(h) { let (path, file) = target(h, opts.folder); - let read = file.and_then(|file| opts.read.and_then(|read| read(&file))); - let source = match read { - Some((bytes, link)) => files.source(bytes, link).ok_or("is not an image VectorCraft reads"), - None => Err("not found"), + // A failed read is cached too, but each href gets its own placeholder: its own link + // path (an Arc shared between hrefs would share the first href's link) and warning. + let cached = file.as_ref().and_then(|f| by_file.get(f)).cloned(); + let source = match cached { + Some(source) => source, + None => { + let read = file.clone().and_then(|file| opts.read.and_then(|read| read(&file))); + let source = match read { + Some((bytes, link)) => files.source(bytes, link).ok_or("is not an image VectorCraft reads"), + None => Err("not found"), + }; + if let Some(file) = file { + by_file.insert(file, source.clone()); + } + source + } }; let source = source.or_else(|why| { warnings.push(format!("linked image '{h}' {why}: a placeholder keeps its place until it is relinked")); @@ -164,7 +180,7 @@ impl Files { let Ok(format) = image::guess_format(&bytes) else { // Unpacked once, here, within what the SVGZ images may unpack to. let text = crate::text_within(&bytes, &self.unpacked).ok()?; - return text.contains(">) { if art.is_empty() { return; } if let NodeKind::Layer { children, clip: clip @ true, .. } = &mut l.kind { *clip = false; - let clipped = std::mem::take(children); + let mut clipped = std::mem::take(children); + let guides = clipped.split_off(Node::guide_run_start(&clipped)); if let Some(group) = self.named("", NodeKind::Group { children: clipped, clip: true }) { children.push(Arc::new(group)); } + children.extend(guides); } if let Some(ch) = l.children_mut() { - let i = index.min(ch.len()); + let i = index.min(Node::guide_run_start(ch)); ch.splice(i..i, art); } } diff --git a/crates/svg/src/import/layers.rs b/crates/svg/src/import/layers.rs index 15a77e37f0..a6d6a46b30 100644 --- a/crates/svg/src/import/layers.rs +++ b/crates/svg/src/import/layers.rs @@ -16,6 +16,16 @@ pub(super) fn root_layer_name(root: XNode) -> Option { root.attribute("data-name").or(id).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string) } +/// The title the file gives root element `root`: the text of its first `` child (the one +/// SVG 1.1 §5.4 and SVG 2 §5.4 give a document or element; a `<title>` inside a shape or group is +/// that element's tooltip, not the document's), its runs of white space made single spaces. `None` +/// without one, or when it is blank. +pub(super) fn root_title(root: XNode) -> Option<String> { + let title = root.children().find(|c| c.is_element() && c.tag_name().name() == "title" && c.tag_name().namespace() == Some(super::SVG_NS))?; + let text: Vec<&str> = title.descendants().filter_map(|n| n.text().filter(|_| n.is_text())).flat_map(str::split_whitespace).collect(); + (!text.is_empty()).then(|| text.join(" ")) +} + /// Is element `g` a `<g>` marked as a layer ([`SUBLAYER`])? Only one with an id counts: the id (or /// the label beside it) is its name. pub(super) fn marked_layer(g: XNode) -> bool { diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 904b76cd13..52b6663906 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -51,6 +51,10 @@ const SVG_NS: &str = "http://www.w3.org/2000/svg"; /// Most line breaks one absolutely positioned character adds before itself. const MAX_LINE_GAP: f64 = 10_000.0; +/// Most blank lines (breaks past the first newline of each gap) the absolutely positioned +/// characters of one text add in all: past it, a gap is one break as wide as the gap. +const MAX_LINE_BREAKS: usize = 10_000; + /// A whitespace/comma separated list. fn list(v: &str) -> impl Iterator<Item = &str> { v.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()) @@ -1060,6 +1064,7 @@ impl Ctx { } else if obj.plain_text().split('\n').any(|p| vectorcraft_text::paragraph_is_rtl(p, None)) { obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::LeftToRight)); } + keep_reader_anchors(&mut obj); // The placeholder covers the text (laid out when a paint server needs its bounding box). let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default(); let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); @@ -1154,6 +1159,12 @@ fn justify_of(anchor: f64) -> Justify { } } +/// How far a line's leading may differ from its spacing and still count as it: 0.01 absolute, but +/// never more than a thousandth of the spacing itself (tiny type has tiny gaps). +fn leading_tolerance(spacing: f64) -> f64 { + 0.01_f64.min(spacing.abs() * 1e-3) +} + /// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the /// justification, the x of the first line's left (or anchor) edge and, when no character is /// placed on its own, each line's first character and anchor x. @@ -1174,6 +1185,7 @@ fn lines( // Line starts (first character, anchor x) and absolutely placed characters (index, x). let mut lines = vec![(0, x0)]; let mut targets: Vec<(usize, f64)> = vec![]; + let mut added = 0usize; for i in 1..n { let ny = y[i].unwrap_or(cur) + dy[i]; let lead = cells[i].style.effective_leading(); @@ -1182,7 +1194,9 @@ fn lines( // Whole multiples of the auto leading add blank lines (not without limit: a far-off y // mustn't ask for billions); other spacing is one break. let count = (gap / lead).round().clamp(1.0, MAX_LINE_GAP); - let count = if (gap / count - lead).abs() <= lead * 0.05 { count } else { 1.0 }; + // The first newline just ends the previous line: only the others are blank lines. + let count = if (gap / count - lead).abs() <= lead * 0.05 && added + (count as usize - 1) <= MAX_LINE_BREAKS { count } else { 1.0 }; + added += count as usize - 1; breaks.push(Break { at: i, count: count as usize, leading: gap / count }); lines.push((i, ax + dx[i])); (base, cur) = (ny, ny); @@ -1198,7 +1212,8 @@ fn lines( // A line's characters take its spacing as leading unless it is their auto leading. for (k, b) in breaks.iter().enumerate() { let end = breaks.get(k + 1).map_or(n, |nb| nb.at); - if cells[b.at..end].iter().any(|c| (c.style.effective_leading() - b.leading).abs() > 0.01) { + let tolerance = leading_tolerance(b.leading); + if cells[b.at..end].iter().any(|c| (c.style.effective_leading() - b.leading).abs() > tolerance) { for c in &mut cells[b.at..end] { c.style.leading = Some(b.leading); } @@ -1264,6 +1279,55 @@ fn lines( (Justify::Left, left, None) } +/// Centred and right-aligned lines of point type `obj` where a reader draws them. `text-anchor` +/// aligns a line's advance, which ends after the letter spacing of its last character (SVG +/// export anchors lines so); VectorCraft aligns a line without that tracking +/// ([`vectorcraft_text::LineInfo::trailing`]). Each such line moves back by its share of it: the +/// type moves when every line moves alike, otherwise each paragraph's right indent takes the +/// tracking (a line of imported point type is a paragraph). Browsers add that letter spacing +/// today; CSS WG issue 1518 and Firefox bugs 1907305 and 1913554 may drop it at a line's end. +fn keep_reader_anchors(obj: &mut TextObject) { + let share = |j: Justify| match j { + Justify::Center => 0.5, + Justify::Right => 1.0, + _ => 0.0, + }; + // Laid out only when a line may move: tracked type with a centred or right-aligned paragraph. + if !matches!(obj.kind, TextKind::Point) + || obj.vertical + || obj.runs.iter().all(|r| r.style.tracking == 0.0) + || obj.paragraph_styles().iter().all(|p| share(p.justify) == 0.0) + { + return; + } + let plain = obj.plain_text(); + // Each line's paragraph, its tracking left out and how far that moves it. + let lines: Vec<(usize, f64, f64)> = measure(obj) + .lines + .iter() + .map(|l| { + let para = plain.get(..l.start).map_or(0, |before| before.matches('\n').count()); + let trailing = if l.trailing.is_finite() { l.trailing } else { 0.0 }; + (para, trailing, share(obj.para_at(para).justify) * trailing) + }) + .collect(); + let Some(&(_, _, first)) = lines.first() else { return }; + if first == 0.0 && lines.iter().all(|l| l.2 == 0.0) { + return; + } + if lines.iter().all(|l| (l.2 - first).abs() < 1e-9) { + obj.xf *= Affine::translate((-first, 0.0)); + return; + } + let mut styles = obj.paragraph_styles(); + for &(para, trailing, moves) in &lines { + if let Some(style) = styles.get_mut(para).filter(|_| moves != 0.0) { + style.right_indent += trailing; + } + } + obj.set_paragraph_styles(styles); +} + /// A left-aligned point text of `runs` at the origin (for measuring). fn with_runs(runs: Vec<TextRun>) -> TextObject { let mut t = TextObject::point(Point::ZERO, "", CharStyle::default()); @@ -1322,7 +1386,7 @@ fn assemble(cells: &[Cell], breaks: &[Break]) -> (Runs, Vec<usize>) { let key = (prev.fill, prev.stroke); push(&mut out, '\n', prev.final_style(), key); let mut blank = prev.final_style(); - if (blank.effective_leading() - b.leading).abs() > 0.01 { + if (blank.effective_leading() - b.leading).abs() > leading_tolerance(b.leading) { blank.leading = Some(b.leading); } for _ in 1..b.count { diff --git a/crates/svg/tests/it/conic.rs b/crates/svg/tests/it/conic.rs new file mode 100644 index 0000000000..ce8ae1216b --- /dev/null +++ b/crates/svg/tests/it/conic.rs @@ -0,0 +1,84 @@ +//! Conic gradients, which SVG has no element for: fills and strokes of opaque stops are written +//! as solid wedges around the center clipped to the shape (or the stroke's outline), others as an +//! image, with a warning; read back, the SVG looks as the canvas paints the gradient, its seam +//! still sharp. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_svg::{ExportOptions, export_full, import}; +use vectorcraft_testkit::raster::{assert_similar, render_artboard}; + +/// `gradient` (white to black when `None`), sweeping clockwise from the right around (100, 80). +fn conic(gradient: Option<Gradient>) -> Paint { + let mut g = GradientPaint::new(gradient.unwrap_or(Gradient { kind: GradientKind::Conic, ..Gradient::default() })); + g.geom = Some(GradientGeom { start: Point::new(100.0, 80.0), end: Point::new(160.0, 80.0), aspect: 1.0, focal: None }); + Paint::Gradient(Box::new(g)) +} + +/// A 200 × 160 document holding `n`. +fn doc_with(mut n: Node) -> Document { + let mut d = Document::new(200.0, 160.0); + n.id = d.alloc_id(); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +#[test] +fn a_conic_fill_is_solid_wedges_clipped_to_the_shape() { + let shape = shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 150.0)); + let d = doc_with(Node::path(NodeId(0), shape, Appearance::basic(conic(None), Paint::None, 0.0))); + let o = export_full(&d, &ExportOptions::default(), None); + assert!(!o.svg.contains("Gradient") && !o.svg.contains("<image "), "no gradient element or image stands in"); + assert!(o.svg.contains("<clipPath"), "clipped to the shape"); + assert_eq!(o.svg.matches(" fill=\"#").count(), 360, "a wedge a degree"); + assert!(o.warnings.iter().any(|w| w.contains("conic gradients are written as solid wedges")), "{:?}", o.warnings); + // Read back, it looks as the canvas paints the gradient, the seam (right of the center) too. + let (canvas, back) = (render_artboard(&d), render_artboard(&import(&o.svg).unwrap())); + assert_similar(&canvas, &back, 6.0, 0.01); + for (x, y) in [(150, 82), (150, 77), (100, 130), (50, 80), (100, 30)] { + let (a, b) = (canvas.over_white(x, y), back.over_white(x, y)); + assert!(a[0].abs_diff(b[0]) <= 6, "({x},{y}): {a:?} vs {b:?}"); + } +} + +#[test] +fn a_conic_stroke_is_wedges_clipped_to_the_stroke_outline() { + let shape = shapes::rectangle(Rect::new(30.0, 30.0, 170.0, 130.0)); + let d = doc_with(Node::path(NodeId(0), shape, Appearance::basic(Paint::None, conic(None), 12.0))); + let o = export_full(&d, &ExportOptions::default(), None); + assert!(o.svg.contains("<clipPath") && !o.svg.contains("Gradient"), "{}", o.svg); + assert_similar(&render_artboard(&d), &render_artboard(&import(&o.svg).unwrap()), 8.0, 0.01); +} + +/// Translucent stops (wedges drawn over each other would add up their opacity), dither and the +/// Perceptual method give an image of the sweep clipped to the shape. +#[test] +fn a_conic_that_wedges_cannot_draw_is_an_image() { + let mut clear = GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)); + clear.opacity = 0.0; + let translucent = Gradient::new(GradientKind::Conic, vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), clear]); + let dithered = Gradient { dither: true, ..Gradient { kind: GradientKind::Conic, ..Gradient::default() } }; + let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient { kind: GradientKind::Conic, ..Gradient::default() } }; + for g in [translucent, dithered, perceptual] { + let shape = shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 140.0)); + let d = doc_with(Node::path(NodeId(0), shape, Appearance::basic(conic(Some(g.clone())), Paint::None, 0.0))); + let o = export_full(&d, &ExportOptions::default(), None); + assert_eq!(o.svg.matches("<image ").count(), 1, "{g:?}"); + assert!(o.warnings.iter().any(|w| w.contains("conic") && w.contains("images")), "{:?}", o.warnings); + assert_similar(&render_artboard(&d), &render_artboard(&import(&o.svg).unwrap()), 12.0, 0.02); + } +} + +/// A conic on characters, which SVG paints with a gradient element, is a linear gradient, with a +/// warning. +#[test] +fn a_conic_on_characters_is_written_linear() { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + let st = CharStyle { fill: conic(None), size: 48.0, ..CharStyle::default() }; + let d = doc_with(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 80.0), "Sweep", st))))); + let o = export_full(&d, &ExportOptions::default(), None); + assert!(o.svg.contains("<linearGradient"), "{}", o.svg); + assert!(o.warnings.iter().any(|w| w.contains("conic gradients on characters")), "{:?}", o.warnings); +} diff --git a/crates/svg/tests/it/css_rules.rs b/crates/svg/tests/it/css_rules.rs index 88e96cddf5..0c1af2d287 100644 --- a/crates/svg/tests/it/css_rules.rs +++ b/crates/svg/tests/it/css_rules.rs @@ -284,6 +284,57 @@ fn gradients_give_css_gradients() { assert!(bg.starts_with("radial-gradient(circle ") && bg.contains(" at 50px 50px, #ffffff 0%, #000000 100%)"), "{bg}"); } +/// A conic gradient is a CSS conic gradient (CSS turns clockwise from straight up): from where +/// the vector points, at the center. A mirrored one has its stops mirrored about the seam, and an +/// elliptical one is written circular, with a warning. +#[test] +fn conic_gradients_give_css_conic_gradients() { + let mut d = doc(); + let conic = |geom: Option<GradientGeom>| { + let mut g = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..Gradient::default() }); + g.geom = geom; + Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 0.0) + }; + let mut n = rect(&mut d, (0.0, 0.0, 100.0, 60.0), 0.0); + n.appearance = conic(None).into(); + let id = add(&mut d, n); + assert_eq!( + prop(&one(&d, id, &CssOptions::default()), "background-image"), + Some("conic-gradient(from 90deg at 50px 30px, #ffffff 0%, #000000 100%)") + ); + // Pointing straight up and mirrored: it sweeps counterclockwise, so black comes first clockwise. + let mut n = rect(&mut d, (0.0, 0.0, 100.0, 60.0), 0.0); + n.appearance = conic(Some(GradientGeom { start: Point::new(40.0, 30.0), end: Point::new(40.0, 0.0), aspect: -1.0, focal: None })).into(); + let id = add(&mut d, n); + assert_eq!( + prop(&one(&d, id, &CssOptions::default()), "background-image"), + Some("conic-gradient(from 0deg at 40px 30px, #000000 0%, #ffffff 100%)") + ); + let mut n = rect(&mut d, (0.0, 0.0, 100.0, 60.0), 0.0); + n.appearance = conic(Some(GradientGeom { start: Point::new(40.0, 30.0), end: Point::new(70.0, 30.0), aspect: 0.5, focal: None })).into(); + let id = add(&mut d, n); + let sheet = css_rules(&d, &[id], &CssOptions::default()); + assert!(sheet.warnings.iter().any(|w| w.contains("conic gradients are written circular")), "{:?}", sheet.warnings); +} + +/// CSS has no diamond gradient: a diamond is the radial gradient through its square's corners (its +/// vector, and the aspect across it), at its center, with a warning. +#[test] +fn diamond_gradients_give_css_radial_gradients_through_their_corners() { + let mut d = doc(); + let mut g = GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() }); + g.geom = Some(GradientGeom { start: Point::new(40.0, 30.0), end: Point::new(70.0, 30.0), aspect: 0.5, focal: None }); + let mut n = rect(&mut d, (0.0, 0.0, 100.0, 60.0), 0.0); + n.appearance = Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 0.0).into(); + let id = add(&mut d, n); + let sheet = css_rules(&d, &[id], &CssOptions::default()); + assert!(sheet.warnings.iter().any(|w| w.contains("diamond gradients are written as radial gradients")), "{:?}", sheet.warnings); + assert_eq!( + prop(&one(&d, id, &CssOptions::default()), "background-image"), + Some("radial-gradient(ellipse 30px 15px at 40px 30px, #ffffff 0%, #000000 100%)") + ); +} + #[test] fn shadows_and_unsupported_art() { let mut d = doc(); diff --git a/crates/svg/tests/it/diamond.rs b/crates/svg/tests/it/diamond.rs new file mode 100644 index 0000000000..822cf5faf1 --- /dev/null +++ b/crates/svg/tests/it/diamond.rs @@ -0,0 +1,146 @@ +//! Diamond gradients, which SVG has no element for: fills and strokes of opaque stops are written +//! as four linear gradients, one for each quadrant of the diamond's frame, clipped to the shape +//! (or the stroke's outline), others as an image, with a warning; read back, the SVG looks as the +//! canvas paints the gradient. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Point, Rect, shapes}; +use vectorcraft_svg::{ExportOptions, export_full, import}; +use vectorcraft_testkit::raster::{assert_similar, render_artboard}; + +/// `gradient` (red to blue when `None`), from (100, 80) out to a square turned and stretched +/// across its vector. +fn diamond(gradient: Option<Gradient>) -> Paint { + let ramp = Gradient::new( + GradientKind::Diamond, + vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))], + ); + let mut g = GradientPaint::new(gradient.unwrap_or(ramp)); + g.geom = Some(GradientGeom { start: Point::new(100.0, 80.0), end: Point::new(150.0, 50.0), aspect: 0.7, focal: None }); + g.swatch = Some("Gem".into()); + Paint::Gradient(Box::new(g)) +} + +/// A 200 × 160 document holding `n`. +fn doc_with(mut n: Node) -> Document { + let mut d = Document::new(200.0, 160.0); + n.id = d.alloc_id(); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +#[test] +fn a_diamond_fill_is_four_linear_gradients_clipped_to_the_shape() { + let shape = shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 150.0)); + let d = doc_with(Node::path(NodeId(0), shape, Appearance::basic(diamond(None), Paint::None, 0.0))); + let o = export_full(&d, &ExportOptions::default(), None); + assert_eq!(o.svg.matches("<linearGradient").count(), 4, "{}", o.svg); + assert!(!o.svg.contains("<radialGradient") && !o.svg.contains("<image "), "no stand-in"); + assert!(o.svg.contains("<clipPath"), "clipped to the shape"); + // Not named after the swatch: none of the four is its gradient. + assert!(!o.svg.contains("id=\"Gem"), "{}", o.svg); + assert!(o.warnings.iter().any(|w| w.contains("diamond gradients are written as four linear gradients")), "{:?}", o.warnings); + // Read back, it looks as the canvas paints the gradient, with no hairline between quadrants. + assert_similar(&render_artboard(&d), &render_artboard(&import(&o.svg).unwrap()), 4.0, 0.01); +} + +#[test] +fn a_diamond_stroke_is_four_linear_gradients_clipped_to_the_stroke_outline() { + let shape = shapes::rectangle(Rect::new(30.0, 30.0, 170.0, 130.0)); + let d = doc_with(Node::path(NodeId(0), shape, Appearance::basic(Paint::None, diamond(None), 12.0))); + let o = export_full(&d, &ExportOptions::default(), None); + assert!(o.svg.contains("<clipPath") && o.svg.matches("<linearGradient").count() == 4, "{}", o.svg); + assert_similar(&render_artboard(&d), &render_artboard(&import(&o.svg).unwrap()), 8.0, 0.01); +} + +/// A stroke's miter reaches past its paint box (the path's box grown by half the weight): the +/// quadrants of a diamond, the image of a Perceptual one and the wedges of a conic gradient cover +/// it, and read back it is painted as the canvas paints it. +#[test] +fn a_stroke_past_its_paint_box_is_painted_to_its_tip() { + // The center lies below the art, so the miter's tip is farther from it than any corner of the + // paint box. + let c = Point::new(100.0, 200.0); + let geom = GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(200.0, 0.0), aspect: 1.0, focal: None }; + let ramp = |kind, method| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let mut g = GradientPaint::new(Gradient { method, ..Gradient::new(kind, stops) }); + g.geom = Some(geom); + Paint::Gradient(Box::new(g)) + }; + let mut wrong = vec![]; + for (case, paint) in [ + ("diamond", ramp(GradientKind::Diamond, GradientMethod::Classic)), + ("perceptual diamond", ramp(GradientKind::Diamond, GradientMethod::Perceptual)), + ("conic", ramp(GradientKind::Conic, GradientMethod::Classic)), + ] { + let mut ap = Appearance::basic(Paint::None, paint, 8.0); + for it in &mut ap.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = it { + s.miter_limit = 10.0; + } + } + // The miter's tip runs up to y 23.5; the paint box starts at y 36. Rows 30 and 31 are + // covered across pixel column 100. + let peak = vectorcraft_geom::SubPath::polyline(&[Point::new(85.0, 100.0), Point::new(100.0, 40.0), Point::new(115.0, 100.0)], false); + let d = doc_with(Node::path(NodeId(0), vectorcraft_geom::PathData::single(peak), ap)); + let o = export_full(&d, &ExportOptions::default(), None); + let (want, got) = (render_artboard(&d), render_artboard(&import(&o.svg).unwrap())); + for y in [30, 31] { + let (a, b) = (want.over_white(100, y), got.over_white(100, y)); + assert!(a[0] < 200, "{case} at y {y}: the canvas paints the tip: {a:?}"); + if !a.iter().zip(b).all(|(p, q)| p.abs_diff(q) <= 12) { + wrong.push(format!("{case} at y {y}: {a:?} vs {b:?}")); + } + } + } + assert!(wrong.is_empty(), "{wrong:?}"); +} + +/// Translucent stops (the overlapping quadrants would add up their opacity), dither, the +/// Perceptual method and a diamond without an extent give an image clipped to the shape. +#[test] +fn a_diamond_that_quadrants_cannot_draw_is_an_image() { + let mut clear = GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)); + clear.opacity = 0.0; + let ramp = || Gradient::new(GradientKind::Diamond, vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::BLACK)]); + let translucent = Gradient::new(GradientKind::Diamond, vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), clear]); + let dithered = Gradient { dither: true, ..ramp() }; + let perceptual = Gradient { method: GradientMethod::Perceptual, ..ramp() }; + let flat = { + let Paint::Gradient(mut g) = diamond(None) else { panic!("a gradient") }; + g.geom = g.geom.map(|geom| GradientGeom { aspect: 0.0, ..geom }); + Paint::Gradient(g) + }; + for (case, paint) in [ + ("translucent", diamond(Some(translucent))), + ("dithered", diamond(Some(dithered))), + ("perceptual", diamond(Some(perceptual))), + ("flat", flat), + ] { + let shape = shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 140.0)); + let d = doc_with(Node::path(NodeId(0), shape, Appearance::basic(paint, Paint::None, 0.0))); + let o = export_full(&d, &ExportOptions::default(), None); + assert_eq!(o.svg.matches("<image ").count(), 1, "{case}"); + assert!(o.warnings.iter().any(|w| w.contains("diamond") && w.contains("images")), "{case}: {:?}", o.warnings); + assert_similar(&render_artboard(&d), &render_artboard(&import(&o.svg).unwrap()), 12.0, 0.02); + } +} + +/// A diamond on characters, which SVG paints with a gradient element, is the radial gradient +/// through its corners, with a warning, centered even when the diamond carries a focal point (a +/// plug-in's or a file's, which a diamond doesn't draw). +#[test] +fn a_diamond_on_characters_is_written_radial() { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + let Paint::Gradient(mut g) = diamond(None) else { panic!("a gradient") }; + g.geom = g.geom.map(|geom| GradientGeom { focal: Some(Point::new(110.0, 75.0)), ..geom }); + let st = CharStyle { fill: Paint::Gradient(g), size: 48.0, ..CharStyle::default() }; + let d = doc_with(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 80.0), "Gem", st))))); + let o = export_full(&d, &ExportOptions::default(), None); + assert!(o.svg.contains("<radialGradient"), "{}", o.svg); + assert!(!o.svg.contains(" fx=\""), "{}", o.svg); + assert!(o.warnings.iter().any(|w| w.contains("diamond gradients on characters")), "{:?}", o.warnings); +} diff --git a/crates/svg/tests/it/ids.rs b/crates/svg/tests/it/ids.rs index 0781397fa3..c41dd4bcf7 100644 --- a/crates/svg/tests/it/ids.rs +++ b/crates/svg/tests/it/ids.rs @@ -159,3 +159,21 @@ fn unique_ids_differ_when_only_gradient_stops_differ() { assert!(!ids1.is_empty() && !ids2.is_empty()); assert!(ids1.iter().all(|id| !ids2.contains(id)), "IDs must not collide: {ids1:?} vs {ids2:?}"); } + +/// Ruler guides on each layer, named as a layer and an object above them are, with a URL, are not +/// written: the SVG is the same as without them, with every kind of object id. +#[test] +fn ruler_guides_are_not_written_and_take_no_id() { + let plain = doc("a", 0.0); + let mut guided = plain.clone(); + for (i, (l, name)) in [(guided.layers[0].id, "Top & Front"), (guided.layers[1].id, "Logo mark (v2)")].into_iter().enumerate() { + let mut g = Node::new(guided.alloc_id(), vectorcraft_doc::NodeKind::RulerGuide { vertical: i == 0, pos: 30.0, artboard: None }); + g.name = Some(name.into()); + g.edit_attrs(|a| a.url = "https://example.com/".into()); + guided.insert(Some(l), usize::MAX, g).unwrap(); + } + for object_ids in [ObjectIds::LayerNames, ObjectIds::Minimal, ObjectIds::Unique] { + let opts = ExportOptions { object_ids, ..Default::default() }; + assert_eq!(export(&guided, &opts), export(&plain, &opts), "{object_ids:?}"); + } +} diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 10418f3441..d6983a1ce2 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -88,6 +88,23 @@ fn a_linked_png_resolves_against_the_svg_folder_and_stays_linked() { assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 20.0).abs() < 1e-6 && (b.width() - 80.0).abs() < 1e-6, "{b:?}"); } +#[test] +fn hrefs_spelling_one_file_differently_read_it_once() { + let dir = folder("spellings"); + std::fs::write(dir.join("img").join("a.png"), png(4, 4)).unwrap(); + let reads = std::sync::atomic::AtomicUsize::new(0); + let counting = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + read(path) + }; + let folder = dir.to_string_lossy(); + let body = r#"<image href="img/a.png" width="4" height="4"/><image href="./img/a.png" width="4" height="4"/><image href="img/%61.png" width="4" height="4"/>"#; + let (d, w) = import_with(&svg(body), &ImportOptions { folder: Some(&folder), read: Some(&counting) }).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(images(&d).len(), 3); + assert_eq!(reads.into_inner(), 1, "one read for the three spellings"); +} + #[test] fn a_missing_link_warns_and_keeps_a_placeholder_in_its_box() { let dir = folder("missing"); @@ -139,6 +156,26 @@ fn files_with_the_same_pixels_have_keys_of_their_own() { assert_eq!(*d.images[&b.key].bytes, bytes); } +#[test] +fn hrefs_spelling_one_missing_file_differently_each_warn_and_keep_their_own_link() { + let dir = folder("missing_twice"); + let reads = std::sync::atomic::AtomicUsize::new(0); + let counting = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + read(path) + }; + let folder = dir.to_string_lossy(); + let body = r#"<image href="img/gone.png" width="4" height="4"/><image href="./img/gone.png" width="4" height="4"/>"#; + let (d, w) = import_with(&svg(body), &ImportOptions { folder: Some(&folder), read: Some(&counting) }).unwrap(); + assert_eq!(w.iter().filter(|w| w.contains("gone.png") && w.contains("not found")).count(), 2, "{w:?}"); + assert_eq!(reads.into_inner(), 1, "the failed read is cached"); + let found = images(&d); + assert_eq!(found.len(), 2); + for (_, im) in found { + assert_eq!(Path::new(&im.link.as_ref().unwrap().path), dir.join("img").join("gone.png")); + } +} + #[test] fn svg_images_import_as_vector_art() { let dir = folder("svgimage"); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index a30bc193b0..8b0d0338c6 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -245,6 +245,57 @@ fn per_character_positions_with_middle_anchor() { assert!(close(mid(0), 50.0, 0.05) && close(mid(1), 100.0, 0.05), "{} {}", mid(0), mid(1)); } +/// `text-anchor` aligns a line's advance, which ends after its last character's letter spacing, +/// and VectorCraft aligns a line without that tracking: the imported lines move back by their +/// share of it and stay where a reader draws them, and a centred or right-aligned tracked line +/// exported and read back stays where it was (export anchors lines the same way). +#[test] +fn anchored_letter_spaced_lines_stay_where_a_reader_draws_them() { + let starts = |t: &TextObject| { + let lay = layout(FontDb::global(), t); + lay.lines.iter().map(|l| (t.xf * lay.glyphs[l.glyph_start].origin).x).collect::<Vec<_>>() + }; + let advances = |t: &TextObject| { + let lay = layout(FontDb::global(), t); + lay.lines.iter().map(|l| lay.glyphs[l.glyph_start..l.glyph_end].iter().map(|g| g.advance).sum::<f64>()).collect::<Vec<_>>() + }; + for (anchor, share) in [("middle", 0.5), ("end", 1.0)] { + let d = open(&format!(r#"<text x="200" y="100" text-anchor="{anchor}" letter-spacing="8" font-size="40">WAVE</text>"#)); + let t = only_text(&d); + let (start, advance) = (starts(t)[0], advances(t)[0]); + assert!(close(start, 200.0 - share * advance, 1e-6), "{anchor}: the line starts at {start}, not {}", 200.0 - share * advance); + let back = import(&vectorcraft_svg::export(&d, &vectorcraft_svg::ExportOptions::default())).unwrap(); + let again = starts(only_text(&back))[0]; + assert!(close(again, start, 1e-6), "{anchor}: read back, the line starts at {again}, not {start}"); + } + // Lines anchored differently: each moves by its own share. + let d = open( + r#"<text y="100" font-size="20" letter-spacing="4"><tspan x="200" text-anchor="middle">Wave</tspan><tspan x="200" dy="30" text-anchor="end">Line</tspan></text>"#, + ); + let t = only_text(&d); + let (s, a) = (starts(t), advances(t)); + assert!(close(s[0], 200.0 - a[0] / 2.0, 1e-6) && close(s[1], 200.0 - a[1], 1e-6), "{s:?} {a:?}"); +} + +#[test] +fn a_small_line_gap_in_tiny_type_keeps_its_leading() { + // 0.0085 against an auto leading of 0.006 differs by less than 0.01 but is not a whole multiple of it. + let d = open(r#"<text x="1" y="1" font-size="0.005">One<tspan x="1" dy="0.0085">Two</tspan></text>"#); + let t = only_text(&d); + let two = t.runs.iter().find(|r| r.text.contains("Two")).unwrap().style.leading; + assert!(two.is_some_and(|l| close(l, 0.0085, 1e-9)), "{two:?}"); +} + +#[test] +fn blank_lines_in_tiny_type_keep_their_own_spacing() { + // B sits 0.0085 below A (kept as its leading); C is three 0.006 lines below B, so the two blank + // lines between them must be 0.006 apart, not carry B's 0.0085. + let d = open(r#"<text x="1" y="1" font-size="0.005">A<tspan x="1" dy="0.0085">B</tspan><tspan x="1" dy="0.018">C</tspan></text>"#); + let t = only_text(&d); + let blank = t.runs.iter().find(|r| r.text == "\n\n").expect("a run of the two blank lines"); + assert!(blank.style.leading.is_some_and(|l| close(l, 0.006, 1e-9)), "{:?}", blank.style.leading); +} + #[test] fn tspan_lines_dx_and_baseline_shift() { let d = open( diff --git a/crates/svg/tests/it/main.rs b/crates/svg/tests/it/main.rs index 09c175a37a..ac0b2442ec 100644 --- a/crates/svg/tests/it/main.rs +++ b/crates/svg/tests/it/main.rs @@ -7,10 +7,12 @@ mod blend_export; mod clip_text; mod colorized_images; mod colour_glyphs; +mod conic; mod container_export; mod css_rules; mod dash_align; mod data_attributes; +mod diamond; mod effects_export; mod encoding_profile_fonts; mod focal; diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index b13ecf160b..127e47846c 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -909,6 +909,22 @@ fn import_tspan_far_below_is_bounded() { assert!(breaks <= 10_002, "{breaks} line breaks"); } +#[test] +fn import_many_tspans_far_apart_are_bounded_together() { + // Each tspan 9,999 lines (auto leading 14.4 pt) below the last: each within the limit of one gap, + // two hundred of them were two million line breaks. + let spans: String = (1..=200).map(|i| format!(r#"<tspan x="5" y="{}">{i}</tspan>"#, 20.0 + 14.4 * 9_999.0 * i as f64)).collect(); + let d = import_art(&format!( + r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><text x="5" y="20" font-size="12">a{spans}</text></svg>"# + )); + let a = art(&d); + let NodeKind::Text(t) = &a[0].kind else { panic!() }; + let text = t.plain_text(); + assert!(text.ends_with("200"), "{}", &text[text.len().saturating_sub(20)..]); + let breaks = text.matches('\n').count(); + assert!(breaks <= 10_200, "{breaks} line breaks"); +} + #[test] fn import_tspan_on_the_same_baseline_stays_on_the_line() { // Styled runs positioned on the line's own baseline (as Illustrator writes them, with x and y on diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index a031de7412..e858f1ba08 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -109,6 +109,60 @@ fn rich_text_writes_spacing_shift_and_scale() { assert_eq!(attr(tags[1], "y"), attr(tags[0], "y")); } +/// The space before a line's first character (`kerningBefore`, #5111) moves the line's first +/// `<tspan>` to where the character is drawn, left aligned or anchored at a centred line's centre. +#[test] +fn the_space_before_a_lines_first_character_moves_its_tspan() { + let before = CharStyle { kerning_before: 250.0, ..style(12.0) }; + // 250/1000 em of 12 pt: 3 pt. The second paragraph's first character takes it too; the "O" after + // the first "H" is inside its line, so its value does nothing. + let runs = vec![run("HO", before.clone()), run("H\n", style(12.0)), run("H", before.clone()), run("O", style(12.0))]; + let svg = export(&area_doc(runs, 200.0, Justify::Left), &ExportOptions::default()); + // The first <tspan> on each baseline. + let mut starts: Vec<(f64, f64)> = vec![]; + for t in tspans(&svg) { + let (x, y) = (attr(t, "x").unwrap(), attr(t, "y").unwrap()); + if starts.last().is_none_or(|&(_, last)| last != y) { + starts.push((x, y)); + } + } + assert_eq!(starts.iter().map(|s| s.0).collect::<Vec<_>>(), vec![3.0, 3.0], "{svg}"); + // Centred, the line is 3 pt longer and the anchor sits at the middle of what a reader draws. + let svg = export(&area_doc(vec![run("H", before.clone()), run("OH", style(12.0))], 200.0, Justify::Center), &ExportOptions::default()); + let x = tspans(&svg).iter().find_map(|t| attr(t, "x")).unwrap(); + assert!((x - 101.5).abs() < 0.01, "{svg}"); + // A justified line, which a reader's own advances place word by word, starts there too. + let words = vec![run("H", before.clone()), run("OH OH OH OH OH OH OH OH OH OH", style(12.0))]; + let svg = export(&area_doc(words, 90.0, Justify::JustifyLeft), &ExportOptions::default()); + assert_eq!(attr(tspans(&svg)[0], "x"), Some(3.0), "{svg}"); +} + +/// On a path, the space before the first character is its `dx` along the path. One before a +/// character after a line break, which the `<textPath>` can't write, is kept as outlines. +#[test] +fn the_space_before_the_first_character_on_a_path_is_its_dx() { + let doc = |runs: Vec<TextRun>| { + let mut t = TextObject::point(Point::ZERO, "", style(12.0)); + t.runs = runs; + let mut line = BezPath::new(); + line.move_to((20.0, 100.0)); + line.line_to((280.0, 100.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + vectorcraft_svg::export_full(&d, &ExportOptions::default(), None) + }; + let before = CharStyle { kerning_before: 250.0, ..style(12.0) }; + let out = doc(vec![run("HO", before.clone()), run("H", style(12.0))]); + let tags = tspans(&out.svg); + assert!(out.svg.contains("<textPath"), "{}", out.svg); + assert_eq!((attr(tags[0], "dx"), attr(tags[1], "dx")), (Some(3.0), None), "{}", out.svg); + let out = doc(vec![run("HO\n", style(12.0)), run("H", before)]); + assert!(!out.svg.contains("<textPath") && out.warnings.iter().any(|w| w.contains("line break")), "{:?}", out.warnings); +} + /// Proportional Metrics (#966) is written as the `palt` feature, beside the character's own. #[test] fn proportional_metrics_write_palt() { diff --git a/crates/svg/tests/it/title_control_chars.rs b/crates/svg/tests/it/title_control_chars.rs index 3318ed346f..2318eebc67 100644 --- a/crates/svg/tests/it/title_control_chars.rs +++ b/crates/svg/tests/it/title_control_chars.rs @@ -69,3 +69,29 @@ fn dublin_core_metadata_control_chars_are_filtered() { assert!(svg.contains("<dc:subject>kw</dc:subject>")); assert!(svg.contains("<dc:rights>(c) me</dc:rights>")); } + +/// The root's `<title>` is the File Info title of the imported document ([`Document::info_title`]); +/// its name stays what `Document::new` gave it, and a shape's `<title>` is that shape's tooltip. +#[test] +fn the_roots_title_is_the_file_info_title_not_the_documents_name() { + let svg = |inner: &str| { + format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">{inner}<rect width="5" height="5"><title>Tip"#) + }; + let d = import(&svg("\n Access\n paths ")).unwrap(); + assert_eq!((d.title.as_str(), d.metadata.title.as_deref(), d.info_title()), ("Untitled-1", Some("Access paths"), "Access paths")); + for none in [svg(""), svg(" ")] { + let d = import(&none).unwrap(); + assert_eq!((d.title.as_str(), d.metadata.title.as_deref(), d.info_title()), ("Untitled-1", None, "Untitled-1")); + } +} + +/// Exports write the File Info title, where the document has one, in place of its name. +#[test] +fn exports_write_the_file_info_title() { + let mut d = Document::new(200.0, 200.0); + d.title = "box.svg".into(); + d.metadata.title = Some("Access paths".into()); + let svg = export(&d, &ExportOptions { metadata: true, ..ExportOptions::default() }); + assert!(svg.contains("Access paths") && svg.contains("Access paths"), "{svg}"); + assert!(!svg.contains("box.svg"), "{svg}"); +} diff --git a/crates/testkit/src/fixtures.rs b/crates/testkit/src/fixtures.rs index 656bf4a8bb..8deb84a45b 100644 --- a/crates/testkit/src/fixtures.rs +++ b/crates/testkit/src/fixtures.rs @@ -263,20 +263,20 @@ impl DocBuilder { } } -/// All non-layer nodes of a document in paint order. +/// All nodes of a document other than layers and ruler guides, in paint order. pub fn art_nodes(doc: &Document) -> Vec<&Node> { let mut v = Vec::new(); doc.walk(|n| { - if !n.is_layer() { + if !n.is_layer() && !n.is_ruler_guide() { v.push(n) } }); v } -/// Ids of the top-level art (direct children of layers), bottom first. +/// Ids of the top-level art (direct children of layers other than ruler guides), bottom first. pub fn top_level_ids(doc: &Document) -> Vec { - doc.layers.iter().flat_map(|l| l.children().into_iter().flatten().map(|n| n.id)).collect() + doc.layers.iter().flat_map(|l| l.children().into_iter().flatten().filter(|n| !n.is_ruler_guide()).map(|n| n.id)).collect() } /// Every node id (layers included), paint order. diff --git a/crates/testkit/src/invariants.rs b/crates/testkit/src/invariants.rs index c03b33dd53..8791acf428 100644 --- a/crates/testkit/src/invariants.rs +++ b/crates/testkit/src/invariants.rs @@ -3,7 +3,7 @@ use std::collections::HashSet; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind}; use vectorcraft_engine::Session; /// Serialize a document to JSON (the canonical form for equality checks). @@ -11,7 +11,8 @@ pub fn doc_json(doc: &Document) -> Value { serde_json::to_value(doc).expect("document serializes") } -/// Tree invariants: ids unique, `node_count` equals the number of walked nodes, `next_id` above +/// Tree invariants: ids unique, `node_count` equals the number of walked nodes other than ruler +/// guides, ruler guides only at the top of a layer, `next_id` above /// every id, top level made of layers, layers only at the top or inside layers, clip groups have /// a first child, compound children are paths, no image holds its own pixels (the document keeps /// them). @@ -21,11 +22,21 @@ pub fn check_document(doc: &Document) -> Result<(), String> { let mut max = 0u64; let mut err = None; doc.walk(|n| { - walked += 1; + // `node_count` counts objects: ruler guides are left out of it. + walked += usize::from(!n.is_ruler_guide()); max = max.max(n.id.0); if !seen.insert(n.id) && err.is_none() { err = Some(format!("duplicate id {}", n.id)); } + let guides = n.children().map_or(0, |ch| ch.iter().filter(|c| c.is_ruler_guide()).count()); + if guides > 0 && err.is_none() { + let ch = n.children().map(Vec::as_slice).unwrap_or_default(); + if !n.is_layer() { + err = Some(format!("{} holds a ruler guide but is not a layer", n.id)); + } else if ch.len() - Node::guide_run_start(ch) != guides { + err = Some(format!("layer {} has a ruler guide below its art", n.id)); + } + } match &n.kind { NodeKind::Group { children, .. } if children.iter().any(|c| c.is_layer()) && err.is_none() => { err = Some(format!("group {} contains a layer", n.id)); diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 9045a4f550..a3c6bf6e80 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -169,6 +169,17 @@ impl<'a> Tree<'a> { } } + /// Glyph `gid`'s outline in the current transform; empty once the glyph is over budget, so + /// the layers that follow cost nothing (a compact layer list can name one big outline often). + fn layer_outline(&mut self, gid: GlyphId) -> BezPath { + if self.too_large { + return BezPath::new(); + } + let mut path = outline(self.font, self.location, gid); + path.apply_affine(self.transform()); + path + } + fn transform(&self) -> Affine { self.transforms.last().copied().unwrap_or(FLIP) } @@ -359,8 +370,7 @@ impl ColorPainter for Tree<'_> { } fn push_clip_glyph(&mut self, glyph_id: GlyphId) { - let mut clip = outline(self.font, self.location, glyph_id); - clip.apply_affine(self.transform()); + let clip = self.layer_outline(glyph_id); self.charge(&clip); self.open(Open { clip: Some(clip), blend: None, children: vec![], flooded: false }); } @@ -392,8 +402,7 @@ impl ColorPainter for Tree<'_> { /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option, brush: Brush<'_>) { - let mut path = outline(self.font, self.location, glyph_id); - path.apply_affine(self.transform()); + let path = self.layer_outline(glyph_id); let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine); self.transforms.push(brush_xf); self.fill_path(&path, &brush); diff --git a/crates/text/src/composer.rs b/crates/text/src/composer.rs index dbfa374317..bac0edbe92 100644 --- a/crates/text/src/composer.rs +++ b/crates/text/src/composer.rs @@ -116,7 +116,9 @@ fn adjustment_ratio(natural: f64, width: f64, stretch: f64, shrink: f64, last: b /// Compose the paragraph `g` into lines. `width(k)` is the available width of line `k`; /// `start_credit(i)` is the width a wrapped line starting at glyph `i` gives back (Mojikumi sets -/// an opening bracket there flush with the line's start); `cands` are the break opportunities +/// an opening bracket there flush with the line's start); `end_credit(t)` is the width a line whose +/// last character is glyph `t - 1` gives back (Mojikumi sets a closing mark there half width), at +/// most that glyph's advance, and nothing at a hyphenation point; `cands` are the break opportunities /// in increasing order (the paragraph end is added); `flex` holds how far each glyph may stretch /// and shrink in a justified line. /// Returns `(end, hyphen)` per line, or `None` if no set of breaks fits within the tolerance @@ -125,6 +127,7 @@ pub(crate) fn compose( g: &[SGlyph], width: &dyn Fn(usize) -> f64, start_credit: &dyn Fn(usize) -> f64, + end_credit: &dyn Fn(usize) -> f64, cands: &[Breakpoint], flex: &[Flex], p: &Params, @@ -153,6 +156,11 @@ pub(crate) fn compose( } b }; + let line_end_credit = |t: usize| { + let credit = end_credit(t); + let most = t.checked_sub(1).and_then(|k| g.get(k)).map_or(0.0, |gl| gl.adv.max(0.0)); + if credit.is_finite() { credit.clamp(0.0, most) } else { 0.0 } + }; let mut all: Vec = cands.iter().copied().filter(|c| c.end > 0 && c.end < n).collect(); all.push(Breakpoint { end: n, hyphen: 0.0 }); let (adj_demerits, hyphen_penalty) = @@ -170,7 +178,10 @@ pub(crate) fn compose( let Some(a) = nodes.get(ai) else { continue }; let t = trim(bp.end, a.pos); let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; - let natural = w[t] - w[a.pos] - credit + bp.hyphen; + // A line that ends with a hyphen ends with it, not with its last character. At most the + // last glyph's advance, so a longer line from the same node is never narrower. + let end = if hyphen || t <= a.pos { 0.0 } else { line_end_credit(t) }; + let natural = w[t] - w[a.pos] - credit - end + bp.hyphen; let lw = width(a.line); // Adjustment ratio, badness and whether the line ends the active node's reach. let Some(ratio) = adjustment_ratio(natural, lw, st[t] - st[a.pos], sh[t] - sh[a.pos], last, p) else { continue }; diff --git a/crates/text/src/edit.rs b/crates/text/src/edit.rs index a4505f9596..c2838fbbe8 100644 --- a/crates/text/src/edit.rs +++ b/crates/text/src/edit.rs @@ -214,6 +214,28 @@ pub fn next_char(s: &str, i: usize) -> usize { s[i..].chars().next().map(|c| i + c.len_utf8()).unwrap_or(s.len()) } +/// Does the character at byte `i` of `s` start a line by itself: the first character of the text, +/// of a paragraph, or after a forced line break (U+2028)? +pub fn starts_line(s: &str, i: usize) -> bool { + i == 0 || s.get(..i).is_some_and(|before| before.ends_with(['\n', '\u{2028}'])) +} + +/// The character whose kerning the Type tool's caret at byte `i` of `s` sets (the Kerning field, +/// Alt+arrows, Reset Tracking and Kerning), and whether that kerning is the space before it +/// ([`vectorcraft_doc::CharStyle::kerning_before`]) or after it +/// ([`vectorcraft_doc::CharStyle::kerning`]). Inside a line it is the space after the character +/// before the caret. At the start of a line ([`starts_line`]) no character on the line comes before +/// the caret, so it is the space before the character after it (#5111). None at the start of an +/// empty line, where no character follows either. +pub fn caret_kerning_target(s: &str, i: usize) -> Option<(Range, bool)> { + let i = floor_char(s, i); + if !starts_line(s, i) { + return Some((prev_char(s, i)..i, false)); + } + let c = s.get(i..)?.chars().next()?; + (c != '\n' && c != '\u{2028}').then(|| (i..i + c.len_utf8(), true)) +} + /// The start of the grapheme cluster before `i` (Left arrow): a Thai consonant with its vowel and /// tone marks, an accented letter or an emoji sequence is passed over whole. pub fn prev_cluster(s: &str, i: usize) -> usize { diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index a95ac2dc5d..12d27bd119 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -192,6 +192,19 @@ mod alias_tests { font } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_file_search_for_uncovered_characters_stops_at_its_budget() { + let db = FontDb::with_font_dirs(vec![]); + // The first search scans the font folders, which starts the count again. + db.system_fallback('\u{E001}'); + db.sys.lock().unwrap().file_searches = names::MAX_FILE_SEARCHES; + assert!(!db.system_fallback('\u{E000}')); + let sys = db.sys.lock().unwrap(); + assert_eq!(sys.file_searches, names::MAX_FILE_SEARCHES); + assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss"); + } + #[test] fn a_collection_lists_at_most_max_faces() { let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]); diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 902a3e5aae..4ef17c40c6 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -456,6 +456,7 @@ impl FontDb { let mut sys = self.sys.lock().unwrap_or_else(|e| e.into_inner()); sys.scans = sys.scans.wrapping_add(1); sys.misses.clear(); + sys.file_searches = 0; } self.changed(); n diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index 7f02517037..fdbb27e3a7 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -7,23 +7,63 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) - face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid) } +/// The most path elements one glyph outline keeps. Real outlines have hundreds; a variable +/// composite glyph can repeat a big base outline into millions. Elements past it are dropped. +pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20; + /// A pen drawing outlines y down, as text space has them. pub(crate) struct FlipPen(pub(crate) BezPath); +impl FlipPen { + fn full(&self) -> bool { + self.0.elements().len() >= MAX_OUTLINE_ELEMENTS + } +} + impl OutlinePen for FlipPen { fn move_to(&mut self, x: f32, y: f32) { + if self.full() { + return; + } self.0.move_to((x as f64, -y as f64)); } fn line_to(&mut self, x: f32, y: f32) { + if self.full() { + return; + } self.0.line_to((x as f64, -y as f64)); } fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + if self.full() { + return; + } self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); } fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + if self.full() { + return; + } self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); } fn close(&mut self) { + if self.full() { + return; + } self.0.close_path(); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pen_keeps_at_most_the_element_cap() { + let mut pen = FlipPen(BezPath::new()); + pen.move_to(0.0, 0.0); + for i in 0..MAX_OUTLINE_ELEMENTS + 10 { + pen.line_to(i as f32, 0.0); + } + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 71e8e7ab88..fa91e97875 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -482,7 +482,7 @@ impl FontDb { /// Load a system font covering `c` (preferred fallback families first, then any cataloged /// file under 40 MB). Returns true if one was loaded. Misses are remembered. #[cfg(not(target_arch = "wasm32"))] - fn system_fallback(&self, c: char) -> bool { + pub(super) fn system_fallback(&self, c: char) -> bool { if c.is_control() || c.is_whitespace() { return false; } @@ -501,6 +501,13 @@ impl FontDb { return true; } } + { + let mut sys = self.sys.lock().unwrap_or_else(|e| e.into_inner()); + if sys.file_searches >= super::names::MAX_FILE_SEARCHES { + return false; + } + sys.file_searches += 1; + } let mut paths: Vec = self.read_catalog().values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect(); paths.sort(); paths.dedup(); diff --git a/crates/text/src/fontdb/names.rs b/crates/text/src/fontdb/names.rs index 6ed1b44a2c..7531b130ec 100644 --- a/crates/text/src/fontdb/names.rs +++ b/crates/text/src/fontdb/names.rs @@ -7,8 +7,16 @@ pub(super) struct SysFallback { pub(super) misses: std::collections::HashSet, /// Counts the scans of the font folders: a search that a scan overtook doesn't record its miss. pub(super) scans: u64, + /// Characters that went on to read every cataloged font file (and found nothing, or a face). + /// Each such search rereads the catalog, so only [`MAX_FILE_SEARCHES`] are made per scan. + pub(super) file_searches: u32, } +/// The most characters searched for in the font files themselves between two scans of the font +/// folders. Real text has a few uncovered characters; a document of thousands of distinct +/// private-use code points would reread the whole catalog for each. +pub(super) const MAX_FILE_SEARCHES: u32 = 1024; + /// Fonts made for Thai, tried first (when installed) for Thai the font in use lacks: Windows /// (Leelawadee UI; Tahoma before Windows 8), macOS (Thonburi, Sukhumvit Set) and Linux (Noto, /// TLWG). diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index b7c4f1060e..435bbc4ed7 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -38,7 +38,8 @@ pub(crate) fn is_harakat(c: char) -> bool { /// Do character styles `a` and `b` differ, if at all, only in paint: fill, stroke and how the /// stroke is drawn, overprint, and the character style name? Those are not read by the shaper -/// and change no glyph, advance or position. Stricter than [`crate::shape`]'s `shapes_alike` +/// and change no glyph, advance or position. Nor is the space before a line's first character +/// inside a cluster, which takes it from its first character (#5111), so it is ignored too. Stricter than [`crate::shape`]'s `shapes_alike` /// (which also ignores baseline shift, tracking, underline, …). pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { // Exhaustive: a new attribute must explicitly keep or relax this boundary rule. @@ -51,6 +52,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { leading, tracking, kerning, + kerning_before: _, optical_kerning, baseline_shift, h_scale, diff --git a/crates/text/src/justify.rs b/crates/text/src/justify.rs index a3a1419402..53de928be2 100644 --- a/crates/text/src/justify.rs +++ b/crates/text/src/justify.rs @@ -89,6 +89,7 @@ pub(crate) fn apply_desired(sg: &mut [SGlyph], j: &JustificationOptions, scale_g let base = g.adv; if g_des != 1.0 { g.adv *= g_des; + g.tracking *= g_des; g.sx *= g_des; g.dx *= g_des; g.kern_shift *= g_des; diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 15b71ae233..6e02df73cd 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -37,9 +37,9 @@ pub(crate) use bidi::{is_rtl, para_bidi}; use breaking::tab_advance; #[cfg(test)] use breaking::{break_line, candidates}; +pub use driver::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; #[cfg(test)] -pub(crate) use driver::layout_faces_per_call; -pub use driver::{decorations, fit_first_line, fit_source_lines, layout, layout_with, scaled}; +pub(crate) use driver::{fit_passes, layout_faces_per_call}; use vertical::{TcyStyle, stands_upright, tate_chu_yoko, upright_cell, upright_centre, upright_extent, whole_character_widths}; #[cfg(test)] @@ -99,14 +99,17 @@ fn takes_cell(g: &SGlyph) -> bool { /// /// It stands in glyph space as it stands in vertical point type's line space: a quarter turn /// counterclockwise from horizontal path type's pose about the center of its cell, a baseline shift -/// kept across the column and a leading space taken off moving it along the path, then moved across +/// kept across the column and a leading space taken off (or the space before a column's first +/// character) moving it along the path, then moved across /// the path as a glyph lying on its side is. fn upright_path_turn(g: &SGlyph, em: f64, pre: Affine, local: Affine, unturned: Affine, angle: f64, advance: f64) -> (Affine, f64) { let cell = if takes_cell(g) { upright_cell(g) } else { advance }; let (shift, unshift) = (Affine::translate((0.0, -g.bshift)), Affine::translate((0.0, g.bshift))); let about = Point::new(cell * 0.5, -upright_centre(g, cell, em)); - let mut turn = - Affine::translate((-g.lead, g.face.ideographic_centre() * em)) * shift * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, about) * unshift; + let mut turn = Affine::translate((g.kern_shift - g.lead, g.face.ideographic_centre() * em)) + * shift + * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, about) + * unshift; // The effects that keep the glyph's axes fixed (Stair Step) leave its top toward the path's end on // a path that runs to the left: it turns half a turn about its cell's center. let tangent = Vec2::new(angle.cos(), angle.sin()); @@ -359,19 +362,20 @@ impl Ctx<'_> { } else { self.db.outline(&g.face, g.gid) }; - // A glyph whose leading space was taken off (mojikumi) is drawn that much earlier: an - // upright one in vertical type by moving it up the column once it stands upright. + // A glyph whose leading space was taken off (mojikumi) is drawn that much earlier, and one + // moved along the line by manual kerning ([`SGlyph::kern_shift`]) that much later: an + // upright one in vertical type by moving it along the column once it stands upright. let upright = self.vertical && g.tcy.is_none() && stands_upright(g) && !(self.on_path && g.inline.is_some()); - let lead = if upright { 0.0 } else { g.lead }; + let (lead, kern_shift) = if upright { (0.0, 0.0) } else { (g.lead, g.kern_shift) }; let local = match &g.inline { // Inline graphics: art space to glyph space (no font outline), moved along the line by // right-to-left manual kerning as a glyph is. - Some(ib) => Affine::translate((g.kern_shift - lead, -g.bshift)) * ib.xf, + Some(ib) => Affine::translate((kern_shift - lead, -g.bshift)) * ib.xf, // Baseline shift moves the glyph across its line, and Character Rotation then turns it // about its shifted pen position, so the shift is across the line at any rotation. // Manual kerning and composition trim move that pen position along the line. None => { - Affine::translate((g.kern_shift - lead, -g.bshift)) + Affine::translate((kern_shift - lead, -g.bshift)) * Affine::rotate(-g.rotation.to_radians()) * Affine::translate((g.dx, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy) @@ -379,7 +383,7 @@ impl Ctx<'_> { }; // The turning point in font units, which later moves of the glyph's transform keep. let pivot = match local.determinant() { - det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(g.kern_shift - lead, -g.bshift), + det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(kern_shift - lead, -g.bshift), _ => Point::ZERO, }; let unturned = if g.inline.is_none() && g.rotation != 0.0 && g.sx != 0.0 && g.sy != 0.0 { @@ -490,9 +494,10 @@ impl Ctx<'_> { // space after the cell, and must not push the glyph off the centre line). let em = self.style_at(g.byte).size; let cell = if takes_cell(g) { upright_cell(g) } else { advance }; - // A leading space taken off moves it up the column after the turn (moving the - // turning point instead would move it across the column too). - let turn = Affine::translate((-g.lead, 0.0)) + // A leading space taken off moves it up the column after the turn, and the space + // before a column's first character down it (moving the turning point instead + // would move it across the column too). + let turn = Affine::translate((g.kern_shift - g.lead, 0.0)) * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(origin.x + cell * 0.5, origin.y - upright_centre(g, cell, em))); m = shift * turn * unshift * m; // Its own advance across, from where the cell centres it: where the shaper set the @@ -527,10 +532,16 @@ impl Ctx<'_> { }; // Where its own width starts along its advance: the shaper's placement, a leading space // taken off and right-to-left manual kerning move the glyph along the line. An upright or - // tate-chu-yoko glyph in vertical type starts its cell at the start of its advance. - let width_start = if g.inline.is_none() && !upright && !(self.vertical && g.tcy.is_some()) { + // tate-chu-yoko glyph in vertical type starts its cell at the start of its advance, an + // upright one after the space before a column's first character. + let along = { let [a, b, ..] = pre.as_coeffs(); - Some((g.kern_shift + g.dx - g.lead) * a.hypot(b)).filter(|s| s.is_finite()).unwrap_or(0.0) + a.hypot(b) + }; + let width_start = if g.inline.is_none() && !upright && !(self.vertical && g.tcy.is_some()) { + Some((g.kern_shift + g.dx - g.lead) * along).filter(|s| s.is_finite()).unwrap_or(0.0) + } else if upright { + Some(g.kern_shift * along).filter(|s| s.is_finite()).unwrap_or(0.0) } else { 0.0 }; @@ -659,6 +670,7 @@ mod emit_kashida_mark_last { len: 2, run: 0, adv: 10.0, + tracking: 0.0, dx: 0.0, dy: 0.0, kern_shift: 0.0, @@ -675,6 +687,7 @@ mod emit_kashida_mark_last { tcy: None, inline: None, word_end: false, + keeps_word: false, lead: 0.0, proportional: false, vpal: None, @@ -719,6 +732,7 @@ mod emit_kashida_mark_last { len: 4, run: 1, adv: 0.0, + tracking: 0.0, dx: 0.0, dy: 0.0, kern_shift: 0.0, @@ -735,6 +749,7 @@ mod emit_kashida_mark_last { tcy: None, inline: None, word_end: false, + keeps_word: false, lead: 0.0, proportional: false, vpal: None, diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 87fa8db4df..0f033d4fcb 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -63,12 +63,19 @@ pub(super) struct Pen<'r> { pub(super) next_top: Option, /// The narrowest word no line from here down is wide enough for (see [`Pen::place`]). pub(super) no_room_for: f64, + /// Baseline steps still allowed over all the frame's cells and placements (shared by this pen's + /// copies): see [`MAX_TOTAL_STEPS`]. + pub(super) steps_left: std::rc::Rc>, } /// The largest number of steps layout takes to move a line down a frame cell to find room for it: /// in a cell taller than this many leads, a step is the cell's height divided by this. const MAX_STEPS: usize = 100_000; +/// The most baseline steps one frame's layout takes in all, over every cell: a cell may take +/// [`MAX_STEPS`], but rows and columns of tall, narrow-shaped cells would multiply that. +pub(super) const MAX_TOTAL_STEPS: usize = 10_000_000; + impl Pen<'_> { /// Baseline and horizontal span for a line with estimated metrics `est` and indents that starts /// with a word `word` wide; `None` = the frame is full (overflow). @@ -110,6 +117,12 @@ impl Pen<'_> { // height when that is more, in at most `MAX_STEPS` steps. let step = est.lead.max(1.0).max(r.cell.height() / MAX_STEPS as f64); for _ in 0..=MAX_STEPS { + let left = self.steps_left.get(); + if left == 0 { + // Out of steps: the frame is full as far as this text goes. + return None; + } + self.steps_left.set(left - 1); // A baseline a step no longer moves (past a gutter of 1e300, say) won't reach a line. if baseline + est.desc > r.bottom() + 0.01 || baseline + step <= baseline || baseline.is_nan() { break; @@ -240,29 +253,52 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64, out } -/// Width of the word starting at glyph `i`: its advances up to the first break opportunity (spaces -/// left out, the hyphen of a soft hyphen in), the least room a line needs not to break inside it. -/// A list marker at `i` (glyphs of length 0) counts whole, with the word after it. -pub(super) fn word_width(g: &[SGlyph], i: usize) -> f64 { +/// Width of the word starting at glyph `i`: its advances up to the first place a line may break +/// (spaces left out, the hyphen of a soft hyphen in), the least room a line needs not to break +/// inside it. As in [`break_line`], kinsoku keeps a character that may not end a line with the one +/// after it, a No Break run (its spaces inside it included) is one word up to a forced line break, +/// and a cluster is never split. A soft hyphen just before a forced line break adds no hyphen. A list marker at `i` (glyphs of length 0) counts whole, with the word after it. A word +/// that ends where a line may end is measured as the line is set: without the spaces at its end, +/// and with its last glyph as narrow as `line_end` sets it; one that ends at a soft hyphen or past +/// the measured glyphs is not. +pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kinsoku) -> f64 { /// Glyphs measured at most: a word wrapped over many lines is measured again from each line's /// start, and one this long is broken inside whatever cell it meets. const MAX_GLYPHS: usize = 1024; let rest = g.get(i..).unwrap_or_default(); let marker = rest.iter().take_while(|gl| gl.len == 0).count(); let mut w: f64 = rest.iter().take(marker).map(|gl| gl.adv).sum(); - for gl in rest.iter().skip(marker).take(MAX_GLYPHS) { - if gl.is_space() { - break; + let start = i + marker; + let mut end = start; + // The spaces at the end of what is measured so far (inside a No Break run), and the end of its + // last glyph that is not a space. + let (mut trailing, mut ink) = (0.0, start); + let set = |w: f64, trailing: f64, ink: usize| w - trailing - line_end_credit(g, line_end, ink); + while let Some(gl) = g.get(end).filter(|_| end - start < MAX_GLYPHS) { + // A forced line break ends the line, inside a No Break run too, as in [`break_line`]. + if gl.ch == '\u{2028}' { + return set(w, trailing, ink); } - if gl.is_soft_hyphen() { + if gl.is_space() && (end == start || !splits_no_break(g, end)) { + return set(w, trailing, ink); + } + let forced_next = g.get(end + 1).is_some_and(|n| n.ch == '\u{2028}'); + if gl.is_soft_hyphen() && !forced_next && kinsoku_allows(g, end, kinsoku) && !splits_no_break(g, end + 1) { return w + hyphen_glyph(gl).adv; } w += gl.adv; - if gl.break_after() { - break; + end += 1; + if gl.is_space() { + trailing += gl.adv; + } else { + (trailing, ink) = (0.0, end); + } + let cluster_ends = g.get(end).is_none_or(|next| next.byte != gl.byte); + if gl.break_after() && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) { + return set(w, trailing, ink); } } - w + if end >= g.len() { set(w, trailing, ink) } else { w } } /// Greedy break: returns (end glyph index, hyphenated) for a line starting at `i` of `width`. @@ -274,6 +310,8 @@ pub(super) fn word_width(g: &[SGlyph], i: usize) -> f64 { /// keeps the line from breaking before the character that overflows, `kinsoku_type` decides /// whether the line pushes characters in ([`push_in`]) or out; `hanging` is true when Optical /// Margin Alignment or Roman Hanging Punctuation is on, and `vertical` in vertical type. +/// `line_end[k]` is how much narrower a line ending with glyph `k` is set (Mojikumi); a cluster +/// that fits only that narrower stays on the line when the line may end after it (empty: none). #[allow(clippy::too_many_arguments)] pub(super) fn break_line( text: &str, @@ -288,6 +326,7 @@ pub(super) fn break_line( kinsoku_type: KinsokuShoriType, hanging: bool, vertical: bool, + line_end: &[f64], ) -> (usize, bool) { if !width.is_finite() { if let Some(pos) = g[i..].iter().position(|gl| gl.ch == '\u{2028}') { @@ -329,7 +368,11 @@ pub(super) fn break_line( if gl.ch == '\u{2028}' { return (cluster_end, false); } - if j > first && !gl.is_space() && x + cluster_width > width + EPS { + // Measured as the line is set when it ends with this cluster: only the cluster's last glyph + // is narrowed, and only where the line may end. + let end_credit = + Some(line_end_credit(g, line_end, cluster_end)).filter(|&c| c > 0.0 && may_end_after(g, cluster_end, kinsoku)).unwrap_or(0.0); + if j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS { // It ends the line with the spaces after it. if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, cluster_end - 1, kinsoku) { let mut end = cluster_end; @@ -338,8 +381,8 @@ pub(super) fn break_line( } return (end, false); } - if let Some(end) = - push_in(g, i, j, cluster_end, x + cluster_width, width, last_break.map(|b| b.0), kinsoku, kinsoku_type, hanging, vertical) + let pushed_out = last_break.map(|b| b.0); + if let Some(end) = push_in(g, i, j, cluster_end, x + cluster_width, width, pushed_out, kinsoku, kinsoku_type, hanging, vertical, line_end) { return (end, false); } @@ -482,6 +525,30 @@ pub(super) fn optical_hangs_rtl(line: &[(&SGlyph, f64)], share: fn(&SGlyph) -> f (left, right, left_glyphs, right_glyphs) } +/// How much narrower a line whose last character is glyph `end - 1` is set: `line_end` of that +/// glyph ([`break_line`]), at most its advance, and 0 when it is not finite. +fn line_end_credit(g: &[SGlyph], line_end: &[f64], end: usize) -> f64 { + let Some(k) = end.checked_sub(1) else { return 0.0 }; + match (line_end.get(k), g.get(k)) { + (Some(&credit), Some(gl)) if credit.is_finite() && credit > 0.0 => credit.min(gl.adv.max(0.0)), + _ => 0.0, + } +} + +/// May [`break_line`] end a line after glyph `end - 1` (and the spaces after it)? At the paragraph's +/// end or a forced line break, and where it records a break without a hyphen. +fn may_end_after(g: &[SGlyph], end: usize, kinsoku: Kinsoku) -> bool { + let mut e = end; + while g.get(e).is_some_and(SGlyph::is_space) { + e += 1; + } + if e >= g.len() || g[e].ch == '\u{2028}' { + return true; + } + let Some(last) = e.checked_sub(1).and_then(|k| g.get(k)) else { return false }; + last.break_after() && last.len > 0 && !last.is_soft_hyphen() && kinsoku_allows(g, e - 1, kinsoku) && !splits_no_break(g, e) +} + /// Would a line ending at glyph index `end` split a No Break run? fn splits_no_break(g: &[SGlyph], end: usize) -> bool { end > 0 && g.get(end - 1).is_some_and(|a| a.no_break) && g.get(end).is_some_and(|b| b.no_break) @@ -526,7 +593,8 @@ const PUSH_IN_RUN: usize = 16; /// neither does a line holding a tab or right-to-left text, nor one where the characters taken in /// reach a space after a character that may not end a line. With `hanging` (Optical Margin /// Alignment or Roman Hanging Punctuation), the gaps that hanging punctuation keeps open are not -/// counted. `vertical`: the line is a column of vertical type ([`squeeze_em`]). +/// counted. `vertical`: the line is a column of vertical type ([`squeeze_em`]). Both lines are +/// measured with their last character set as narrow as `line_end` sets it ([`break_line`]). #[allow(clippy::too_many_arguments)] fn push_in( g: &[SGlyph], @@ -540,6 +608,7 @@ fn push_in( kinsoku_type: KinsokuShoriType, hanging: bool, vertical: bool, + line_end: &[f64], ) -> Option { if kinsoku == Kinsoku::None || kinsoku_type == KinsokuShoriType::PushOutOnly { return None; @@ -591,7 +660,7 @@ fn push_in( || (a + 3 == last && punct(last - 2) && quote(last - 1))) }; let room: f64 = (i..end - 1).filter(|&a| closes(g, a) && !may_hang(a)).map(|a| PUSH_IN_SQUEEZE * squeeze_em(&g[a], vertical)).sum(); - if x - width > room + EPS { + if x - line_end_credit(g, line_end, last) - width > room + EPS { return None; } if kinsoku_type == KinsokuShoriType::PushOutFirst { @@ -599,7 +668,8 @@ fn push_in( while kept > i && g[kept - 1].is_space() { kept -= 1; } - let short = width - g[i..kept].iter().map(|h| h.adv).sum::(); + let set = if kept > i { line_end_credit(g, line_end, kept) } else { 0.0 }; + let short = width - (g[i..kept].iter().map(|h| h.adv).sum::() - set); if short <= squeeze_em(before, vertical) + EPS { return None; } @@ -664,8 +734,20 @@ 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`, in the -/// language of the word's first letter. +/// language of the word's first letter; never next to a Hangul letter, which takes no hyphen, and +/// nowhere in a Korean word that Korean Line Break Anywhere off keeps whole. fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &HyphenationOptions) -> Vec { + if g.get(ws..we).is_some_and(|word| word.iter().any(|h| h.keeps_word)) { + return Vec::new(); + } + let mut points = word_hyphen_breaks(text, g, ws, we, opts); + let hangul = |i: usize| g.get(i).is_some_and(|h| h.inline.is_none() && crate::shape::is_hangul(h.ch)); + points.retain(|&k| !hangul(k.wrapping_sub(1)) && !hangul(k)); + points +} + +/// [`hyphen_breaks`] before the points next to Hangul are left out. +fn word_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); while a < b && !g[a].is_letter() { @@ -732,3 +814,26 @@ pub(super) fn candidates(text: &str, g: &[SGlyph], hyphenate: Option<&Hyphenatio v.dedup_by_key(|b| b.end); v } + +#[cfg(test)] +#[test] +fn a_pen_out_of_baseline_steps_finds_no_room() { + let frame = kurbo::Shape::to_path(&kurbo::Rect::new(0.0, 0.0, 400.0, 400.0), 0.1); + let regions = Region::cells(&frame, &super::LayoutOptions::default(), &[]); + let est = Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 }; + let pen = |steps| Pen { + regions: Some(®ions), + ri: 0, + prev: None, + pending: 0.0, + fb: FirstBaseline::Ascent, + fb_min: 0.0, + queued: vec![], + model: LeadingModel::default(), + next_top: None, + no_room_for: f64::INFINITY, + steps_left: std::rc::Rc::new(std::cell::Cell::new(steps)), + }; + assert!(pen(MAX_TOTAL_STEPS).place(est, 0.0, 0.0, 0.0).is_some()); + assert!(pen(0).place(est, 0.0, 0.0, 0.0).is_none()); +} diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 79a7ebd8d8..68519f397b 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -209,24 +209,105 @@ const SHRINK_PASSES: usize = 11; pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout { #[cfg(any(test, feature = "test-fonts"))] crate::test_fonts::count_layout(); + // The sizes the fits step and limit are the ones the Character panel shows (`shown`), whatever + // em size a font height reference sets them at. + let shown = t; let resolved = db.font_heights_resolved(t); let t = &*resolved; let first = layout_once(db, t, opts); match (opts.fit.min_scale(), &t.kind) { - (Some(min), TextKind::Area { .. }) if first.overflow => shrink_to_fit(db, t, opts, min).unwrap_or(first), + (Some(min), TextKind::Area { .. }) if first.overflow => shrink_to_fit(db, t, shown, opts, min).unwrap_or(first), + (_, TextKind::OnPath { .. }) if t.dynamic_text => fill_path(db, t, shown, opts, &first).unwrap_or(first), _ => first, } } +/// The document size of the first character of `t` (its run's size; an empty run before it draws +/// nothing), in tenths of a point. None when it is not a usable size. +fn first_size_tenths(t: &TextObject) -> Option { + let points = t.style_scale()?.points; + let run = t.runs.iter().find(|r| !r.text.is_empty()).or(t.runs.first()); + run.map(|r| r.style.size * points * 10.0).filter(|s| s.is_finite() && *s > 0.0) +} + +/// Most layout passes Dynamic Text runs past the first (a guess, a search out from it, bisection). +const DYNAMIC_PASSES: usize = 11; + +/// The sizes, in tenths of a document point, Dynamic Text keeps the first run's size within: 0.1 +/// to 1,296 pt, the Character panel's range. +const DYNAMIC_TENTHS: (f64, f64) = (1.0, 12_960.0); + +/// Dynamic Text for type on a path: the largest scale at which the text does not run past its end +/// bracket, so that it fills the span between its brackets. The first run's document size moves in +/// steps of 0.1 pt within 0.1 to 1,296 pt; at either limit the text keeps that size, and at the +/// smallest it may still overflow. Each guess is the size tried last times the span's length over +/// the length the text took there, which is exact for a straight span with no Spacing; a guess +/// outside the sizes still open gives way to a step out from the last one (doubling) or to +/// bisection. At most [`DYNAMIC_PASSES`] passes. `t` is laid out; the sizes are those of `shown`, +/// `t` before its font height references were resolved. None (keep `first`) when the text takes no +/// length, the span has none, or the text has no usable size. +fn fill_path(db: &FontDb, t: &TextObject, shown: &TextObject, opts: &LayoutOptions, first: &TextLayout) -> Option { + let tenths = first_size_tenths(shown)?; + let (min, max) = DYNAMIC_TENTHS; + // The size in tenths that would fill the span, from a layout at `k` tenths. + let guess = |k: f64, l: &TextLayout| -> Option { + let (used, room) = l.path_fill?; + let g = (k * room / used).floor(); + (used.is_finite() && used > 1e-9 && room.is_finite() && room > 1e-9 && g.is_finite()).then(|| g.clamp(min, max)) + }; + let mut next = guess(tenths, first)?; + let at = |k: f64| -> TextLayout { + #[cfg(test)] + FIT_PASSES.set(FIT_PASSES.get() + 1); + let f = k / tenths; + let mut l = layout_once(db, &scaled(t, f), opts); + l.fit_scale = f; + l + }; + // The largest size tried that fits, and the smallest that overflows, each with its layout. + let mut fits: Option<(f64, TextLayout)> = None; + let mut over: Option<(f64, TextLayout)> = None; + let mut step = 1.0; + for _ in 0..DYNAMIC_PASSES { + let l = at(next); + let guessed = guess(next, &l); + if l.overflow { + if over.as_ref().is_none_or(|(o, _)| next < *o) { + over = Some((next, l)); + } + } else if fits.as_ref().is_none_or(|(f, _)| next > *f) { + fits = Some((next, l)); + } + // The sizes still open lie strictly between the largest that fits and the smallest that + // overflows, within the limits. + let lo = fits.as_ref().map_or(min - 1.0, |f| f.0); + let hi = over.as_ref().map_or(max + 1.0, |o| o.0); + if hi - lo <= 1.0 { + break; + } + next = match guessed.filter(|g| *g > lo && *g < hi) { + Some(g) => g, + None if fits.is_some() && over.is_some() => (lo + (hi - lo) * 0.5).floor(), + // Everything tried fits: try larger. Everything tried overflows: try smaller. + None if fits.is_some() => (lo + step).min(hi - 1.0), + None => (hi - step).max(lo + 1.0), + }; + step *= 2.0; + } + // The largest that fits, or at the smallest size (or at the pass limit) the smallest tried. + fits.or(over).map(|(_, l)| l) +} + /// Shrink Text to Fit for text that overflows at full size: the largest scale in `min..1` at which /// it fits, searched by bisection over the first run's document size in steps of 0.1 pt (so its scaled size /// is a whole number of tenths of a point, the same every time). Down at `min` it lays out there, -/// still overflowing. None (keep the full-size layout) when the text has no usable size. -fn shrink_to_fit(db: &FontDb, t: &TextObject, opts: &LayoutOptions, min: f64) -> Option { +/// still overflowing. `t` is laid out; the sizes are those of `shown`, `t` before its font height +/// references were resolved. None (keep the full-size layout) when the text has no usable size. +fn shrink_to_fit(db: &FontDb, t: &TextObject, shown: &TextObject, opts: &LayoutOptions, min: f64) -> Option { // Exact size edits after object scaling may store a local size below 0.1. Fit in the // same document points as the Character controls, independent of that representation. - let points = t.style_scale()?.points; - let size = t.runs.first().map(|r| r.style.size * points).filter(|s| s.is_finite() && *s >= 0.1)?; + let points = shown.style_scale()?.points; + let size = shown.runs.first().map(|r| r.style.size * points).filter(|s| s.is_finite() && *s >= 0.1)?; if !(min.is_finite() && min < 1.0) { return None; } @@ -292,6 +373,31 @@ pub fn scaled(t: &TextObject, f: f64) -> TextObject { s } +/// `t` in the styles its layout draws it in: [`scaled`] by the layout's +/// [`TextLayout::fit_scale`] when Shrink Text to Fit (area type) or Dynamic Text (type on a path) +/// scales it, `t` itself otherwise. Text with neither setting is not laid out. +pub fn drawn(t: &TextObject) -> std::borrow::Cow<'_, TextObject> { + let fits = match &t.kind { + TextKind::Area { .. } => t.area.fit.min_scale().is_some(), + TextKind::OnPath { .. } => t.dynamic_text, + TextKind::Point => false, + }; + let f = if fits { layout(FontDb::global(), t).fit_scale } else { 1.0 }; + if f != 1.0 { std::borrow::Cow::Owned(scaled(t, f)) } else { std::borrow::Cow::Borrowed(t) } +} + +#[cfg(test)] +thread_local! { + /// How many layouts Dynamic Text ran past the first on this thread ([`fit_passes`]). + static FIT_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many layouts Dynamic Text ran past the first on this thread. +#[cfg(test)] +pub(crate) fn fit_passes() -> usize { + FIT_PASSES.get() +} + #[cfg(test)] thread_local! { /// Set while [`layout_faces_per_call`] lays text out: layout keeps no run faces. diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index e1d55eece6..d7ac206424 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -10,6 +10,7 @@ use super::{ ListMarker, Mojikumi, ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; +use crate::shape::keep_korean_words; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -23,11 +24,14 @@ const MAX_COMPOSE_GLYPHS: usize = 200_000; /// Every-line composition of paragraph glyphs `sg` if applicable (area text, justified or ragged, /// with uniform line metrics or in rectangular cells without text wrap); `None` falls back to the /// greedy single-line composer. With `continued`, the paragraph continues from the frame before, -/// and its first composed line is not its first line. +/// and its first composed line is not its first line. `line_end` is how much narrower a line +/// ending with each glyph is set ([`ParagraphData::line_end`]). +#[allow(clippy::too_many_arguments)] fn compose_para( cx: &Ctx<'_>, sg: &[SGlyph], flex: &[Flex], + line_end: &[f64], para: &ParaStyle, pen: &Pen<'_>, rtl: bool, @@ -68,6 +72,12 @@ fn compose_para( return None; } let total: f64 = sg.iter().map(|g| g.adv).sum(); + // The same rule as the line loop below: an opening bracket starting a wrapped line gives up + // the space before it. + let start_credit = |i: usize| { + let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf; + sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0) + }; let mut sim = pen.clone(); let mut widths = vec![]; let mut acc = 0.0; @@ -77,8 +87,9 @@ fn compose_para( let first = widths.is_empty(); let ind_l = para.laid_out_left_indent() + if first && !continued { para.first_line_indent } else { 0.0 }; // Only the first line's first word is known here. Later lines are placed as the composed - // lines need: each fits its width, so its first word does too. - let word = if first { word_width(sg, 0) } else { 0.0 }; + // lines need: each fits its width, so its first word does too. It is measured as the line + // loop measures it, with Mojikumi's narrower start and end. + let word = if first { word_width(sg, 0, line_end, para.kinsoku) - start_credit(0) } else { 0.0 }; let Some((b, x0, x1, _)) = sim.place(m, ind_l, para.right_indent, word) else { break }; let w = x1 - x0 - ind_l - para.right_indent; widths.push(w); @@ -103,13 +114,10 @@ fn compose_para( // stop at four times its stretch and fall back to the single-line composer; the documented // default range (word spacing up to 133%) is narrow enough that most paragraphs would. let (strict, loose) = (1.0, f64::INFINITY); - // The same rule as the line loop below: an opening bracket starting a wrapped line gives up - // the space before it. - let start_credit = |i: usize| { - let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf; - sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0) - }; - compose(sg, &width, &start_credit, &cands, flex, ¶ms(strict)).or_else(|| compose(sg, &width, &start_credit, &cands, flex, ¶ms(loose))) + // A line's last character is set narrower, as the line loop sets it. + let end_credit = |end: usize| end.checked_sub(1).and_then(|k| line_end.get(k)).copied().unwrap_or(0.0); + let pass = |p: &Params| compose(sg, &width, &start_credit, &end_credit, &cands, flex, p); + pass(¶ms(strict)).or_else(|| pass(¶ms(loose))) } /// The list marker of each of the paragraphs `paras` of `t` (None for none): bullets, and numbers @@ -150,6 +158,7 @@ pub(super) fn flow(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, reg model: t.para_at(0).leading_model, next_top: None, no_room_for: f64::INFINITY, + steps_left: std::rc::Rc::new(std::cell::Cell::new(super::breaking::MAX_TOTAL_STEPS)), }; let markers = list_markers(t, paras); for (pi, pr) in paras.iter().enumerate() { @@ -183,6 +192,10 @@ struct ParagraphData<'a, 'text> { sg: Vec, compressed: Vec, wakan: Vec, + /// How much narrower a line ending with each glyph is set ([`line_end_trim`]), for measuring + /// where lines break; empty when the paragraph's lines are measured at full width (Mojikumi + /// None, or right-to-left text). + line_end: Vec, flex: Vec, marker: usize, pm: Metrics, @@ -212,13 +225,18 @@ fn prepare_paragraph<'a, 'text>( let mut sg = cx.shape_para(pr.clone(), bidi.as_ref()); // Thai, Lao, Khmer and Myanmar break lines between words, not at spaces. mark_word_ends(text.get(pr.clone()).unwrap_or_default(), pr.start, &mut sg); + // Korean breaks between words, unless Korean Line Break Anywhere lets it break between syllables. + if !para.korean_line_break_anywhere { + keep_korean_words(&mut sg); + } // Japanese composition: consecutive punctuation shares one half-em space. let mut compressed = if para.mojikumi == Mojikumi::LineEndHalf { compress_punctuation(&mut sg) } else { vec![] }; // …and a quarter em between Japanese and Latin text. let mut wakan = if para.mojikumi == Mojikumi::LineEndHalf { space_japanese_and_latin(&mut sg) } else { vec![] }; // Justification…: the glyphs at Desired word and letter spacing and glyph scaling, and how - // far a justified line may move each one from it. - let mut flex = apply_desired(&mut sg, ¶.justification, !cx.vertical); + // far a justified line may move each one from it (Dynamic Text's Block on area type sets the + // Desired word spacing to its word gap). + let mut flex = apply_desired(&mut sg, &t.layout_justification(para), !cx.vertical); // Threaded text: a first paragraph that continues from the frame before has its first // line, first-line indent and list marker there. let continued = pi == 0 && t.first_para_continues; @@ -253,7 +271,13 @@ fn prepare_paragraph<'a, 'text>( if pi > 0 { pen.pending += para.space_before; } - let composed = compose_para(cx, &sg, &flex, para, pen, rtl, continued); + // A line fits when it fits as it is set: with its last character narrowed by Mojikumi. + let line_end = if para.mojikumi == Mojikumi::LineEndHalf && !rtl { + (0..sg.len()).map(|k| line_end_trim(&sg, &compressed, &wakan, k)).collect() + } else { + vec![] + }; + let composed = compose_para(cx, &sg, &flex, &line_end, para, pen, rtl, continued); // Hyphenation options: the Hyphenation Zone applies with the Single-line Composer, and the // Hyphen Limit counts the lines in a row that end with a hyphen. let zone = if cx.opts.composer.unwrap_or(para.composer) == Composer::SingleLine { para.hyphenation.zone } else { 0.0 }; @@ -269,6 +293,7 @@ fn prepare_paragraph<'a, 'text>( sg, compressed, wakan, + line_end, flex, marker, pm, @@ -284,6 +309,8 @@ struct PlacementContext<'a> { para: &'a ParaStyle, pr: &'a Range, sg: &'a mut [SGlyph], + /// [`ParagraphData::line_end`]. + line_end: &'a [f64], continued: bool, rtl: bool, mirror: bool, @@ -312,14 +339,27 @@ struct LinePosition { } fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementContext<'_>) -> Option { - let PlacementContext { para, pr, sg, continued, rtl, mirror, pm, composed, hyphen_run, hyphen_limit, zone, index: i, para_line, hanging } = - context; + let PlacementContext { + para, + pr, + sg, + line_end, + continued, + rtl, + mirror, + pm, + composed, + hyphen_run, + hyphen_limit, + zone, + index: i, + para_line, + hanging, + } = context; let n = sg.len(); let est = if *i < n { Metrics::of(&sg[*i]) } else { *pm }; let first_line = *para_line == 0 && !*continued; let (ind_l, ind_r) = line_indents(para, first_line, *mirror); - // Measured before Mojikumi narrows an opening bracket, as the composer measures it. - let word = word_width(sg, *i); // Mojikumi: an opening bracket starting a line is set flush with the line's start (the // space before it goes), and the line has that much more room. At a paragraph's start // that is the first-line indent: JIS X 4051's principle (JLREQ 3.1.5, Figure 71 ①). @@ -332,6 +372,8 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC glyph.adv -= half; glyph.lead += half; } + // The line's first word, as narrow as the line sets it at both ends. + let word = word_width(sg, *i, line_end, para.kinsoku); // Place, break, then settle the baseline on the line's real metrics (moving on to the // next row/column if it no longer fits). loop { @@ -345,8 +387,23 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC let (end, hyph, pushed_in) = match composed.as_ref().and_then(|lines| lines.get(*para_line)) { Some(&(end, hyph)) if end > *i => (end, hyph, false), _ if *i < n => { - let line = - |ty| break_line(cx.text, sg, *i, width, ¶.tabs, ind_l, hyphenate, para.burasagari, para.kinsoku, ty, *hanging, cx.vertical); + let line = |ty| { + break_line( + cx.text, + sg, + *i, + width, + ¶.tabs, + ind_l, + hyphenate, + para.burasagari, + para.kinsoku, + ty, + *hanging, + cx.vertical, + line_end, + ) + }; let (end, hyph) = line(para.kinsoku_type); // The line pushed characters in where it ends after the line that pushes out. let pushed_in = pushes_in(para) && end > line(KinsokuShoriType::PushOutOnly).0; @@ -389,6 +446,9 @@ struct LineGeometry { ax1: f64, width: f64, render_width: f64, + /// The tracking after the line's last character, when that character ends the line (see + /// [`prepare_line_geometry`]); 0 otherwise. + trailing: f64, order: Vec, drawn: Vec, opt_l: f64, @@ -413,6 +473,9 @@ struct LineJustification { /// Right-aligned area type: the line's last tab, which takes the text after it to the right /// edge (the text before it sits at its stops, from the left edge). last_tab: Option, + /// The tracking after the line's last character that its alignment leaves out of its width: + /// [`LineGeometry::trailing`] for a line that isn't justified, 0 for one that is. + trailing: f64, } fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut paragraph: ParagraphData<'_, '_>) -> bool { @@ -433,6 +496,7 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut para: paragraph.para, pr: ¶graph.pr, sg: &mut paragraph.sg, + line_end: ¶graph.line_end, continued: paragraph.continued, rtl: paragraph.rtl, mirror: paragraph.mirror, @@ -467,6 +531,18 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut true } +/// Mojikumi (Line-end Punctuation Half Width): how much narrower a line ending with glyph `k` of +/// `sg` is set. A closing bracket, comma or full stop ending the line is set half width, unless it +/// already lost that half to the punctuation after it (`compressed`), and no Japanese–Latin space +/// (`wakan`) is left after the line's last character. Never more than the glyph's advance, and 0 +/// for an advance or a space that is not finite. +pub(super) fn line_end_trim(sg: &[SGlyph], compressed: &[bool], wakan: &[f64], k: usize) -> f64 { + let Some(g) = sg.get(k) else { return 0.0 }; + let half = if compressed.get(k).copied().unwrap_or(false) { None } else { punct_half(g, Punct::Closing) }; + let trim = half.unwrap_or(0.0) + wakan.get(k).copied().unwrap_or(0.0); + if trim.is_finite() && g.adv.is_finite() { trim.min(g.adv).max(0.0) } else { 0.0 } +} + /// The geometry of the line of `paragraph` from glyph `index`, placed at `position`: where it /// ends with its trailing spaces trimmed, its hyphen, its room and margins, the glyphs that hang or /// stay out of justification, and whether it is the paragraph's last line. @@ -482,12 +558,10 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData trimmed -= 1; } let hyphen = (position.hyph && position.end > index).then(|| hyphen_glyph(&sg[position.end - 1])); - // Mojikumi: a closing bracket, comma or full stop ending the line is set half width, and - // no Japanese–Latin space is left at the end of a line. - let end_trim = trimmed.checked_sub(1).filter(|&k| k >= index && para.mojikumi == Mojikumi::LineEndHalf).map_or(0.0, |k| { - let half = if paragraph.compressed.get(k).copied().unwrap_or(false) { None } else { sg.get(k).and_then(|g| punct_half(g, Punct::Closing)) }; - half.unwrap_or(0.0) + paragraph.wakan.get(k).copied().unwrap_or(0.0) - }); + let end_trim = trimmed + .checked_sub(1) + .filter(|&k| k >= index && para.mojikumi == Mojikumi::LineEndHalf) + .map_or(0.0, |k| line_end_trim(sg, ¶graph.compressed, ¶graph.wakan, k)); let measured_width = set_width(sg, index, trimmed, ¶.tabs, position.ind_l) + hyphen.as_ref().map_or(0.0, |g| g.adv) - end_trim; let line_start = sg.get(index).map_or(paragraph.pr.start, |g| g.byte); let line_end = sg.get(position.end).map_or(paragraph.pr.end, |g| g.byte); @@ -582,6 +656,31 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData // ends with the empty line after it (`run_paragraph_lines`). let soft_return = position.end > index && sg.get(position.end - 1).is_some_and(|g| g.ch == '\u{2028}'); let last_of_para = position.end >= n && !soft_return; + // The tracking after the line's last character: an aligned line is measured without it. The + // page of users' `.ai` files sets a centred line of tracked type half that tracking right of + // where a line measured with it goes, and a right-aligned one the whole tracking right (in + // lines that end a paragraph). The last character is the last one the line draws before a + // paragraph's end, a forced line break, or the spaces the layout wraps the line at (they hang + // past it). Spaces or a tab typed before a paragraph's end or a forced line break are the + // line's last characters, and the letter before them keeps its tracking: the page counts it in + // the 2 lines of the files that end so. Forced line breaks and wraps aren't in the files; they + // take the rule so that turning a wrap into a forced line break or a new paragraph (Break + // Text, Convert To Point Type) keeps the line where it was. A line a hyphen ends, one whose + // last character hangs, and vertical and right-to-left lines keep the tracking. + let tail = sg.get(trimmed..position.end).unwrap_or_default(); + let ends_drawn = match tail.split_last() { + None => true, + Some((last, before)) if last.ch == '\u{2028}' => before.is_empty(), + // Spaces at a wrap: the paragraph goes on. + Some(_) => position.end < n, + }; + let trailing = trimmed + .checked_sub(1) + .and_then(|k| sg.get(k)) + .filter(|g| { + ends_drawn && trimmed > index && !g.level.is_rtl() && !cx.vertical && !paragraph.rtl && hyphen.is_none() && hang.is_none() && opt_r == 0.0 + }) + .map_or(0.0, |g| if g.tracking.is_finite() { g.tracking } else { 0.0 }); LineGeometry { position, index, @@ -593,6 +692,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData ax1, width, render_width, + trailing, order, drawn, opt_l, @@ -738,6 +838,9 @@ fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &Lin // A tab ending the line counts: its text sits at the left edge, the tab up to the right one. .then(|| (line.index..line.position.end).rev().find(|&j| sg.get(j).is_some_and(|g| g.ch == '\t' && g.len > 0))) .flatten(); + // An aligned line is as wide as its characters without the tracking after the last one. + let trailing = if justify || pushed_in { 0.0 } else { line.trailing }; + let width = width - trailing; let start_x = if justify || pushed_in || last_tab.is_some() { line.ax0 - line.opt_l } else if paragraph.regions.is_none() { @@ -753,7 +856,7 @@ fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &Lin _ => line.ax1 + line.opt_r - width, } }; - LineJustification { per_space, per_gap, per_cjk, squeeze, fit, start_x, after, kashidas, last_tab } + LineJustification { per_space, per_gap, per_cjk, squeeze, fit, start_x, after, kashidas, last_tab, trailing } } /// The advance and leader of tab `glyph_index` of `line`, at pen position `x`: up to its stop @@ -780,10 +883,11 @@ fn tab_glyph<'p>( return (advance, leader); } // The width of what follows up to the line's end (nothing, when the tab ends the line), with - // the hyphen a hyphenated line ends with. + // the hyphen a hyphenated line ends with, and without the tracking after its last character, + // as a right-aligned line is measured. let after = sg.get(glyph_index + 1..line.trimmed).unwrap_or_default(); let hyphen = line.hyphen.as_ref().map_or(0.0, |g| g.adv); - let rest = if after.is_empty() { 0.0 } else { after.iter().map(|g| g.adv).sum::() - line.end_trim + hyphen }; + let rest = if after.is_empty() { 0.0 } else { after.iter().map(|g| g.adv).sum::() - line.end_trim + hyphen - justification.trailing }; ((line.ax1 + line.opt_r - rest - x).max(0.0), leader) } @@ -905,6 +1009,7 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData baseline: position.baseline, x0: start_x, x1: x_end, + trailing: justification.trailing, ascent: position.m.asc, descent: position.m.desc, first_baseline: if pen.model == LeadingModel::EmBoxTop { diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 398928ee98..de0272cb44 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -190,6 +190,7 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, baseline: 0.0, x0: 0.0, x1: 0.0, + trailing: 0.0, ascent: m.0, descent: m.1, first_baseline: 0.0, @@ -294,6 +295,8 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, .count() }; let (mut steps, mut s0, mut hung) = arrange(&sg); + // What the whole text takes along the path and what the span holds: Dynamic Text's first guess. + cx.out.path_fill = Some((steps.iter().sum(), avail + hung.0 + hung.1)); // Where the text that fits ends: before the first glyph that doesn't, which threaded text // flows on from, as from the last line of area type. let mut fits = text_len; @@ -417,6 +420,7 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, baseline: ps.y, x0: ps.x, x1: pe.x, + trailing: 0.0, ascent: m.0, descent: m.1, first_baseline: 0.0, diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index c94d25f897..0c8ffb4e2f 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -16,6 +16,7 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec { len, run: 0, adv, + tracking: 0.0, dx: 0.0, dy: 0.0, kern_shift: 0.0, @@ -32,6 +33,7 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec { tcy: None, inline: None, word_end: false, + keeps_word: false, lead: 0.0, proportional: false, vpal: None, @@ -91,14 +93,15 @@ fn indic_hyphenation_reaches_both_composers_without_splitting_marks() { KinsokuShoriType::PushOutOnly, false, false, + &[], ); assert_eq!((end, hyphen), (4, true), "{tag}"); let params = Params { justify_last: false, ragged: true, tolerance: 1.0, uniform_from: 0, hyphen_limit: 0 }; - let lines = compose(&glyphs, &|_| 4.5, &|_| 0.0, &cands, &[], ¶ms).expect("every-line composition"); + let lines = compose(&glyphs, &|_| 4.5, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms).expect("every-line composition"); assert!(lines.iter().any(|(_, hyphen)| *hyphen), "{tag}"); assert!(lines.iter().all(|(end, _)| end % 2 == 0), "{tag}: {lines:?}"); let limited = Params { hyphen_limit: 1, ..params }; - if let Some(lines) = compose(&glyphs, &|_| 4.5, &|_| 0.0, &cands, &[], &limited) { + if let Some(lines) = compose(&glyphs, &|_| 4.5, &|_| 0.0, &|_| 0.0, &cands, &[], &limited) { assert!(lines.windows(2).all(|pair| !pair[0].1 || !pair[1].1), "{tag}: {lines:?}"); } } @@ -163,7 +166,7 @@ fn greedy_wrap_keeps_an_oversized_first_cluster_and_its_source_range() { let glyphs = synthetic_glyphs(&[(0, 4, 2.0, 'ب'), (0, 4, 2.0, 'ب'), (4, 2, 1.0, 'ت')]); let (end, hyphenated) = - break_line(text, &glyphs, 0, 3.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false); + break_line(text, &glyphs, 0, 3.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false, &[]); assert!(!hyphenated); assert_eq!(end, 2, "oversized base-plus-mark cluster must stay together"); @@ -177,12 +180,12 @@ fn greedy_wrap_keeps_an_oversized_cluster_after_a_line_start_atomic() { let glyphs = synthetic_glyphs(&[(0, 4, 1.0, 'ب'), (4, 4, 2.0, 'ت'), (4, 4, 2.0, 'ت'), (8, 2, 1.0, 'ث')]); let (first_end, _) = - break_line(text, &glyphs, 0, 3.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false); + break_line(text, &glyphs, 0, 3.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false, &[]); assert_eq!(first_end, 1); assert_eq!(source_range(&glyphs, 0, first_end), 0..4); let (second_end, hyphenated) = - break_line(text, &glyphs, first_end, 3.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false); + break_line(text, &glyphs, first_end, 3.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false, &[]); assert!(!hyphenated); assert_eq!(second_end, 3, "oversized cluster at the next line start must stay together"); @@ -238,7 +241,7 @@ fn no_break_keeps_marked_characters_on_one_line() { let text = "A B"; let plain = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 1, 4.0, ' '), (2, 1, 10.0, 'B')]); let (end, hyphen) = - break_line(text, &plain, 0, 16.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false); + break_line(text, &plain, 0, 16.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[]); assert!(!hyphen); assert_eq!(end, 2, "without the mark the line ends after the space"); @@ -247,7 +250,7 @@ fn no_break_keeps_marked_characters_on_one_line() { g.no_break = true; } let (end, hyphen) = - break_line(text, &marked, 0, 16.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false); + break_line(text, &marked, 0, 16.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[]); assert!(!hyphen); assert_eq!(end, 3, "the marked words stay together even though they are wider than the line"); @@ -256,15 +259,60 @@ fn no_break_keeps_marked_characters_on_one_line() { let mut glyphs = synthetic_glyphs(&[(0, 1, 8.0, 'A'), (1, 1, 2.0, ' '), (2, 3, 10.0, '日'), (5, 3, 10.0, '本')]); glyphs[2].no_break = true; glyphs[3].no_break = true; - let (end, _) = break_line(text, &glyphs, 0, 22.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false); + let (end, _) = + break_line(text, &glyphs, 0, 22.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[]); assert_eq!(end, 2, "the marked pair moves to the next line together"); - let (end, _) = break_line(text, &glyphs, end, 15.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false); + let (end, _) = + break_line(text, &glyphs, end, 15.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[]); assert_eq!(end, 4, "on its own line the pair stays together even when it is wider than the line"); let breaks = candidates(text, &glyphs, None, Kinsoku::None); assert!(breaks.iter().all(|b| b.end != 3), "no break between the marked characters: {breaks:?}"); } +/// A soft hyphen inside a No Break run is not a place a line may break, so the word is measured +/// across it, as wide as [`break_line`] keeps it. +#[test] +fn word_width_measures_across_a_soft_hyphen_inside_a_no_break_run() { + let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 2, 0.0, '\u{00ad}'), (3, 1, 10.0, 'B'), (4, 1, 10.0, 'C')]); + // The hyphen a soft hyphen adds comes from the face, scaled to well under 10 pt. + for g in &mut glyphs { + g.sx = 0.001; + } + let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + assert!(plain < 30.0, "without the mark the word ends at the soft hyphen: {plain}"); + for g in &mut glyphs { + g.no_break = true; + } + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + assert!((marked - 30.0).abs() < 1e-9, "the marked run is measured whole: {marked}"); +} + +/// A forced line break ends the word [`breaking::word_width`] measures, inside a No Break run too, +/// and a soft hyphen just before it adds no hyphen, as [`break_line`] sets the line. +#[test] +fn word_width_stops_at_a_forced_line_break() { + let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 3, 5.0, '\u{2028}'), (4, 1, 10.0, 'B'), (5, 1, 10.0, 'C')]); + for g in &mut glyphs { + g.no_break = true; + } + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}"); + + let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 2, 0.0, '\u{00ad}'), (3, 3, 5.0, '\u{2028}'), (6, 1, 10.0, 'B')]); + // The hyphen a soft hyphen adds comes from the face, scaled to well under 10 pt. + for g in &mut glyphs { + g.sx = 0.001; + } + let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + assert!((plain - 10.0).abs() < 1e-9, "no hyphen before the forced line break: {plain}"); + for g in &mut glyphs { + g.no_break = true; + } + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}"); +} + /// Synthetic full-width characters `text`, each 10 pt wide on a 10 pt em. fn full_width(text: &str) -> Vec { let specs: Vec<(usize, usize, f64, char)> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), 10.0, ch)).collect(); @@ -285,7 +333,7 @@ fn full_width(text: &str) -> Vec { fn kinsoku_shori_type_pushes_a_closing_bracket_in_or_out() { use KinsokuShoriType::{PushInFirst, PushOutFirst, PushOutOnly}; let hung = |text: &str, width: f64, kinsoku: Kinsoku, ty: KinsokuShoriType, hanging: bool| { - break_line(text, &full_width(text), 0, width, &[], 0.0, None, Burasagari::None, kinsoku, ty, hanging, false).0 + break_line(text, &full_width(text), 0, width, &[], 0.0, None, Burasagari::None, kinsoku, ty, hanging, false, &[]).0 }; let end = |text: &str, width: f64, kinsoku: Kinsoku, ty: KinsokuShoriType| hung(text, width, kinsoku, ty, false); let text = "一二三四五六七八九十一二三四五」六"; @@ -350,7 +398,8 @@ fn kinsoku_shori_type_counts_the_gaps_that_close() { let mixed = "一二三א五六七八九十一二三四五」六"; let mut glyphs = full_width(mixed); glyphs[3].level = unicode_bidi::Level::rtl(); - let mixed_end = |ty: KinsokuShoriType| break_line(mixed, &glyphs, 0, 150.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false).0; + let mixed_end = + |ty: KinsokuShoriType| break_line(mixed, &glyphs, 0, 150.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false, &[]).0; assert_eq!(mixed_end(PushInFirst), 14, "right-to-left text on the line: 五 is pushed out with 」"); assert_eq!(mixed_end(PushOutOnly), 14); @@ -361,7 +410,8 @@ fn kinsoku_shori_type_counts_the_gaps_that_close() { for g in &mut glyphs { g.sy *= 2.0; } - let tall_end = |ty: KinsokuShoriType| break_line(tall, &glyphs, 0, 50.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false).0; + let tall_end = + |ty: KinsokuShoriType| break_line(tall, &glyphs, 0, 50.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false, &[]).0; assert_eq!(tall_end(PushInFirst), 4, "Vertical Scale does not widen the gaps: 五 is pushed out with 」"); // No gap closes inside a shaped cluster. 二 is two glyphs here, so the line has five gaps to @@ -370,7 +420,195 @@ fn kinsoku_shori_type_counts_the_gaps_that_close() { glyphs[1].adv = 5.0; let half = glyphs[1].clone(); glyphs.insert(2, half); - let split_end = |width: f64| break_line(tall, &glyphs, 0, width, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, PushInFirst, false, false).0; + let split_end = + |width: f64| break_line(tall, &glyphs, 0, width, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, PushInFirst, false, false, &[]).0; assert_eq!(split_end(54.0), 5, "五 is pushed out with 」"); assert_eq!(split_end(55.0), 7, "five gaps close by 5 pt: 」 is pushed in"); } + +/// Mojikumi: the greedy breaker measures a line as it is set, with its last character narrowed +/// (`line_end`): 」 set half width ends a measure of three and a half characters. Only the last +/// glyph of the last cluster counts, and only where the line may end. +#[test] +fn greedy_wrap_counts_the_narrower_line_end() { + use KinsokuShoriType::{PushInFirst, PushOutFirst, PushOutOnly}; + let text = "一二三」四五六"; + let glyphs = full_width(text); + let mut credit = vec![0.0; glyphs.len()]; + credit[3] = 5.0; + let end = |glyphs: &[SGlyph], width: f64, burasagari: Burasagari, line_end: &[f64]| { + break_line(text, glyphs, 0, width, &[], 0.0, None, burasagari, Kinsoku::Hard, PushOutOnly, false, false, line_end).0 + }; + assert_eq!(end(&glyphs, 35.0, Burasagari::None, &credit), 4, "」 half width fits"); + assert_eq!(end(&glyphs, 35.0, Burasagari::None, &[]), 2, "」 full width does not: 三 goes with it"); + assert_eq!(end(&glyphs, 34.0, Burasagari::None, &credit), 2, "half width is still too wide"); + // A credit that isn't finite counts for nothing, and one larger than the glyph for its advance. + assert_eq!(end(&glyphs, 35.0, Burasagari::None, &[0.0, 0.0, 0.0, f64::INFINITY]), 2); + assert_eq!(end(&glyphs, 35.0, Burasagari::None, &[0.0, 0.0, 0.0, f64::NAN]), 2); + assert_eq!(end(&glyphs, 30.0, Burasagari::None, &[0.0, 0.0, 0.0, 100.0]), 4, "at most 10 pt off"); + assert_eq!(end(&glyphs, 29.0, Burasagari::None, &[0.0, 0.0, 0.0, 100.0]), 2); + + // The line may not end after 三 (、 follows it): its credit does not keep it on the line, so 、 + // does not hang after a line already wider than the measure. + let comma = "一二三、"; + let glyphs = full_width(comma); + let end = |line_end: &[f64]| { + break_line(comma, &glyphs, 0, 25.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, PushOutOnly, false, false, line_end).0 + }; + assert_eq!(end(&[0.0, 0.0, 5.0, 0.0]), 2); + + // Kinsoku Shori Type measures both lines as they are set. Pushing 。 in leaves the line 5 pt + // wider than the measure with 。 half width, which its five gaps close. + let pushed = "一二三四」。六"; + let glyphs = full_width(pushed); + let end = |ty: KinsokuShoriType, line_end: &[f64]| { + break_line(pushed, &glyphs, 0, 50.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false, line_end).0 + }; + let stop = [0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0]; + assert_eq!(end(PushInFirst, &stop), 6, "。 is pushed in"); + assert_eq!(end(PushInFirst, &[]), 3, "full width, the gaps can't close enough"); + // Push Out First: pushing out to after 」, set half width, leaves the line 15 pt short, more + // than an em, so 四 is pushed in. + let pushed = format!("{}二」「四", "一".repeat(10)); + let glyphs = full_width(&pushed); + let end = |line_end: &[f64]| { + break_line(&pushed, &glyphs, 0, 130.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, PushOutFirst, false, false, line_end).0 + }; + let mut bracket = vec![0.0; glyphs.len()]; + bracket[11] = 5.0; + assert_eq!(end(&bracket), 14, "四 is pushed in"); + assert_eq!(end(&[]), 12, "full width, pushing out leaves the line one em short: 「四 go on"); + + // 三 is two glyphs of one cluster: the credit of its first glyph does not count. + let text = "一二三"; + let mut glyphs = full_width(text); + glyphs[2].adv = 5.0; + let half = glyphs[2].clone(); + glyphs.insert(3, half); + let end = + |line_end: &[f64]| break_line(text, &glyphs, 0, 26.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, PushOutOnly, false, false, line_end).0; + assert_eq!(end(&[0.0, 0.0, 4.0, 0.0]), 2, "the cluster stays whole and goes to the next line"); + assert_eq!(end(&[0.0, 0.0, 0.0, 4.0]), 4, "its last glyph's credit keeps it on the line"); +} + +/// Mojikumi: the every-line composer measures each candidate line with its last character narrowed +/// (`end_credit`), never by more than that glyph's advance, and a line ending in a hyphen ends with +/// the hyphen. +#[test] +fn composition_counts_the_narrower_line_end() { + let text = "一二三」四五六"; + let glyphs = full_width(text); + let cands = candidates(text, &glyphs, None, Kinsoku::Hard); + let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 }; + let lines = + |width: f64, end_credit: &dyn Fn(usize) -> f64, cands: &[Breakpoint]| compose(&glyphs, &|_| width, &|_| 0.0, end_credit, cands, &[], ¶ms); + let half = |t: usize| if t == 4 { 5.0 } else { 0.0 }; + assert_eq!(lines(35.0, &half, &cands), Some(vec![(4, false), (7, false)])); + let solid = lines(35.0, &|_| 0.0, &cands).expect("composed"); + assert!(solid.iter().all(|&(end, _)| end != 4), "」 full width does not end the first line: {solid:?}"); + // At most the glyph's advance; a credit that isn't finite counts for nothing. + assert_eq!(lines(30.0, &|t| if t == 4 { 100.0 } else { 0.0 }, &cands).and_then(|l| l.first().copied()), Some((4, false))); + assert!(lines(35.0, &|_| f64::NAN, &cands).is_some_and(|l| l.iter().all(|&(end, _)| end != 4))); + // No credit for a line ending in a hyphen. + let hyphenated = [Breakpoint { end: 4, hyphen: 1.0 }]; + assert_eq!(lines(38.0, &half, &hyphenated), None); + assert_eq!(lines(38.0, &half, &[Breakpoint { end: 4, hyphen: 0.0 }]), Some(vec![(4, false), (7, false)])); +} + +/// The glyphs of `text`, each 10 pt wide, with Korean words kept whole unless `anywhere` (Korean +/// Line Break Anywhere on). +fn korean(text: &str, anywhere: bool) -> Vec { + let mut glyphs = full_width(text); + if !anywhere { + crate::shape::keep_korean_words(&mut glyphs); + } + glyphs +} + +/// Korean Line Break Anywhere off: both composers break a Korean word only at its spaces, so a +/// word that doesn't fit moves to the next line whole; on, they break between its syllables. +#[test] +fn korean_words_break_at_spaces_unless_line_break_anywhere() { + use KinsokuShoriType::PushOutOnly; + let text = "가나다 라마바"; + let greedy = + |g: &[SGlyph], width: f64| break_line(text, g, 0, width, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, PushOutOnly, false, false, &[]).0; + let ends = |g: &[SGlyph]| candidates(text, g, None, Kinsoku::Hard).iter().map(|b| b.end).collect::>(); + // 50 pt holds "가나다 라" and not "가나다 라마". + assert_eq!(greedy(&korean(text, false), 50.0), 4, "off: the line ends at the space"); + assert_eq!(greedy(&korean(text, true), 50.0), 5, "on: the line ends after 라"); + assert_eq!(ends(&korean(text, false)), [4]); + assert_eq!(ends(&korean(text, true)), [1, 2, 4, 5, 6]); + let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 }; + let off = korean(text, false); + let cands = candidates(text, &off, None, Kinsoku::Hard); + assert_eq!(compose(&off, &|_| 50.0, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms), Some(vec![(4, false), (7, false)])); + // The first word is measured whole, as the line loop measures it. + assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard), 30.0); + assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard), 10.0); + // A word wider than the line still breaks, at the syllable that overflows. + assert_eq!(greedy(&korean("가나다라마바", false), 25.0), 2); + // A soft return still ends the line. + let soft = "가나\u{2028}다라"; + assert_eq!( + break_line(soft, &korean(soft, false), 0, 100.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, PushOutOnly, false, false, &[]).0, + 3 + ); +} + +/// Korean Line Break Anywhere off keeps the Han, kana and full-width letters of a Korean word with +/// it, lets the line break after East Asian punctuation in it (as kinsoku allows), and leaves +/// text without Hangul its own breaks. On, No Break still keeps its characters together. +#[test] +fn korean_words_keep_their_letters_and_break_after_punctuation() { + let ends = |text: &str, anywhere: bool| candidates(text, &korean(text, anywhere), None, Kinsoku::Hard).iter().map(|b| b.end).collect::>(); + assert_eq!(ends("漢字한국 ab", false), [5], "Han in a Korean word stays with it"); + assert_eq!(ends("日本語 한국어", false), [1, 2, 4], "Japanese keeps its breaks"); + assert_eq!(ends("가나。다라", false), [3], "after the full stop"); + assert_eq!(ends("「가나」다", false), [4], "after the closing bracket, not the opening one"); + assert_eq!(ends("가나AB다", false), Vec::::new(), "full-width letters stay with it"); + let text = "가나다라"; + let mut glyphs = korean(text, true); + for g in &mut glyphs[1..3] { + g.no_break = true; + } + let end = break_line(text, &glyphs, 0, 25.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false, &[]).0; + assert_eq!(end, 1, "No Break keeps 나다 together"); +} + +/// Hyphenation adds no hyphen to a Korean word, even where a hyphenation exception marks one: the +/// word that overflows breaks without one, and the every-line composer is offered no hyphenated +/// break in it. +#[test] +fn korean_words_take_no_hyphen() { + let opts = HyphenationOptions { words_longer_than: 0, after_first: 1, before_last: 1, ..Default::default() }; + let text = "가나다라"; + crate::hyphen::with_hyphenation_exceptions_for_test("가나-다라", || { + let glyphs = korean(text, false); + let line = break_line( + text, + &glyphs, + 0, + 25.0, + &[], + 0.0, + Some((&opts, 0.0)), + Burasagari::None, + Kinsoku::Hard, + KinsokuShoriType::PushOutOnly, + false, + false, + &[], + ); + assert_eq!(line, (2, false)); + assert!(candidates(text, &glyphs, Some(&opts), Kinsoku::Hard).iter().all(|b| b.hyphen == 0.0)); + }); + // Nor between the Latin letters of a word that also holds Hangul. + let text = "가나foobar"; + crate::hyphen::with_hyphenation_exceptions_for_test("가나foo-bar", || { + let hyphens = + |anywhere: bool| candidates(text, &korean(text, anywhere), Some(&opts), Kinsoku::Hard).iter().filter(|b| b.hyphen > 0.0).count(); + assert_eq!(hyphens(false), 0); + assert_eq!(hyphens(true), 1, "on, the word's Latin letters hyphenate as before"); + }); +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 011bb6eb20..d2e3cf1dc8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -48,8 +48,8 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; -pub use layout::{decorations, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::spacing_scale; +pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; +pub use shape::{line_start_space, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; @@ -285,6 +285,14 @@ pub struct LineInfo { pub x0: f64, /// Right edge of the line content, trailing spaces excluded. pub x1: f64, + /// The tracking after the line's last character (in `x1` and in its glyph's advance) that the + /// line's alignment leaves out: the line is aligned as if it ended this much before `x1` (a + /// centred line is centred and a right-aligned one, or the text after the last tab of + /// right-aligned area type, ends there; a left-aligned line starts where it would anyway). 0 + /// when spaces or a tab typed before a paragraph's end or a forced line break end the line, + /// when a hyphen ends it or its last character hangs, in justified lines and lines that push + /// characters in, in vertical and right-to-left lines, and in type on a path. + pub trailing: f64, pub ascent: f64, pub descent: f64, /// Area type: how far the line's baseline sits below the top of its frame cell (inside the @@ -362,9 +370,14 @@ pub struct TextLayout { pub on_path: bool, /// Area type: the frame cells text flowed into (one per row/column). pub frames: Vec, - /// Shrink Text to Fit: the factor the text's sizes, leading and baseline shifts were scaled - /// by to fit its frame (1.0 when the text is not shrunk). + /// Shrink Text to Fit and Dynamic Text: the factor the text's sizes, leading and baseline + /// shifts were scaled by to fit its frame or the span of its path (1.0 when the text is not + /// scaled). Shrink Text to Fit keeps it at most 1; Dynamic Text may take it above 1. pub fit_scale: f64, + /// Type on a path: the length the arranged glyphs take along the path, and the length of the + /// span between the brackets with what hangs outside them ([`Self::fit_scale`]'s first guess + /// for Dynamic Text). `None` for other type and for a path with no length. + pub path_fill: Option<(f64, f64)>, /// Inline graphics, in text order. pub inlines: Vec, /// List markers, in text order. @@ -384,6 +397,7 @@ impl Default for TextLayout { on_path: false, frames: Vec::new(), fit_scale: 1.0, + path_fill: None, inlines: Vec::new(), markers: Vec::new(), } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index a58e8ef57e..ba7339bc6b 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -30,12 +30,18 @@ pub(crate) struct SGlyph { pub run: usize, /// Advance in points (tracking, manual kerning and horizontal scale applied). pub adv: f64, + /// The tracking `adv` holds after the glyph's character, in points: on the last glyph of its + /// cluster, 0 on the others. An aligned line leaves its last character's out of its width + /// ([`crate::layout`]). + pub tracking: f64, /// Offset from the pen position, y down. pub dx: f64, pub dy: f64, /// Right to left: the run's manual kerning, which moves the glyph right along the baseline, /// outside its Character Rotation; with whole-point advances, the difference the kerning makes - /// to the cluster's rounded advance. 0 otherwise. + /// to the cluster's rounded advance. Left to right and in vertical type: the space before a + /// line's first character ([`CharStyle::kerning_before`]), which moves it along the line the + /// same way. 0 otherwise. pub kern_shift: f64, /// Outline scale (font units -> points). pub sx: f64, @@ -70,6 +76,9 @@ pub(crate) struct SGlyph { /// A word of a script written without spaces (Thai, Lao, Khmer, Myanmar) ends after the /// glyph's cluster, so a line may break there ([`mark_word_ends`]). pub word_end: bool, + /// A letter of a Korean word kept whole (Korean Line Break Anywhere off): a CJK character + /// here doesn't let the line break after it ([`keep_korean_words`]). + pub keeps_word: bool, /// No Break (Character panel menu): keep this glyph on the same line as the neighbouring /// glyphs that have it. pub no_break: bool, @@ -152,7 +161,7 @@ impl SGlyph { self.is_space() || self.word_end || matches!(self.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/' | SOFT_HYPHEN | '\u{2028}') - || is_cjk(self.ch) + || (is_cjk(self.ch) && !self.keeps_word) } /// A soft (discretionary) hyphen: invisible unless a line breaks after it. pub fn is_soft_hyphen(&self) -> bool { @@ -177,6 +186,7 @@ pub(crate) fn hyphen_glyph(g: &SGlyph) -> SGlyph { let mut h = g.clone(); h.gid = gid; h.adv = g.face.advance(gid) * g.sx; + h.tracking = 0.0; h.dx = 0.0; h.dy = 0.0; h.kern_shift = 0.0; @@ -320,6 +330,30 @@ pub(crate) fn mark_word_ends(text: &str, start: usize, sg: &mut [SGlyph]) { } } +/// Korean Line Break Anywhere off: mark the letters of each Korean word of `sg` (a paragraph's +/// glyphs) as [`SGlyph::keeps_word`], so the word breaks only at its spaces and punctuation. A +/// Korean word is the run of glyphs between spaces and forced line breaks when any of them is +/// Hangul; its Han, kana and full-width letters are kept with it. Punctuation in it still lets +/// the line break after it, and runs without Hangul keep their own breaks. +pub(crate) fn keep_korean_words(sg: &mut [SGlyph]) { + let mut start = 0; + while start < sg.len() { + let len = sg[start..].iter().position(|g| g.is_space() || g.ch == '\u{2028}').unwrap_or(sg.len() - start); + let word = &mut sg[start..start + len]; + if word.iter().any(|g| g.inline.is_none() && is_hangul(g.ch)) { + for g in word.iter_mut().filter(|g| g.inline.is_none()) { + g.keeps_word = g.ch.is_alphanumeric(); + } + } + start += len + 1; + } +} + +/// Is `c` Hangul: a syllable, a jamo or a compatibility jamo (full or half width)? +pub(crate) fn is_hangul(c: char) -> bool { + c.script() == Script::Hangul +} + pub(crate) fn is_cjk(c: char) -> bool { matches!(c as u32, 0x2E80..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0xFF00..=0xFFEF | 0x20000..=0x2FFFF) } @@ -517,6 +551,37 @@ pub(crate) fn shape_runs( } } +/// [`CharStyle::kerning_before`] of the character at `byte` of `text` in style `st`, in points of +/// `spacing_em`: the space before it when it starts a line by itself ([`crate::edit::starts_line`]), else 0. Its +/// cluster takes the space in its advance, as manual kerning takes the space after a character, +/// and left to right (and in vertical type) its glyphs are drawn that much later on the line +/// (#5111). Right to left, the line starts at its right: the space the advance gains is already on +/// that side. +fn space_before(text: &str, byte: usize, st: &CharStyle, spacing_em: f64) -> f64 { + if st.kerning_before == 0.0 || !crate::edit::starts_line(text, byte) || text.get(byte..).is_some_and(|rest| rest.starts_with(['\n', '\u{2028}'])) + { + return 0.0; + } + Some(st.kerning_before / 1000.0 * spacing_em).filter(|s| s.is_finite()).unwrap_or(0.0) +} + +/// The space before the character at `byte` of `text` in style `st`, in points, as the layout sets +/// it ([`CharStyle::kerning_before`]): its thousandths of the em the character is set in, when it +/// starts a line by itself, else 0. For writers that place a line's first character themselves. +pub fn line_start_space(text: &str, byte: usize, st: &CharStyle, vertical: bool) -> f64 { + let small = st.small_caps.is_some() && !st.all_caps && text.get(byte..).and_then(|s| s.chars().next()).is_some_and(char::is_lowercase); + space_before(text, byte, st, glyph_size(st, small) * spacing_scale(st, vertical)) +} + +/// The size characters in style `st` are shaped at: Superscript, Subscript and synthesized Small +/// Caps (`small`: a lowercase letter in them) shrink the glyphs; line metrics keep the full size. +fn glyph_size(st: &CharStyle, small: bool) -> f64 { + let full = st.size.max(0.0); + let (pos_scale, _) = st.position.scale_shift(full); + let small_scale = if small { st.small_caps.unwrap_or(100.0) / 100.0 } else { 1.0 }; + full * pos_scale * small_scale +} + /// Line segments of a glyph outline in font units, cached for the current shaping pass. type Profile = Vec<(f64, f64, f64, f64)>; type CachedProfile = (Profile, (f64, f64)); @@ -812,8 +877,11 @@ fn source_run_at(runs: &[(Range, &CharStyle)], span: &Range, byte: /// Can one glyph draw characters in styles `a` and `b`? Only when the styles are equal, except that /// horizontal type (`vertical` false) does not read Standard Vertical Roman Alignment or the -/// tate-chu-yoko offsets, so styles that differ only in those are drawn alike there. +/// tate-chu-yoko offsets, so styles that differ only in those are drawn alike there. The space +/// before a line's first character ([`space_before`]) is never read inside a cluster, which takes it +/// from its first character, so it doesn't split a ligature either. fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { + let b = &CharStyle { kerning_before: a.kerning_before, ..b.clone() }; if a == b { return true; } @@ -831,7 +899,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { /// They do when they differ only in paint and stroke, underline and strikethrough, overprint, the /// character style's name, leading, baseline shift, rotation, Character Alignment, Character /// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its -/// run's, see [`shape_segment`]) and the tracking, as long as the tracking keeps or drops standard +/// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]) +/// and the tracking, as long as the tracking keeps or drops standard /// ligatures alike ([`crate::features::ligatures_suppressed_by`]). fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { // Every field is named, so that a new attribute has to be sorted into one group or the other. @@ -844,6 +913,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { leading: _, tracking, kerning: _, + kerning_before: _, optical_kerning: _, baseline_shift: _, h_scale, @@ -943,8 +1013,9 @@ fn shaping_script(c: char) -> Script { /// /// The art is scaled uniformly to `scale` x the font size tall, its left edge on the pen and its /// vertical centre on the middle of the cap height raised by the inline's shift (see -/// [`InlineArt`]). Its advance is the scaled art width plus tracking and its character's manual -/// kerning, which right to left in horizontal type also moves the art right by the value, as it +/// [`InlineArt`]). Its advance is the scaled art width plus tracking, its character's manual +/// kerning and the space before it at a line's start ([`space_before`]). Right to left in +/// horizontal type the manual kerning also moves the art right by the value, as it /// moves a letter's glyph. The art doesn't take the run's Horizontal Scale; the tracking and the /// kerning do, as after a letter ([`spacing_scale`]). The glyph's ascent and descent grow to the /// art's extent so a tall graphic opens up its line. A missing symbol takes a square of the same @@ -976,9 +1047,10 @@ fn inline_glyph( _ => (kurbo::Affine::IDENTITY, h, None), }; let spacing_em = size * spacing_scale(st, vertical); - let tracking = st.tracking / 1000.0 * spacing_em; + let tracking = Some(st.tracking / 1000.0 * spacing_em).filter(|t| t.is_finite()).unwrap_or(0.0); let manual_kern = st.kerning.map(|v| v / 1000.0 * spacing_em).filter(|k| k.is_finite()).unwrap_or(0.0); - let adv = width + if tracking.is_finite() { tracking } else { 0.0 } + manual_kern; + let before = space_before(text, range.start, st, spacing_em); + let adv = width + tracking + manual_kern + before; SGlyph { face: face.clone(), gid: 0, @@ -986,9 +1058,10 @@ fn inline_glyph( len: range.len().max(1), run, adv: if adv.is_finite() { adv } else { 0.0 }, + tracking: if adv.is_finite() { tracking } else { 0.0 }, dx: 0.0, dy: 0.0, - kern_shift: if level.is_rtl() && !vertical { manual_kern } else { 0.0 }, + kern_shift: if level.is_rtl() && !vertical { manual_kern } else { before }, // Not used to draw (the art has its own transform), but they make the glyph's em box // its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a // character of its run's size, whatever its scale (see `layout::glyph_em`). @@ -1011,6 +1084,7 @@ fn inline_glyph( level, inline: Some(InlineBox { art: drawn, xf }), word_end: false, + keeps_word: false, no_break: st.no_break, vertical_roman: false, cursive: false, @@ -1073,9 +1147,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let cursive = text_seg.chars().map(|c| c.script()).find(|s| !matches!(s, Script::Common | Script::Inherited)).is_some_and(joins); let full = st.size.max(0.0); // Superscript/subscript and small capitals shrink the glyphs; line metrics keep the full size. - let (pos_scale, pos_shift) = st.position.scale_shift(full); - let small_scale = if small { st.small_caps.unwrap_or(100.0) / 100.0 } else { 1.0 }; - let size = full * pos_scale * small_scale; + let (_, pos_shift) = st.position.scale_shift(full); + let size = glyph_size(st, small); let k = size / face.upem; let km = full / face.upem; let hs = st.h_scale / 100.0; @@ -1396,19 +1469,24 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe None => gid, }; let mut kern_shift = 0.0; + let mut tracked = 0.0; if ch == SOFT_HYPHEN || ch == '\u{2028}' { adv = 0.0; } else { let manual_kern = gst.kerning.map(|v| v / 1000.0 * spacing_em).unwrap_or(0.0); + let before = space_before(text, cl, gst, spacing_em); // Manual kerning spaces a character from the next one in reading order. Right to left, // that one is drawn to its left: the cluster's glyphs move right along the baseline by // the value, so that the space its last glyph's advance gains is at the cluster's left. + // The space before a line's first character moves them the other way. if level.is_rtl() && !feats.vertical { kern_shift = manual_kern; + } else { + kern_shift = before; } if last_in_cluster { - let tracking = gst.tracking / 1000.0 * spacing_em; - adv += tracking + manual_kern; + tracked = gst.tracking / 1000.0 * spacing_em; + adv += tracked + manual_kern + before; } } out.push(SGlyph { @@ -1418,6 +1496,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe len: end.saturating_sub(cl).max(1), run, adv, + tracking: tracked, dx: xo as f64 * k * hs, dy: -(yo as f64) * k * vs, kern_shift, @@ -1438,6 +1517,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe level: *level, inline: None, word_end: false, + keeps_word: false, no_break: gst.no_break, vertical_roman: gst.standard_vertical_roman, cursive, diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index aab7f0e1f0..1300920ad1 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -414,6 +414,41 @@ pub fn vertical_punctuation_font(alternates: bool) -> Option> { Some(builder.build()) } +/// The family of [`full_width_font`]. +pub const FULL_WIDTH_FAMILY: &str = "Fullwidthtest Sans"; + +/// The ideographs and Japanese punctuation [`full_width_font`] sets one em wide. +pub const FULL_WIDTH_CHARS: &str = "一二三四五六「」、。"; + +/// A test-only cmap over bundled Source Sans 3: [`FULL_WIDTH_CHARS`] use the one-em-wide glyph of +/// U+2318, so Japanese composition is tested without OS fonts; Latin letters and the space keep +/// their own glyphs. +pub fn full_width_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let wide = write_fonts::types::GlyphId::new(charmap.map('\u{2318}')?.to_u32()); + let latin = ('A'..='Z').chain('a'..='z').chain([' ']); + let mut mappings: Vec<(char, write_fonts::types::GlyphId)> = FULL_WIDTH_CHARS.chars().map(|c| (c, wide)).collect(); + for c in latin { + mappings.push((c, write_fonts::types::GlyphId::new(charmap.map(c)?.to_u32()))); + } + let cmap = Cmap::from_mappings(mappings).ok()?; + let name = name_table(&[(1, FULL_WIDTH_FAMILY), (2, "Regular"), (4, "Fullwidthtest Sans Regular"), (6, "FullwidthtestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GSUB") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`half_form_font`]. pub const HALF_FORM_FAMILY: &str = "Halftest Sans"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index a7a0724ee1..bcb233b8c3 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -19,6 +19,7 @@ mod inline; mod joiners; mod justify; mod kept_layouts; +mod kerning_before; mod ligature_carets; mod path_joins; mod ruby; @@ -252,6 +253,137 @@ fn tracking_and_manual_kerning_take_the_horizontal_scale() { } } +/// A centred or right-aligned line is as wide as its characters without the tracking after the +/// last one, as the page of users' `.ai` files aligns tracked lines: centred half that tracking +/// right of a line measured with it, right-aligned the whole tracking right, so the last glyph's +/// own advance ends on the anchor or the frame's edge. The tracking is still in the last glyph's +/// advance (the caret after it, and a selection of it, keep it). +#[test] +fn an_aligned_line_leaves_its_last_characters_tracking_out_of_its_width() { + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + // 200/1000 of a 20 pt em: 4 pt after each character, also at 50% Horizontal Scale with 400. + for (tracking, h_scale, after) in [(200.0, 100.0, 4.0), (-100.0, 100.0, -2.0), (400.0, 50.0, 4.0)] { + let st = CharStyle { tracking, h_scale, ..style(20.0) }; + let mut t = point("Wave", st.clone()); + let w = width(&t); + let start = |t: &TextObject| layout(db(), t).glyphs[0].origin.x; + let end = |t: &TextObject| { + let l = layout(db(), t); + let last = l.glyphs.last().unwrap(); + last.origin.x + last.advance + }; + assert!(near(start(&t), 0.0), "left aligned point type starts at its anchor"); + t.para.justify = Justify::Center; + assert!(near(start(&t), -(w - after) / 2.0), "{tracking} at {h_scale}%: centred from {}, not {}", -(w - after) / 2.0, start(&t)); + t.para.justify = Justify::Right; + assert!(near(end(&t) - after, 0.0), "{tracking} at {h_scale}%: right aligned, the last glyph ends {} past the anchor", end(&t) - after); + let plain = layout(db(), &TextObject { runs: vec![TextRun::new("Wave", CharStyle { tracking: 0.0, ..st.clone() })], ..t.clone() }); + let tracked = layout(db(), &t); + let last_advance = |l: &TextLayout| l.glyphs.last().unwrap().advance; + assert!(near(last_advance(&tracked) - last_advance(&plain), after), "{tracking}: the last glyph keeps its tracking"); + // Area type: the same in its frame. + let frame = Rect::new(0.0, 0.0, 300.0, 100.0); + let centred = area("Wave", st.clone(), frame, Justify::Center); + assert!(near(start(¢red), (300.0 - (w - after)) / 2.0), "{tracking}: centred area type starts at {}", start(¢red)); + let right = area("Wave", st.clone(), frame, Justify::Right); + assert!(near(end(&right) - after, 300.0), "{tracking}: right aligned area type ends {} past its edge", end(&right) - after - 300.0); + // A line that ends in a space keeps its last letter's tracking: the space comes after it. + let spaced = area("Wave ", st, frame, Justify::Right); + let l = layout(db(), &spaced); + let e = l.glyphs.iter().find(|g| g.byte == 3).unwrap(); + assert!(near(e.origin.x + e.advance, 300.0), "{tracking}: before a space the line ends at {}", e.origin.x + e.advance); + } +} + +/// Right-aligned area type with a tab sets the text after its last tab as it sets a right-aligned +/// line: the last glyph's advance, less the tracking after it, ends on the frame's edge. +#[test] +fn the_text_after_the_last_tab_of_right_aligned_type_leaves_its_last_tracking_out() { + let frame = Rect::new(0.0, 0.0, 336.0, 100.0); + let lay = layout(db(), &area("Item\t24.00", CharStyle { tracking: 200.0, ..style(13.0) }, frame, Justify::Right)); + assert!(lay.glyphs[0].origin.x.abs() < 1e-6, "the item starts at the left edge: {}", lay.glyphs[0].origin.x); + let last = lay.glyphs.last().unwrap(); + let after = 200.0 / 1000.0 * 13.0; + let end = last.origin.x + last.advance - after; + assert!((end - 336.0).abs() < 1e-6, "the price ends at {end}, not on the edge"); +} + +/// Which lines leave the tracking after their last character out of their width +/// (`LineInfo::trailing`): those a paragraph's end, a forced line break or a wrap ends, also a +/// wrap at a space (the space hangs past the line). Spaces typed before a paragraph's end or a +/// forced line break end the line themselves, and the letter before them keeps its tracking. So +/// do a line a hyphen ends, one whose last character hangs (burasagari, Optical Margin +/// Alignment), a justified line, right-to-left lines and lines ending in a right-to-left run, +/// vertical type and type on a path. +#[test] +fn which_lines_leave_the_tracking_after_their_last_character_out() { + let st = CharStyle { tracking: 200.0, ..style(20.0) }; + // 200/1000 of a 20 pt em. + let t = 4.0; + let trailing = |o: &TextObject| layout(db(), o).lines.iter().map(|l| l.trailing).collect::>(); + let centred = |text: &str| { + let mut o = point(text, st.clone()); + o.para.justify = Justify::Center; + o + }; + let narrow = Rect::new(0.0, 0.0, 90.0, 300.0); + assert_eq!(trailing(&area("Wave Wave", st.clone(), narrow, Justify::Center)), [t, t], "a wrap at a space"); + assert_eq!(trailing(&area("Wave-Wave", st.clone(), narrow, Justify::Center)), [t, t], "a wrap after a hyphen"); + assert_eq!(trailing(¢red("Wave\u{2028}Wave")), [t, t], "a forced line break"); + assert_eq!(trailing(¢red("Wave \u{2028}Wave")), [0.0, t], "a space typed before a forced line break"); + assert_eq!(trailing(¢red("Wave \nWave")), [0.0, t], "a space typed before a paragraph's end"); + // Hyphenated: the hyphen ends the line, and has no tracking. + let mut hyphenated = area("internationalization", st.clone(), Rect::new(0.0, 0.0, 120.0, 300.0), Justify::Right); + hyphenated.para.hyphenate = true; + hyphenated.para.composer = vectorcraft_doc::Composer::SingleLine; + let lay = layout(db(), &hyphenated); + assert!(lay.lines.len() > 1 && lay.lines[0].end < "internationalization".len(), "the word is hyphenated: {:?}", lay.lines); + assert_eq!(lay.lines[0].trailing, 0.0, "a hyphenated line"); + // Justified: justification counts it (only the paragraph's last line is aligned). + assert_eq!(trailing(&area("Wave Wave", st.clone(), narrow, Justify::JustifyLeft)), [0.0, t], "a justified line"); + // A last character that hangs. + let mut hanging = area("あいう。", st.clone(), Rect::new(0.0, 0.0, 300.0, 100.0), Justify::Center); + hanging.para.burasagari = vectorcraft_doc::Burasagari::Forced; + assert_eq!(trailing(&hanging), [0.0], "a full stop burasagari hangs"); + let mut optical = area("Wave.", st.clone(), Rect::new(0.0, 0.0, 300.0, 100.0), Justify::Right); + optical.optical_margin = true; + assert_eq!(trailing(&optical), [0.0], "a full stop Optical Margin Alignment hangs"); + optical.runs = vec![TextRun::new("Wave", st.clone())]; + assert_eq!(trailing(&optical), [t], "a letter that doesn't hang"); + // Right to left: a right-to-left paragraph ending in Latin, a Latin one ending in Hebrew. + assert_eq!(trailing(¢red("שלום abc")), [0.0], "a right-to-left paragraph"); + assert_eq!(trailing(¢red("abc שלום")), [0.0], "a right-to-left run ending the line"); + // Vertical type. + let mut vertical = centred("Wave"); + vertical.vertical = true; + assert_eq!(trailing(&vertical), [0.0], "vertical type"); + // Type on a path, centred: as wide as all its advances. + let mut on_path = centred("Wave"); + let w = width(&on_path); + let mut line = kurbo::BezPath::new(); + line.move_to((0.0, 50.0)); + line.line_to((500.0, 50.0)); + on_path.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let lay = layout(db(), &on_path); + assert_eq!(lay.lines[0].trailing, 0.0, "type on a path"); + assert!((lay.glyphs[0].origin.x - (500.0 - w) / 2.0).abs() < 1e-6, "{}", lay.glyphs[0].origin.x); +} + +/// Justification… Desired Glyph Scaling scales each glyph's advance with the tracking in it: an +/// aligned line leaves out its last character's tracking as scaled. +#[test] +fn an_aligned_line_leaves_out_its_last_tracking_as_glyph_scaling_sets_it() { + let mut t = point("Wave", CharStyle { tracking: 400.0, ..style(20.0) }); + t.para.justify = Justify::Center; + t.para.justification.glyph_scaling = [80.0, 90.0, 110.0]; + let lay = layout(db(), &t); + let w: f64 = lay.glyphs.iter().map(|g| g.advance).sum(); + // 400/1000 of a 20 pt em, at 90%. + let left_out = 8.0 * 0.9; + assert!((lay.lines[0].trailing - left_out).abs() < 1e-9, "{}", lay.lines[0].trailing); + assert!((lay.glyphs[0].origin.x + (w - left_out) / 2.0).abs() < 1e-6, "centred from {}", lay.glyphs[0].origin.x); +} + /// The factor tracking and manual kerning take from the Horizontal Scale: the scale in horizontal /// type, 1 in vertical type and for a scale that isn't a positive number. #[test] @@ -2384,6 +2516,41 @@ fn thai_loanwords_stay_whole() { assert!(l.lines.iter().all(|ln| ln.end <= word || ln.end >= word + "โปรแกรม".len()), "{lines:?}"); } +/// Korean Line Break Anywhere (a paragraph attribute): off, a Korean word that does not fit moves +/// to the next line whole, with either composer and in vertical type; on, the line breaks between +/// its syllables. Each paragraph follows its own setting. +#[test] +fn korean_words_stay_whole_unless_line_break_anywhere_is_on() { + let text = "가나다 라마바"; + let first = "가나다 ".len(); + let measure = |vertical: bool| { + let mut t = point("가나다 라", style(20.0)); + t.vertical = vertical; + layout(db(), &t).glyphs.iter().map(|g| g.advance).sum::() + }; + let ends = |t: &TextObject| layout(db(), t).lines.iter().map(|l| l.end).collect::>(); + for vertical in [false, true] { + let fits = measure(vertical); + let frame = if vertical { Rect::new(0.0, 0.0, 400.0, fits + 1.0) } else { Rect::new(0.0, 0.0, fits + 1.0, 400.0) }; + for composer in [Composer::SingleLine, Composer::EveryLine] { + let mut t = area(text, style(20.0), frame, Justify::Left); + (t.vertical, t.para.composer) = (vertical, composer); + assert_eq!(ends(&t), [first, text.len()], "{composer:?} vertical {vertical}: off"); + t.para.korean_line_break_anywhere = true; + let on = ends(&t); + assert!(on.iter().any(|&e| e != first && e != text.len()), "{composer:?} vertical {vertical}: on {on:?}"); + } + } + // Per paragraph: the first breaks between syllables, the second between words. + let fits = measure(false); + let mut t = area(&format!("{text}\n{text}"), style(20.0), Rect::new(0.0, 0.0, fits + 1.0, 400.0), Justify::Left); + t.para.composer = Composer::SingleLine; + let anywhere = vectorcraft_doc::ParaStyle { korean_line_break_anywhere: true, ..t.para.clone() }; + t.set_paragraph_styles(vec![anywhere, t.para.clone()]); + let second = text.len() + 1; + assert_eq!(ends(&t), ["가나다 라".len(), text.len(), second + first, second + text.len()]); +} + /// No Break (Character panel menu) keeps the marked words on one line, where the same text wraps /// at the space without the mark. #[test] diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index d7cd584013..69f9bdb668 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -176,6 +176,7 @@ fn lines_of_clusters(lines: &[&[(usize, usize, f64)]], rtl: bool) -> TextLayout baseline, x0: 0.0, x1: x, + trailing: 0.0, ascent: 10.0, descent: 3.0, first_baseline: 0.0, diff --git a/crates/text/src/tests/fit.rs b/crates/text/src/tests/fit.rs index 415ddc90a0..1f9d55aa42 100644 --- a/crates/text/src/tests/fit.rs +++ b/crates/text/src/tests/fit.rs @@ -1,8 +1,8 @@ -//! Area type fitting: Shrink Text to Fit. +//! Area type fitting (Shrink Text to Fit) and type on a path fitting (Dynamic Text). use crate::*; use kurbo::Shape; -use vectorcraft_doc::{AreaFit, CharStyle, TextKind}; +use vectorcraft_doc::{AreaFit, CharStyle, TextKind, TextRun}; use vectorcraft_geom::PathData; const COPY: &str = "Typography is the craft of arranging type to make written language legible, readable and appealing when displayed. \ @@ -67,6 +67,18 @@ fn scaled_area_shrink_accepts_small_local_sizes_and_uses_document_tenths() { assert!((document_size * 10.0 - (document_size * 10.0).round()).abs() < 1e-6); } +/// A size that measures the cap height shrinks in steps of 0.1 pt of the size the Character panel +/// shows, not of the em size the layout sets it at. +#[test] +fn shrink_text_steps_the_size_the_character_panel_shows() { + let mut t = area(COPY, 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(30.0)); + t.runs[0].style.font_height_reference = vectorcraft_doc::text::FontHeightReference::CapHeight; + let l = layout(db(), &t); + assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale); + let shown = 14.0 * l.fit_scale; + assert!((shown * 10.0 - (shown * 10.0).round()).abs() < 1e-6, "{shown}"); +} + #[test] fn shrink_text_respects_its_minimum() { let t = area(COPY, 14.0, Rect::new(0.0, 0.0, 120.0, 40.0), shrink(90.0)); @@ -174,3 +186,182 @@ fn shrink_text_follows_top_to_top_leading_and_character_alignment() { } assert!(layout(db(), &bigger).overflow); } + +/// Type on a path `path` set at `size`, with Dynamic Text on. +fn dynamic_on(text: &str, size: f64, path: &kurbo::BezPath, end: Option) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, CharStyle { size, ..CharStyle::default() }); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(path), start: 0.0, end }; + t.xf = Affine::IDENTITY; + t.dynamic_text = true; + t +} + +/// Type on a straight path `len` points long, set at `size`, with Dynamic Text on. +fn dynamic(text: &str, size: f64, len: f64) -> TextObject { + dynamic_on(text, size, &kurbo::Line::new((0.0, 100.0), (len, 100.0)).to_path(0.1), None) +} + +/// `t` laid out at `f` times its sizes with Dynamic Text off. +fn fixed_at(t: &TextObject, f: f64) -> TextLayout { + let mut s = scaled(t, f); + s.dynamic_text = false; + layout(db(), &s) +} + +/// Checks that Dynamic Text laid `t` out at the largest tenth of a point that fits: the first run's +/// drawn size is whole tenths, the layout is that of `t` at that size, and a tenth more overflows. +fn assert_fills(t: &TextObject, what: &str) -> TextLayout { + let l = layout(db(), t); + let size = t.runs[0].style.size * l.fit_scale; + assert!((size * 10.0 - (size * 10.0).round()).abs() < 1e-6, "{what}: {size}"); + assert!(!l.overflow, "{what}: fits at {size}"); + let same = fixed_at(t, l.fit_scale); + assert_eq!((same.glyphs.len(), same.overflow), (l.glyphs.len(), false), "{what}"); + assert!(fixed_at(t, (size + 0.1) / t.runs[0].style.size).overflow, "{what}: {size} + 0.1 pt still fits"); + l +} + +/// Dynamic Text: short text grows and long text shrinks to fill the span of its path, at the +/// largest size in tenths of a point that does not run past the end bracket, and the line then +/// takes the span's length within one step. +/// +#[test] +fn dynamic_text_fills_the_span_of_its_path() { + let short = dynamic("Fill me", 12.0, 400.0); + let mut off = short.clone(); + off.dynamic_text = false; + assert_eq!(layout(db(), &off).fit_scale, 1.0, "off, the text keeps its size"); + let l = assert_fills(&short, "short"); + assert!(l.fit_scale > 2.0, "short text grows: {}", l.fit_scale); + let (used, room) = l.path_fill.unwrap_or_default(); + let size = 12.0 * l.fit_scale; + assert!(used <= room + 1e-6 && room - used <= used * 0.1 / size * 1.5 + 1e-6, "{used} of {room} at {size}"); + let long = dynamic(COPY, 12.0, 400.0); + assert!(fixed_at(&long, 1.0).overflow); + let l = assert_fills(&long, "long"); + assert!(l.fit_scale < 1.0, "long text shrinks: {}", l.fit_scale); + // Deterministic. + assert_eq!(layout(db(), &long).fit_scale, l.fit_scale); +} + +/// Dynamic Text refits to the brackets: an end bracket nearer the start makes the text smaller, and +/// a closed path with no end bracket holds the text once round. +/// +#[test] +fn dynamic_text_follows_its_brackets() { + let line = kurbo::Line::new((0.0, 100.0), (400.0, 100.0)).to_path(0.1); + let whole = layout(db(), &dynamic_on("Brackets", 12.0, &line, None)); + let half = dynamic_on("Brackets", 12.0, &line, Some(0.5)); + let l = assert_fills(&half, "half"); + assert!(l.fit_scale < whole.fit_scale * 0.6, "{} vs {}", l.fit_scale, whole.fit_scale); + let circle = kurbo::Circle::new((200.0, 200.0), 100.0).to_path(0.1); + let round = dynamic_on("Round and round the path", 12.0, &circle, None); + let l = assert_fills(&round, "circle"); + let (used, room) = l.path_fill.unwrap_or_default(); + assert!((room - std::f64::consts::TAU * 100.0).abs() < 1.0, "{room}"); + assert!(used > room * 0.95, "{used} of {room}"); +} + +/// The runs keep their proportions: one factor scales every size. +#[test] +fn dynamic_text_keeps_the_runs_proportions() { + let mut t = dynamic("Small", 10.0, 400.0); + t.runs.push(TextRun::new(" LARGE", CharStyle { size: 20.0, ..CharStyle::default() })); + let l = assert_fills(&t, "two runs"); + let d = drawn(&t); + assert!((d.runs[1].style.size / d.runs[0].style.size - 2.0).abs() < 1e-9); + assert!((d.runs[0].style.size - 10.0 * l.fit_scale).abs() < 1e-9); + // A size Dynamic Text does not scale is drawn as stored. + let mut point = t.clone(); + point.dynamic_text = false; + assert!(matches!(drawn(&point), std::borrow::Cow::Borrowed(_))); +} + +/// Nothing to fit: empty text, a path with no length and a span with no length lay out as they are. +/// Past the size limits the text stays at 0.1 pt (and overflows) or at 1,296 pt. +#[test] +fn dynamic_text_edges_and_limits() { + let empty = layout(db(), &dynamic("", 12.0, 400.0)); + assert_eq!((empty.fit_scale, empty.overflow), (1.0, false)); + let spaces = assert_fills(&dynamic(" ", 12.0, 400.0), "spaces"); + assert!(spaces.fit_scale > 1.0); + let one = assert_fills(&dynamic("W", 12.0, 100.0), "one character"); + assert!(one.fit_scale > 1.0); + let point = kurbo::Line::new((50.0, 50.0), (50.0, 50.0)).to_path(0.1); + let l = layout(db(), &dynamic_on("No room", 12.0, &point, None)); + assert_eq!((l.fit_scale, l.overflow), (1.0, true)); + let line = kurbo::Line::new((0.0, 100.0), (400.0, 100.0)).to_path(0.1); + let mut closed_span = dynamic_on("No span", 12.0, &line, Some(0.5)); + closed_span.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.5, end: Some(0.5) }; + let l = layout(db(), &closed_span); + assert_eq!((l.fit_scale, l.overflow), (1.0, true)); + // A span of a hundredth of a point: down at 0.1 pt the text still overflows. + let tiny = layout(db(), &dynamic(COPY, 12.0, 0.01)); + assert!(tiny.overflow && (12.0 * tiny.fit_scale - 0.1).abs() < 1e-9, "{}", 12.0 * tiny.fit_scale); + // A span of 100,000 points: one letter stops at 1,296 pt. + let huge = layout(db(), &dynamic("i", 12.0, 100_000.0)); + assert!(!huge.overflow && (12.0 * huge.fit_scale - 1296.0).abs() < 1e-9, "{}", 12.0 * huge.fit_scale); + // The limits apply to the first character's size, past an empty run before it. + let mut empty_first = dynamic("", 0.1, 100_000.0); + empty_first.runs.push(TextRun::new("i", CharStyle { size: 100.0, ..CharStyle::default() })); + let l = layout(db(), &empty_first); + assert!((100.0 * l.fit_scale - 1296.0).abs() < 1e-9, "{}", 100.0 * l.fit_scale); + // A size that measures the cap height steps and stops as the Character panel shows it. + let mut cap = dynamic("i", 12.0, 100_000.0); + cap.runs[0].style.font_height_reference = vectorcraft_doc::text::FontHeightReference::CapHeight; + let l = layout(db(), &cap); + assert!((12.0 * l.fit_scale - 1296.0).abs() < 1e-9, "{}", 12.0 * l.fit_scale); + let cap_short = + TextObject { kind: dynamic("Cap height", 12.0, 400.0).kind, runs: vec![TextRun::new("Cap height", cap.runs[0].style.clone())], ..cap }; + let l = layout(db(), &cap_short); + let shown = 12.0 * l.fit_scale; + assert!(!l.overflow && (shown * 10.0 - (shown * 10.0).round()).abs() < 1e-6, "{shown}"); + // The same document size whatever the local size: a 12 pt run stored at 0.012 under a scale of 1,000. + let mut scaled_xf = dynamic("Fill me", 0.012, 0.4); + scaled_xf.xf = Affine::scale(1000.0); + let l = layout(db(), &scaled_xf); + let document_size = 12.0 * l.fit_scale; + assert!(!l.overflow && (document_size * 10.0 - (document_size * 10.0).round()).abs() < 1e-6, "{document_size}"); +} + +/// Right-to-left text, vertical type, a bulleted paragraph, Optical Margin Alignment and Spacing +/// fit without overflowing, through the layout's own overflow rule. +#[test] +fn dynamic_text_fits_every_kind_of_line() { + let arc = { + let mut p = kurbo::BezPath::new(); + p.move_to((0.0, 200.0)); + p.quad_to((200.0, 0.0), (400.0, 200.0)); + p + }; + let rtl = dynamic_on("שלום עולם", 12.0, &arc, None); + assert!(assert_fills(&rtl, "right to left").fit_scale > 1.0); + let mut vertical = dynamic_on("Vertical type", 12.0, &kurbo::Line::new((0.0, 0.0), (0.0, 400.0)).to_path(0.1), None); + vertical.vertical = true; + assert!(assert_fills(&vertical, "vertical").fit_scale > 1.0); + let mut bullet = dynamic_on("Bulleted", 12.0, &arc, None); + bullet.para.list = Some(vectorcraft_doc::text::ParaList::bulleted(vectorcraft_doc::text::Bullet::Dot)); + let l = assert_fills(&bullet, "bulleted"); + assert!(!l.markers.is_empty()); + let mut optical = dynamic_on("“Quoted.”", 12.0, &arc, None); + optical.optical_margin = true; + assert!(assert_fills(&optical, "optical margin").fit_scale > 1.0); + let mut spaced = dynamic_on("Spaced around a curve", 12.0, &arc, None); + spaced.path_spacing = 10.0; + assert!(assert_fills(&spaced, "spacing").fit_scale > 1.0); +} + +/// The search lays the text out at most 11 times past the first, however far the size moves. +#[test] +fn dynamic_text_lays_out_a_bounded_number_of_times() { + for (text, len) in [("Fill me", 400.0), (COPY, 400.0), (COPY, 0.01), ("i", 100_000.0), ("Round", 37.3)] { + let before = crate::layout::fit_passes(); + let l = layout(db(), &dynamic(text, 12.0, len)); + let passes = crate::layout::fit_passes() - before; + assert!((1..=11).contains(&passes), "{text:?} on {len}: {passes} passes (fit {})", l.fit_scale); + } + // A straight span with no spacing starts from the right size: a few passes. + let before = crate::layout::fit_passes(); + layout(db(), &dynamic(COPY, 12.0, 300.0)); + assert!(crate::layout::fit_passes() - before <= 4); +} diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index e590f103c7..9bb7700d66 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -171,6 +171,7 @@ fn paint_only_keeps_every_nonpaint_attribute_and_partial_equality() { b.stroke_dash = a.stroke_dash.clone(); b.stroke_align = a.stroke_align; b.style_name = a.style_name.clone(); + b.kerning_before = a.kerning_before; *a == b } @@ -203,6 +204,7 @@ fn paint_only_keeps_every_nonpaint_attribute_and_partial_equality() { field!(leading, Some(60.0), false); field!(tracking, 20.0, false); field!(kerning, Some(0.0), false); + field!(kerning_before, 250.0, true); field!(optical_kerning, true, false); field!(baseline_shift, 1.0, false); field!(h_scale, 90.0, false); @@ -312,6 +314,36 @@ fn harakat_ranges_normalise_their_range() { /// the same way, and only a character in that glyph's shaping cluster: repeated glyph ids alone /// don't do. A later in-cluster owner is kept only for a GDEF mark glyph on a harakat character; /// everything else stays at the cluster start (conservative). +/// A space before the line's first letter (#5111), set on the letter alone as the Type tool's caret +/// sets it, keeps the letter's harakat coloured apart attached and in their own colour. Right to +/// left the space is past the letter's right side, so every glyph stays where it was and the line +/// is the space longer. Checked with the in-memory Arabic test font (its fatha a `GDEF` mark) in +/// every environment, and with an installed Arabic face when there is one. +#[test] +fn a_space_before_the_first_letter_keeps_its_coloured_harakat() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").unwrap()), 1); + check_spaced_harakat(&db, crate::test_fonts::lam_alef_family(b"rlig")); + if let Some(face) = arabic_face("a_space_before_the_first_letter_keeps_its_coloured_harakat") { + check_spaced_harakat(FontDb::global(), &face.family); + } +} + +fn check_spaced_harakat(db: &FontDb, family: &str) { + const WORD: &str = "بَبَب"; // ب 0, fatha 2, ب 4, fatha 6, ب 8 + let coloured = text_with_harakat(WORD, family, Some(red())); + let mut spaced = coloured.clone(); + crate::edit::style_range(&mut spaced.runs, 0, 2, |st| st.kerning_before = 250.0); + let (a, b) = (layout(db, &coloured), layout(db, &spaced)); + let placed = |l: &TextLayout| l.glyphs.iter().map(|g| (g.font_id, g.gid, g.byte, g.xf.as_coeffs().map(f64::to_bits))).collect::>(); + assert_eq!(placed(&a), placed(&b), "{family}: the same glyphs where they were"); + assert!(painted(&spaced, &b, &red()) > 0, "{family}: harakat painted apart"); + assert_eq!(painted(&spaced, &b, &red()), painted(&coloured, &a, &red()), "{family}: the harakat keep their colour"); + // 250/1000 of the 48 pt em. + let length = |l: &TextLayout| l.glyphs.iter().map(|g| g.advance).sum::(); + assert!((length(&b) - length(&a) - 12.0).abs() < 1e-6, "{family}: {} → {}", length(&a), length(&b)); +} + #[test] fn own_chars_need_the_same_setting_and_each_character_in_its_cluster() { // بَبَب right to left: final beh (cluster 8), fatha and medial beh (cluster 4), fatha and diff --git a/crates/text/src/tests/kerning_before.rs b/crates/text/src/tests/kerning_before.rs new file mode 100644 index 0000000000..f3d9e785a8 --- /dev/null +++ b/crates/text/src/tests/kerning_before.rs @@ -0,0 +1,136 @@ +//! The space before a character that starts a line by itself (`CharStyle::kerning_before`, #5111): +//! the first character of the text, of a paragraph or after a forced line break moves along its line +//! by the value, the rest of the line follows, and the value does nothing anywhere else. +use crate::*; +use kurbo::Shape; +use vectorcraft_doc::{CharStyle, Justify}; + +fn db() -> &'static FontDb { + FontDb::global() +} + +fn style(size: f64) -> CharStyle { + CharStyle { size, ..CharStyle::default() } +} + +/// Where glyph `byte` is drawn along a horizontal line. +fn drawn_x(l: &TextLayout, byte: usize) -> f64 { + l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.xf.as_coeffs()[4]).unwrap() +} + +/// `t` with `kerning_before` set on the character at `byte`. +fn spaced(t: &TextObject, byte: usize, value: f64) -> TextObject { + let mut t = t.clone(); + let end = edit::next_char(&t.plain_text(), byte); + edit::style_range(&mut t.runs, byte, end, |st| st.kerning_before = value); + t +} + +/// How far each of `bytes` moved along the line from `a` to `b`. +fn moves(a: &TextObject, b: &TextObject, bytes: &[usize]) -> Vec { + let (la, lb) = (layout(db(), a), layout(db(), b)); + bytes.iter().map(|&i| drawn_x(&lb, i) - drawn_x(&la, i)).collect() +} + +fn near(values: &[f64], expected: &[f64]) -> bool { + values.len() == expected.len() && values.iter().zip(expected).all(|(v, e)| (v - e).abs() < 1e-6) +} + +#[test] +fn the_first_character_moves_along_its_line_and_the_rest_follow() { + let plain = TextObject::point(Point::ZERO, "HOH", style(100.0)); + // 250/1000 em of 100 pt: 25 pt, away from the line's start; a negative value pulls it back. + let away = moves(&plain, &spaced(&plain, 0, 250.0), &[0, 1, 2]); + assert!(near(&away, &[25.0, 25.0, 25.0]), "{away:?}"); + let back = moves(&plain, &spaced(&plain, 0, -100.0), &[0, 1, 2]); + assert!(near(&back, &[-10.0, -10.0, -10.0]), "{back:?}"); + // The line is that much longer, so a centred line moves its first character half as far. + let mut centred = plain.clone(); + centred.para.justify = Justify::Center; + let half = moves(¢red, &spaced(¢red, 0, 250.0), &[0, 2]); + assert!(near(&half, &[12.5, 12.5]), "{half:?}"); +} + +#[test] +fn it_does_nothing_on_a_character_inside_a_line() { + let plain = TextObject::point(Point::ZERO, "HOH", style(100.0)); + let inside = moves(&plain, &spaced(&plain, 1, 250.0), &[0, 1, 2]); + assert!(near(&inside, &[0.0, 0.0, 0.0]), "{inside:?}"); + // Nor on the first character of a line that wrapped in area type: the line break moves. + let area = super::area("HOH HOH", style(50.0), Rect::new(0.0, 0.0, 180.0, 400.0), Justify::Left); + let wrapped = layout(db(), &area); + let second_line = wrapped.glyphs.iter().find(|g| g.byte == 4).unwrap().line; + assert_eq!(second_line, 1, "the second HOH wraps"); + let moved = moves(&area, &spaced(&area, 4, 250.0), &[0, 4, 5]); + assert!(near(&moved, &[0.0, 0.0, 0.0]), "{moved:?}"); +} + +#[test] +fn a_paragraph_and_a_forced_line_break_start_lines_by_themselves() { + let paragraphs = TextObject::point(Point::ZERO, "HO\nHO", style(100.0)); + let moved = moves(¶graphs, &spaced(¶graphs, 3, 250.0), &[0, 1, 3, 4]); + assert!(near(&moved, &[0.0, 0.0, 25.0, 25.0]), "{moved:?}"); + let forced = TextObject::point(Point::ZERO, "HO\u{2028}HO", style(100.0)); + let after = "HO\u{2028}".len(); + let moved = moves(&forced, &spaced(&forced, after, 250.0), &[0, after, after + 1]); + assert!(near(&moved, &[0.0, 25.0, 25.0]), "{moved:?}"); + // On a line break it stays: an empty line has nothing to move. + let empty = TextObject::point(Point::ZERO, "HO\n\nHO", style(100.0)); + let moved = moves(&empty, &spaced(&empty, 3, 250.0), &[0, 4]); + assert!(near(&moved, &[0.0, 0.0]), "{moved:?}"); +} + +#[test] +fn it_takes_the_em_of_the_character_as_manual_kerning_does() { + // Horizontal Scale 50%: half the space, as kerning after a character takes it. + let narrow = TextObject::point(Point::ZERO, "HOH", CharStyle { h_scale: 50.0, ..style(100.0) }); + let moved = moves(&narrow, &spaced(&narrow, 0, 250.0), &[0, 2]); + assert!(near(&moved, &[12.5, 12.5]), "{moved:?}"); +} + +#[test] +fn right_to_left_the_space_is_at_the_right_of_the_first_character() { + // The first character in reading order is drawn rightmost; the space before it is on its right, + // so the two keep their distance, and the line is 25 pt longer. + let plain = TextObject::point(Point::ZERO, "אב", style(100.0)); + let kerned = spaced(&plain, 0, 250.0); + let (a, b) = (layout(db(), &plain), layout(db(), &kerned)); + assert!(drawn_x(&a, 0) > drawn_x(&a, 2), "right to left"); + let gap = |l: &TextLayout| drawn_x(l, 0) - drawn_x(l, 2); + assert!((gap(&b) - gap(&a)).abs() < 1e-6, "{} {}", gap(&a), gap(&b)); + let length = |l: &TextLayout| l.lines[0].x1 - l.lines[0].x0; + assert!((length(&b) - length(&a) - 25.0).abs() < 1e-6, "{} {}", length(&a), length(&b)); +} + +#[test] +fn in_vertical_type_the_first_character_moves_down_its_column() { + // An upright glyph (§) and letters lying on their side both move 5 pt (250/1000 em of 20 pt) + // down the column, and stay in it. + for text in ["§§", "ab"] { + let mut plain = TextObject::point(Point::ZERO, text, style(20.0)); + plain.xf = Affine::IDENTITY; + plain.vertical = true; + let kerned = spaced(&plain, 0, 250.0); + let (a, b) = (layout(db(), &plain), layout(db(), &kerned)); + for i in 0..2 { + let (before, after) = (a.glyphs[i].outline.bounding_box(), b.glyphs[i].outline.bounding_box()); + assert!((after.center().y - before.center().y - 5.0).abs() < 1e-6, "{text} {i}: {before:?} {after:?}"); + assert!((after.center().x - before.center().x).abs() < 1e-6, "{text} {i}: {before:?} {after:?}"); + } + } +} + +#[test] +fn a_space_before_the_first_letter_of_a_ligature_keeps_it_whole() { + // Set on the "f" alone, as the caret before it sets it: Source Serif 4's "fi" ligature stays one + // glyph, and moves. + let serif = CharStyle { font_family: "Source Serif 4".into(), ..style(100.0) }; + let plain = TextObject::point(Point::ZERO, "fit", serif); + let glyphs = |t: &TextObject| layout(db(), t).glyphs.len(); + assert_eq!(glyphs(&plain), 2, "the font joins fi"); + let kerned = spaced(&plain, 0, 250.0); + assert_eq!(glyphs(&kerned), 2, "still joined"); + let moved = moves(&plain, &kerned, &[0, 2]); + assert!(near(&moved, &[25.0, 25.0]), "{moved:?}"); + assert!((line_start_space("fit", 0, &kerned.runs[0].style, false) - 25.0).abs() < 1e-9); +} diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 2bc1c2ff70..e76aee72f0 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -1075,6 +1075,176 @@ fn mojikumi_sets_an_opening_bracket_flush_at_the_start_of_a_wrapped_line() { } } +/// Mojikumi: with Line-end Punctuation Half Width, a line is measured as it is set. A closing +/// bracket, comma or full stop that fits only at half width ends the line in a measure of three +/// and a half ems, with both composers, horizontal and vertical; with Mojikumi None it goes to the +/// next line with the character before it. A closing mark that already lost its half to the +/// punctuation after it takes nothing more off, and the space between Japanese and Latin text +/// counts only where the line ends. Uses a test font whose ideographs and punctuation are one em. +#[test] +fn mojikumi_line_end_half_width_counts_when_a_line_breaks() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::{Burasagari, Composer, Kinsoku, KinsokuShoriType, Mojikumi}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let lay = |text: &str, m: Mojikumi, composer: Composer, burasagari: Burasagari, vertical_type: bool, measure: f64| { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.vertical = vertical_type; + t.para.mojikumi = m; + t.para.composer = composer; + t.para.burasagari = burasagari; + t.para.kinsoku = Kinsoku::Hard; + // Push Out Only lets the every-line composer take the paragraph. + if composer == Composer::EveryLine { + t.para.kinsoku_type = KinsokuShoriType::PushOutOnly; + } + let frame = if vertical_type { Rect::new(0.0, 0.0, 200.0, measure) } else { Rect::new(0.0, 0.0, measure, 200.0) }; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) }; + layout(&db, &t) + }; + let ends = |l: &TextLayout, text: &str| l.lines.iter().map(|line| text[line.start..line.end].to_string()).collect::>(); + let widest = |l: &TextLayout| { + l.lines.iter().map(|line| l.glyphs[line.glyph_start..line.glyph_end].iter().map(|g| g.advance).sum::()).fold(0.0, f64::max) + }; + assert!((lay("一", Mojikumi::None, Composer::SingleLine, Burasagari::None, false, 70.0).glyphs[0].advance - 20.0).abs() < 1e-9, "one em"); + for vertical_type in [false, true] { + for composer in [Composer::SingleLine, Composer::EveryLine] { + let at = format!("vertical {vertical_type} {composer:?}"); + let marks = [("一二三」四五六", "一二三」"), ("一二三。四五六", "一二三。"), ("一二三、四五六", "一二三、")]; + for (text, first) in marks { + let l = lay(text, Mojikumi::LineEndHalf, composer, Burasagari::None, vertical_type, 70.0); + assert_eq!(ends(&l, text), [first, "四五六"], "{at}: {text}"); + assert!((l.glyphs[3].advance - 10.0).abs() < 1e-9, "{at}: {text}: the mark ends the line half width"); + assert!(widest(&l) <= 70.0 + 1e-9, "{at}: {text}: {}", widest(&l)); + // Standard burasagari: the mark fits inside, so it doesn't hang. + let standard = lay(text, Mojikumi::LineEndHalf, composer, Burasagari::Standard, vertical_type, 70.0); + assert_eq!(ends(&standard, text), [first, "四五六"], "{at}: {text} standard"); + assert!(widest(&standard) <= 70.0 + 1e-9, "{at}: {text} standard"); + // Full width it doesn't fit: kinsoku takes 三 to the next line with it. + let solid = lay(text, Mojikumi::None, composer, Burasagari::None, vertical_type, 70.0); + assert_eq!(ends(&solid, text).first().map(String::as_str), Some("一二"), "{at}: {text} none"); + } + // 」 lost its half to 。 after it: the line would be four ems, so 三」。 go on. + let text = "一二三」。四五"; + let l = lay(text, Mojikumi::LineEndHalf, composer, Burasagari::None, vertical_type, 70.0); + assert_eq!(ends(&l, text).first().map(String::as_str), Some("一二"), "{at}: compressed"); + assert!(widest(&l) <= 70.0 + 1e-9, "{at}: compressed"); + } + } + // The quarter em between 三 and A goes where the line ends there: 一二三 fits three ems and a + // tenth, with or without the space at its end. + for composer in [Composer::SingleLine, Composer::EveryLine] { + let text = "一二三ABC"; + let on = lay(text, Mojikumi::LineEndHalf, composer, Burasagari::None, false, 62.0); + assert_eq!(ends(&on, text).first().map(String::as_str), Some("一二三"), "{composer:?}"); + assert!((on.glyphs[2].advance - 20.0).abs() < 1e-9, "{composer:?}: no space at the line's end"); + let wide = lay(text, Mojikumi::LineEndHalf, composer, Burasagari::None, false, 200.0); + assert!((wide.glyphs[2].advance - 25.0).abs() < 1e-9, "{composer:?}: the space inside the line"); + } +} + +/// Mojikumi: in a frame that is narrow at the top, and in a frame a wrap object narrows at the top, +/// a line's first word is measured as the line sets it. A word ending with a closing bracket that +/// fits the narrow lines only with the bracket half width, and an opening bracket that fits them +/// only flush with the line's start, start on the first line, with both composers. An opening +/// bracket that kinsoku keeps with the character after it, and a No Break run, are measured whole. +#[test] +fn mojikumi_narrows_a_lines_first_word_when_looking_for_room() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::{Composer, Kinsoku, KinsokuShoriType, Mojikumi, TextWrap, WrapShape}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + // The top 40 pt of the frame are `top` wide, the rest 200: an L-shaped frame, or a rectangle + // with a wrap object over the top right. + let lay = |text: &str, styled: fn(&mut TextObject), composer: Composer, top: f64, wrapped: bool| { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + styled(&mut t); + t.para.mojikumi = Mojikumi::LineEndHalf; + t.para.composer = composer; + t.para.kinsoku = Kinsoku::Hard; + t.para.kinsoku_type = KinsokuShoriType::PushOutOnly; + let frame = if wrapped { + t.wrap = vec![WrapShape { + path: PathData::from_bezpath(&Rect::new(top, -10.0, 210.0, 40.0).to_path(0.1)), + wrap: TextWrap { offset: 0.0, invert: false }, + }]; + Rect::new(0.0, 0.0, 200.0, 200.0).to_path(0.1) + } else { + let mut p = kurbo::BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((top, 0.0)); + p.line_to((top, 40.0)); + p.line_to((200.0, 40.0)); + p.line_to((200.0, 200.0)); + p.line_to((0.0, 200.0)); + p.close_path(); + p + }; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) }; + layout(&db, &t) + }; + let plain: fn(&mut TextObject) = |_| {}; + let wide_bracket: fn(&mut TextObject) = |t| edit::style_range(&mut t.runs, 0, '「'.len_utf8(), |s| s.h_scale = 250.0); + let no_break: fn(&mut TextObject) = |t| { + let n = t.plain_text().len(); + edit::style_range(&mut t.runs, 0, n, |s| s.no_break = true); + }; + let no_break_but_the_last_word: fn(&mut TextObject) = |t| { + let n = t.plain_text().rfind(' ').map_or(0, |k| k + 1); + edit::style_range(&mut t.runs, 0, n, |s| s.no_break = true); + }; + // "ABCD」" is `full` wide inside a line; ending one, 」 is half width. + let closing = "ABCD」EFGH"; + let open = lay(closing, plain, Composer::SingleLine, 200.0, false); + let full: f64 = open.glyphs[..5].iter().map(|g| g.advance).sum(); + assert!((open.glyphs[4].advance - 20.0).abs() < 1e-9, "」 is one em inside a line"); + for wrapped in [false, true] { + for composer in [Composer::SingleLine, Composer::EveryLine] { + let at = format!("wrapped {wrapped} {composer:?}"); + let top = full - 5.0; + let l = lay(closing, plain, composer, top, wrapped); + let first = l.lines.first().expect("a line"); + assert_eq!(&closing[first.start..first.end], "ABCD」", "{at}"); + assert!(first.baseline < 40.0, "{at}: the word starts on the narrow lines: {}", first.baseline); + let set: f64 = l.glyphs[first.glyph_start..first.glyph_end].iter().map(|g| g.advance).sum(); + assert!(set <= top + 1e-9, "{at}: {set} in {top}"); + // 「 is 50 pt at 250%, 25 pt flush with the line's start: 「一 is 45 pt. + let opening = "「一二三四五六"; + let l = lay(opening, wide_bracket, composer, 47.0, wrapped); + let first = l.lines.first().expect("a line"); + assert_eq!(&opening[first.start..first.end], "「一", "{at}"); + assert!(first.baseline < 40.0, "{at}: 「 starts on the narrow lines: {}", first.baseline); + let set: f64 = l.glyphs[first.glyph_start..first.glyph_end].iter().map(|g| g.advance).sum(); + assert!(set <= 47.0 + 1e-9, "{at}: {set}"); + // Kinsoku keeps 「 with 一: in 40 pt they don't fit, and the line starts below, whole. + let l = lay(opening, wide_bracket, composer, 40.0, wrapped); + let first = l.lines.first().expect("a line"); + assert!(first.baseline > 40.0 && &opening[first.start..first.end] != "「", "{at}: kinsoku: {:?}", placed_lines(&l, opening)); + // A No Break run is one word, its space included: it doesn't fit the narrow lines. + let run_text = "ABCD EFGH"; + let run: f64 = lay(run_text, no_break, composer, 200.0, false).glyphs.iter().map(|g| g.advance).sum(); + let l = lay(run_text, no_break, composer, run - 5.0, wrapped); + let first = l.lines.first().expect("a line"); + assert!(first.baseline > 40.0 && &run_text[first.start..first.end] == run_text, "{at}: no break: {:?}", placed_lines(&l, run_text)); + // …but the space ending a No Break run is not set at the line's end: the run fits a + // line 2 pt wider than it is without that space. + let ending = "ABCD EFGH IJ"; + let l = lay(ending, no_break_but_the_last_word, composer, run + 2.0, wrapped); + let first = l.lines.first().expect("a line"); + assert!(first.baseline < 40.0 && ending[first.start..first.end].trim_end() == run_text, "{at}: {:?}", placed_lines(&l, ending)); + } + } +} + +/// Each line's baseline and text. +fn placed_lines(l: &TextLayout, text: &str) -> Vec<(f64, String)> { + l.lines.iter().map(|line| (line.baseline, text[line.start..line.end].to_string())).collect() +} + /// Burasagari: in a measure of exactly five ems, a comma that would be the sixth character goes to /// the next line with the character before it (None) or hangs outside the line (Standard, Forced); /// a full stop that is the fifth character stays inside (None, Standard) or hangs while the four diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 5606cb884c..2d945c1439 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -17,6 +17,8 @@ pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; mod mesh; pub use mesh::{Mesh, extrude_mesh, inflate_meshes, plane_mesh, revolve_mesh}; +mod shadow; +pub use shadow::{MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, TOO_COMPLEX_SHADOW}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2, kurbo::ParamCurveDeriv}; @@ -339,6 +341,9 @@ impl Revolve { pub struct Face { pub points: Vec, pub depth: f64, + /// The face's unit normal in view space (x right, y down, z toward the viewer), turned to the + /// side the viewer sees. + pub normal: [f64; 3], pub brightness: f64, pub gradient: Option, /// RGB illumination and its unclipped smooth ramp, independent of the legacy white ramp. @@ -451,6 +456,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi Ok(Some(Face { points, depth: vertices.iter().map(|v| v.2).sum::() / vertices.len() as f64, + normal: [normal.0, normal.1, normal.2], brightness, gradient, illumination, @@ -468,6 +474,12 @@ pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result Result, String> { + Ok(revolve(path, bounds, options)?.into_iter().map(Facet::of_face).collect()) +} + const TOO_COMPLEX_PROFILE: &str = "Revolve profile is too complex"; const TOO_COMPLEX_SURFACE: &str = "Revolve surface is too complex; reduce Segments or simplify the profile"; @@ -672,6 +684,19 @@ impl HoleSearch { } } +/// How sanitized Revolve options `o` project a profile with `bounds`: about the axis at the +/// profile's middle height, with the eye as far as the swept radius or the height needs. +fn revolve_projection(bounds: Rect, o: Revolve) -> shadow::Projection { + let axis = match o.edge { + Edge::Left => bounds.x0 - o.offset, + Edge::Right => bounds.x1 + o.offset, + }; + let center_y = (bounds.y0 + bounds.y1) * 0.5; + let radius = (bounds.x0 - axis).abs().max((bounds.x1 - axis).abs()); + let eye = eye_distance(o.perspective, radius.max(bounds.height().abs()).max(1.0)); + shadow::Projection { view: o, origin: Point::new(axis, center_y), eye } +} + /// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn, /// each turned out of the region `rule` fills. fn revolve_faces( @@ -697,13 +722,7 @@ fn revolve_faces( if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve requires finite profile coordinates within 100 million points".into()); } - let axis = match o.edge { - Edge::Left => bounds.x0 - o.offset, - Edge::Right => bounds.x1 + o.offset, - }; - let center_y = (bounds.y0 + bounds.y1) * 0.5; - let radius = (bounds.x0 - axis).abs().max((bounds.x1 - axis).abs()); - let eye = eye_distance(o.perspective, radius.max(bounds.height().abs()).max(1.0)); + let shadow::Projection { origin: Point { x: axis, y: center_y }, eye, .. } = revolve_projection(bounds, o); let steps = o.steps(); let sweep = o.angle.to_radians(); let smooth = o.shade && o.smooth_shading; diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index d1970c2028..b12bd315f5 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -56,12 +56,12 @@ impl Mesh { /// Extrude & Bevel's solid ([`crate::extrude`]) as a mesh. pub fn extrude_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result { - extrude_faces(path, rule, bounds, options, view, true).and_then(|(_, faces)| mesh(&faces)) + extrude_faces(path, rule, bounds, options, view, true).and_then(|(_, faces, _)| mesh(&faces)) } /// Rotate's plane ([`crate::plane`]) as a mesh. pub fn plane_mesh(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result { - plane_faces(path, rule, bounds, view, true).and_then(|(_, faces)| mesh(&faces)) + plane_faces(path, rule, bounds, view, true).and_then(|(_, faces, _)| mesh(&faces)) } /// Inflate's solids for several shapes of one object ([`crate::inflate_together`]) as meshes, one @@ -72,7 +72,7 @@ pub fn inflate_meshes( options: Inflate, view: View, ) -> impl Iterator> + use<> { - inflate_faces(shapes, bounds, options, view, true).map(|r| r.and_then(|(_, faces)| mesh(&faces))) + inflate_faces(shapes, bounds, options, view, true).map(|r| r.and_then(|(_, faces, _)| mesh(&faces))) } /// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs new file mode 100644 index 0000000000..d7cd01a869 --- /dev/null +++ b/crates/three-d/src/shadow.rs @@ -0,0 +1,343 @@ +//! The shadow a 3D effect's solid casts: its faces projected along the first light onto a plane +//! behind the object (square to the view) or below it (under the object's own vertical axis, turned +//! with it), as one hard-edged vector shape. +//! +//! Every face is projected whole, so the shape is the union of the projected faces: each contour is +//! turned so that its face winds the same way, and the shape is filled with the nonzero rule. The +//! plane ends at a square about the foot of the object's center, so a light that grazes the plane +//! does not cast a shadow without end. + +use std::ops::Range; + +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use crate::solid::{Face3, extrude_faces, inflate_faces, plane_faces}; +use crate::{Extrude, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale}; + +/// Where the shadow falls. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ShadowPosition { + /// On a plane behind the object, square to the view. + #[default] + Behind, + /// On a plane below the object, square to its vertical axis and turned with it. + Below, +} + +impl ShadowPosition { + pub const ALL: [ShadowPosition; 2] = [Self::Behind, Self::Below]; + + pub fn id(self) -> &'static str { + match self { + Self::Behind => "behind", + Self::Below => "below", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|p| p.id() == s) + } +} + +/// A shadow's settings. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Shadow { + pub position: ShadowPosition, + /// How far the plane is from the object, as a share (0..1) of the object's largest size. + pub distance: f64, + /// How far the plane reaches, as a share (0.1..4): at 1 the plane is a square four times the + /// object's largest size across. + pub bounds: f64, +} + +impl Default for Shadow { + fn default() -> Self { + Self { position: ShadowPosition::Behind, distance: 0.0, bounds: 1.0 } + } +} + +impl Shadow { + fn sanitized(self) -> Self { + Self { distance: finite(self.distance, 0.0, 0.0, 1.0), bounds: finite(self.bounds, 1.0, 0.1, 4.0), ..self } + } +} + +/// The rotation and projection a solid is drawn with. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Projection { + /// The sanitized view: its rotation, perspective and lights. + pub(crate) view: Revolve, + /// Where the view's origin is on the page. + pub(crate) origin: Point, + /// The eye's distance in front of the origin; `None` without perspective. + pub(crate) eye: Option, +} + +impl Projection { + fn project(&self, v: V3) -> Point { + let f = perspective_scale(self.eye, v.2); + Point::new(self.origin.x + v.0 * f, self.origin.y + v.1 * f) + } + + /// The unit direction toward the first light, in view space; `None` when it lights nothing: + /// Shading is off or its intensity is 0. + fn light(&self) -> Option { + let first = self.view.lights.and_then(|l| l.iter().next().copied()); + let intensity = first.map_or(self.view.light_intensity, |l| l.intensity); + if !self.view.shade || intensity <= 0.0 { + return None; + } + let [x, y, z] = first.map_or_else(|| self.view.light_direction(), |l| l.direction()); + Some(V3(x, y, z).unit()) + } +} + +/// The light must reach the plane at least this steeply (its cosine to the plane's normal). +const MIN_LIGHT: f64 = 1e-3; + +/// Most faces one object's shadow is cast from, its solids together: as many as two of the largest +/// solids. +pub const MAX_SHADOW_FACES: usize = 2 * MAX_SOLID_FACES; + +/// The error a solid added past [`MAX_SHADOW_FACES`] returns. +pub const TOO_COMPLEX_SHADOW: &str = "The 3D shadow is too complex; turn Shadows off or simplify the art"; + +/// The plane a shadow falls on ([`ShadowCaster::shadow_plane`]), placed once for the pieces of one +/// object's shadow ([`ShadowCaster::path_on`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ShadowPlane { + projection: Projection, + /// The unit direction toward the light, and its cosine to the plane's normal. + light: V3, + reach: f64, + /// The plane's unit normal toward the object, and two unit axes along it. + n: V3, + u: V3, + w: V3, + /// Where the plane is along its normal, and the foot of the object's center on it. + level: f64, + foot: V3, + /// Half the side of the square the plane ends at. + half: f64, +} + +/// The faces of one object's solids, gathered to cast one shadow. The solids of one object share +/// their bounds and view, so they share a projection: the first solid's is kept. Each solid added +/// returns the range of its faces, so that the shadow of some of them can be drawn on the plane +/// of others ([`ShadowCaster::shadow_plane`], [`ShadowCaster::path_on`]). +#[derive(Clone, Debug, Default)] +pub struct ShadowCaster { + faces: Vec, + projection: Option, +} + +impl ShadowCaster { + pub fn new() -> Self { + Self::default() + } + + /// How many faces have been gathered. + pub fn len(&self) -> usize { + self.faces.len() + } + + pub fn is_empty(&self) -> bool { + self.faces.is_empty() + } + + /// Keep `faces`, or an error when they would take the faces gathered past [`MAX_SHADOW_FACES`]. + fn add(&mut self, faces: Vec, projection: Option) -> Result, String> { + let start = self.faces.len(); + if start.saturating_add(faces.len()) > MAX_SHADOW_FACES { + return Err(TOO_COMPLEX_SHADOW.into()); + } + if !faces.is_empty() && self.projection.is_none() { + self.projection = projection; + } + self.faces.extend(faces); + Ok(start..self.faces.len()) + } + + /// Add Extrude & Bevel's solid ([`crate::extrude`]). + pub fn extrude(&mut self, path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result, String> { + let (_, faces, projection) = extrude_faces(path, rule, bounds, options, view, true)?; + self.add(faces, projection) + } + + /// Add Rotate's plane ([`crate::plane`]). + pub fn plane(&mut self, path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result, String> { + let (_, faces, projection) = plane_faces(path, rule, bounds, view, true)?; + self.add(faces, projection) + } + + /// Add Inflate's solids for several shapes of one object ([`crate::inflate_together`]), each + /// shape whose entry in `casts` is true: the eye is placed for every shape, as for the solids + /// drawn, but the faces of the others are not kept (their range is empty). A shape that does + /// not inflate is left out, as its solid is; the result says which, in order. + pub fn inflate( + &mut self, + shapes: &[(&PathData, FillRule)], + casts: &[bool], + bounds: Rect, + options: Inflate, + view: View, + ) -> Vec, String>> { + inflate_faces(shapes, bounds, options, view, true) + .enumerate() + .map(|(i, r)| { + let (_, faces, projection) = r?; + if casts.get(i).copied().unwrap_or(true) { self.add(faces, projection) } else { Ok(self.faces.len()..self.faces.len()) } + }) + .collect() + } + + /// Add Revolve's surface ([`crate::revolve`]). + pub fn revolve(&mut self, path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result, String> { + let mut faces = vec![]; + crate::revolve_faces(path, rule, bounds, options, Some(&mut faces))?; + let o = options.sanitized(); + self.add(faces, Some(crate::revolve_projection(bounds, o))) + } + + /// The shadow of the faces gathered, on the page, filled with the nonzero rule: `None` when + /// there are none, when the first light lights nothing (Shading is off or its intensity is 0) + /// or does not reach the plane (it is behind the object for a shadow behind it, or below the + /// plane for one below), or when nothing of the shadow falls within the plane. + pub fn path(&self, shadow: Shadow) -> Option { + let all = 0..self.faces.len(); + let all = std::slice::from_ref(&all); + self.path_on(&self.shadow_plane(shadow, all)?, all) + } + + /// The faces in the ranges `faces`, from the faces gathered. + fn within(&self, faces: &[Range]) -> impl Iterator { + faces.iter().flat_map(|r| self.faces.get(r.clone()).unwrap_or_default()) + } + + /// The plane `shadow` falls on for the faces in the ranges `faces` (its distance, size and + /// center follow from them), for [`ShadowCaster::path_on`]: `None` when there are none or when + /// the first light lights nothing or does not reach the plane. + pub fn shadow_plane(&self, shadow: Shadow, faces: &[Range]) -> Option { + let p = self.projection?; + let light = p.light()?; + let s = shadow.sanitized(); + let corners = || self.within(faces).flat_map(|(contours, _)| contours.iter().flatten()); + let first = *corners().next()?; + let (lo, hi) = corners() + .fold((first, first), |(lo, hi), v| (V3(lo.0.min(v.0), lo.1.min(v.1), lo.2.min(v.2)), V3(hi.0.max(v.0), hi.1.max(v.1), hi.2.max(v.2)))); + let size = (hi.0 - lo.0).max(hi.1 - lo.1).max(hi.2 - lo.2).max(1e-9); + // The plane's normal toward the object, and two axes along it. + let (n, u, w) = match s.position { + ShadowPosition::Behind => (V3(0.0, 0.0, 1.0), V3(1.0, 0.0, 0.0), V3(0.0, 1.0, 0.0)), + ShadowPosition::Below => { + let r = |v: V3| p.view.rotate(v).unit(); + (r(V3(0.0, -1.0, 0.0)), r(V3(1.0, 0.0, 0.0)), r(V3(0.0, 0.0, 1.0))) + } + }; + let reach = n.dot(light); + if !reach.is_finite() || reach < MIN_LIGHT { + return None; + } + // The plane: every corner at least `distance` × size in front of it. + let level = corners().map(|v| n.dot(*v)).fold(f64::INFINITY, f64::min) - s.distance * size; + let centre = V3((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0, (lo.2 + hi.2) / 2.0); + let foot = add(centre, scale(n, level - n.dot(centre))); + Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size }) + } + + /// The shadow the faces in the ranges `faces` cast on `plane`, on the page, filled with the + /// nonzero rule; `None` when nothing of it falls within the plane. + pub fn path_on(&self, plane: &ShadowPlane, faces: &[Range]) -> Option { + let &ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half } = plane; + // A corner's shadow, in the plane's axes about the foot. + let cast = |v: V3| { + let q = add(v, scale(light, -(n.dot(v) - level) / reach)); + let d = q.sub(foot); + Point::new(u.dot(d), w.dot(d)) + }; + let to_page = |q: Point| p.project(add(foot, add(scale(u, q.x), scale(w, q.y)))); + let mut bp = BezPath::new(); + for (contours, _) in self.within(faces) { + let flat: Vec> = contours.iter().map(|c| c.iter().map(|v| cast(*v)).collect()).collect(); + let turn: f64 = flat.iter().map(|c| signed_area(c)).sum(); + // A face edge-on to the light casts nothing. + if flat_area(turn, flat.iter().flatten()) { + continue; + } + for c in &flat { + let mut clipped = clip(c, half); + if turn < 0.0 { + clipped.reverse(); + } + // A plane seen edge-on draws nothing. + let page: Vec = clipped.into_iter().map(to_page).collect(); + if flat_area(signed_area(&page), &page) { + continue; + } + let Some((start, rest)) = page.split_first() else { continue }; + bp.move_to(*start); + for q in rest { + bp.line_to(*q); + } + bp.close_path(); + } + } + let path = PathData::from_bezpath(&bp); + (!path.subpaths.is_empty()).then_some(path) + } +} + +/// Whether `area`, the signed area of a polygon with corners `points`, is within rounding of +/// nothing for its size (the square of its bounds' diagonal), or not a number, so the polygon draws +/// nothing. A long, narrow polygon keeps an area well above that. +fn flat_area<'a>(area: f64, points: impl IntoIterator) -> bool { + let mut points = points.into_iter(); + let Some(first) = points.next() else { return true }; + let bounds = points.fold(Rect::from_points(*first, *first), |b, p| b.union_pt(*p)); + let size = bounds.width().powi(2) + bounds.height().powi(2); + !area.is_finite() || !size.is_finite() || area.abs() <= 1e-14 * size +} + +fn add(a: V3, b: V3) -> V3 { + V3(a.0 + b.0, a.1 + b.1, a.2 + b.2) +} + +fn scale(a: V3, k: f64) -> V3 { + V3(a.0 * k, a.1 * k, a.2 * k) +} + +/// Twice the signed area of polygon `c` (positive counterclockwise with y up). +fn signed_area(c: &[Point]) -> f64 { + c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| a.x * b.y - b.x * a.y).sum::() / 2.0 +} + +/// Polygon `c` cut to the square from -`half` to `half` on both axes, edge by edge (the square is +/// convex, so each contour's winding inside it is kept). +fn clip(c: &[Point], half: f64) -> Vec { + let mut out: Vec = c.to_vec(); + // Each side: the axis it cuts across (x or y) and whether it is the upper one. + for (across_x, upper) in [(true, false), (true, true), (false, false), (false, true)] { + let coord = |p: Point| if across_x { p.x } else { p.y }; + let limit = if upper { half } else { -half }; + let inside = |p: Point| if upper { coord(p) <= limit } else { coord(p) >= limit }; + let input = std::mem::take(&mut out); + let Some(&last) = input.last() else { break }; + let mut prev = last; + for &cur in &input { + let (a, b) = (inside(prev), inside(cur)); + if a != b { + let (pc, cc) = (coord(prev), coord(cur)); + let t = (limit - pc) / (cc - pc); + out.push(prev.lerp(cur, t)); + } + if b { + out.push(cur); + } + prev = cur; + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs new file mode 100644 index 0000000000..3fb3767177 --- /dev/null +++ b/crates/three-d/src/shadow/tests.rs @@ -0,0 +1,187 @@ +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Shape}; + +use super::*; +use crate::{Extrude, Inflate, Light, Lights, Revolve, View}; + +fn square(x: f64, y: f64, s: f64) -> PathData { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + s, y)); + b.line_to((x + s, y + s)); + b.line_to((x, y + s)); + b.close_path(); + PathData::from_bezpath(&b) +} + +/// The view straight on: no rotation, the default light. +fn front() -> View { + View { rotation_x: 0.0, rotation_y: 0.0, rotation_z: 0.0, ..View::default() } +} + +fn extruded(view: View, shadow: Shadow) -> Option { + let path = square(100.0, 100.0, 100.0); + let mut caster = ShadowCaster::new(); + caster.extrude(&path, FillRule::NonZero, Rect::new(100.0, 100.0, 200.0, 200.0), Extrude::default(), view).unwrap(); + caster.path(shadow) +} + +/// The area the shadow covers, sampled on a grid over `r` with the nonzero rule. +fn covered(path: &PathData, r: Rect, steps: usize) -> f64 { + let bp = path.to_bezpath(); + let (dx, dy) = (r.width() / steps as f64, r.height() / steps as f64); + let mut hits = 0; + for i in 0..steps { + for j in 0..steps { + let p = Point::new(r.x0 + (i as f64 + 0.5) * dx, r.y0 + (j as f64 + 0.5) * dy); + if bp.winding(p) != 0 { + hits += 1; + } + } + } + hits as f64 * dx * dy +} + +#[test] +fn a_light_straight_in_front_casts_the_silhouette_behind_the_object() { + let view = View { light_height: 90.0, ..front() }; + let path = extruded(view, Shadow::default()).expect("a shadow"); + let b = path.bounds().unwrap(); + for (got, want) in [(b.x0, 100.0), (b.y0, 100.0), (b.x1, 200.0), (b.y1, 200.0)] { + assert!((got - want).abs() < 1e-6, "{b:?}"); + } + // Every face of the box projects into the square, and the nonzero union fills it whole. + let area = covered(&path, Rect::new(90.0, 90.0, 210.0, 210.0), 120); + assert!((area - 10_000.0).abs() < 300.0, "{area}"); +} + +#[test] +fn the_shadow_behind_falls_away_from_the_light_and_moves_with_the_distance() { + // The default light is up and to the left, in front: the shadow falls down and to the right. + let near = extruded(front(), Shadow::default()).unwrap().bounds().unwrap(); + assert!(near.x1 > 200.0 + 1.0 && near.y1 > 200.0 + 1.0, "{near:?}"); + assert!(near.x0 >= 100.0 - 1e-6 && near.y0 >= 100.0 - 1e-6, "{near:?}"); + let far = extruded(front(), Shadow { distance: 1.0, ..Shadow::default() }).unwrap().bounds().unwrap(); + assert!(far.x1 > near.x1 + 10.0 && far.y1 > near.y1 + 10.0, "{near:?} {far:?}"); +} + +#[test] +fn a_light_behind_the_object_casts_no_shadow_behind_it() { + assert!(extruded(View { light_behind: true, ..front() }, Shadow::default()).is_none()); + let behind = Light { behind: true, ..Light::default() }; + let lights = Lights::new(&[behind, Light::default()]).unwrap(); + // The first light casts the shadow. + assert!(extruded(View { lights: Some(lights), ..front() }, Shadow::default()).is_none()); + let lights = Lights::new(&[Light::default(), behind]).unwrap(); + assert!(extruded(View { lights: Some(lights), ..front() }, Shadow::default()).is_some()); +} + +#[test] +fn a_light_that_lights_nothing_casts_no_shadow() { + assert!(extruded(View { light_intensity: 0.0, ..front() }, Shadow::default()).is_none()); + assert!(extruded(View { shade: false, ..front() }, Shadow::default()).is_none()); + let dark = Light { intensity: 0.0, ..Light::default() }; + let lights = Lights::new(&[dark, Light::default()]).unwrap(); + assert!(extruded(View { lights: Some(lights), ..front() }, Shadow::default()).is_none()); +} + +#[test] +fn the_shadow_below_lies_under_the_object_on_its_floor() { + let below = Shadow { position: ShadowPosition::Below, ..Shadow::default() }; + // Seen level, the floor is edge-on: nothing to draw. + assert!(extruded(front(), below).is_none()); + // Seen from above (the effects' default Off-Axis Front view), the floor shows. + let off_axis = View { rotation_x: -21.88, rotation_y: -23.4, rotation_z: 9.06, ..View::default() }; + assert!(extruded(off_axis, below).is_some()); + // Seen from straight above, the floor is square to the view, under the object: with the light + // straight in front too, the shadow is the object's outline, as the one behind it is. + let top = View { rotation_x: -90.0, light_height: 90.0, ..front() }; + let under = extruded(top, below).unwrap().bounds().unwrap(); + let back = extruded(top, Shadow::default()).unwrap().bounds().unwrap(); + for (a, b) in [(under.x0, back.x0), (under.y0, back.y0), (under.x1, back.x1), (under.y1, back.y1)] { + assert!((a - b).abs() < 1e-6, "{under:?} {back:?}"); + } + // A light from below the floor casts nothing on it. + let from_below = View { light_rotation: -90.0, light_height: 0.0, ..off_axis }; + assert!(extruded(from_below, below).is_none()); +} + +#[test] +fn shadow_bounds_limit_the_plane_the_shadow_falls_on() { + // A low light casts a long shadow; the plane cuts it. + let low = View { light_height: 5.0, ..front() }; + let small = extruded(low, Shadow { bounds: 0.1, ..Shadow::default() }).unwrap().bounds().unwrap(); + let large = extruded(low, Shadow { bounds: 4.0, ..Shadow::default() }).unwrap().bounds().unwrap(); + // At 10 % the square reaches 0.2 × the size (100) from the foot of the center (150, 150). + for v in [small.x0, small.y0, small.x1, small.y1] { + assert!((130.0 - 1e-6..=170.0 + 1e-6).contains(&v), "{small:?}"); + } + assert!(large.width() > small.width() * 5.0, "{small:?} {large:?}"); + for v in [large.x0, large.y0, large.x1, large.y1] { + assert!((-650.0 - 1e-6..=950.0 + 1e-6).contains(&v), "{large:?}"); + } +} + +#[test] +fn bad_settings_are_sanitized_and_an_empty_caster_casts_nothing() { + assert!(ShadowCaster::new().path(Shadow::default()).is_none()); + let wild = Shadow { distance: f64::NAN, bounds: f64::INFINITY, ..Shadow::default() }; + assert_eq!(wild.sanitized(), Shadow { bounds: 1.0, ..Shadow::default() }); + assert_eq!(Shadow { distance: -3.0, bounds: 99.0, ..Shadow::default() }.sanitized(), Shadow { bounds: 4.0, ..Shadow::default() }); + assert_eq!(ShadowPosition::parse("below"), Some(ShadowPosition::Below)); + assert_eq!(ShadowPosition::parse("under"), None); +} + +#[test] +fn the_faces_one_shadow_is_cast_from_are_bounded() { + // An open profile of 500 points revolves into about 64,000 faces at 128 segments: five fit, + // the sixth does not. + let mut b = BezPath::new(); + b.move_to((110.0, 0.0)); + for i in 1..500 { + b.line_to((110.0 + f64::from(i % 2) * 5.0, f64::from(i))); + } + let path = PathData::from_bezpath(&b); + let bounds = path.bounds().unwrap(); + let options = Revolve { segments: 128, offset: 10.0, ..Revolve::default() }; + let mut caster = ShadowCaster::new(); + for _ in 0..5 { + let faces = caster.revolve(&path, FillRule::NonZero, bounds, options).unwrap(); + assert!(faces.len() > 60_000, "{faces:?}"); + } + let err = caster.revolve(&path, FillRule::NonZero, bounds, options).unwrap_err(); + assert!(err.contains("too complex"), "{err}"); + assert!(caster.len() <= MAX_SHADOW_FACES); + assert!(caster.path(Shadow::default()).is_some()); +} + +#[test] +fn a_small_solid_beside_a_huge_one_keeps_its_shadow() { + let bounds = Rect::new(0.0, 0.0, 1_000_010.0, 10.0); + let view = View { light_height: 90.0, ..front() }; + let mut caster = ShadowCaster::new(); + let small = caster.extrude(&square(0.0, 0.0, 10.0), FillRule::NonZero, bounds, Extrude::default(), view).unwrap(); + let huge = caster.extrude(&square(1_000_000.0, 0.0, 10.0), FillRule::NonZero, bounds, Extrude::default(), view).unwrap(); + let all = [small.clone(), huge]; + let plane = caster.shadow_plane(Shadow { bounds: 4.0, ..Shadow::default() }, &all).unwrap(); + let path = caster.path_on(&plane, std::slice::from_ref(&small)).expect("the small solid's shadow"); + let b = path.bounds().unwrap(); + assert!((b.width() - 10.0).abs() < 1e-3 && (b.height() - 10.0).abs() < 1e-3, "{b:?}"); +} + +#[test] +fn every_effect_casts_a_shadow() { + let path = square(100.0, 100.0, 100.0); + let bounds = Rect::new(100.0, 100.0, 200.0, 200.0); + let mut plane = ShadowCaster::new(); + plane.plane(&path, FillRule::NonZero, bounds, View::default()).unwrap(); + assert!(plane.path(Shadow::default()).is_some()); + let mut inflate = ShadowCaster::new(); + let results = inflate.inflate(&[(&path, FillRule::NonZero)], &[true], bounds, Inflate::default(), View::default()); + assert!(results.iter().all(Result::is_ok)); + assert!(inflate.path(Shadow::default()).is_some()); + let mut revolve = ShadowCaster::new(); + revolve.revolve(&path, FillRule::NonZero, bounds, Revolve::default()).unwrap(); + let b = revolve.path(Shadow::default()).unwrap().bounds().unwrap(); + // The surface turns about the square's left edge, reaching 100 to either side of it. + assert!(b.x1 > 100.0 && b.x0 < 100.0 + 1e-6, "{b:?}"); +} diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 45d7d310b2..18c9959b19 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -257,6 +257,12 @@ pub struct Facet { /// The facet's outline with the profile's curves kept as cubics, for [`Facet::path`]. The /// contours stay the polygon that visibility and depth use. pub outline: Option, + /// The facet is a piece of the solid's sides (Extrude & Bevel's walls and bevels, Inflate's + /// sides) rather than of its ends (the caps, a plane, Inflate's front and back). + pub side: bool, + /// The facet is turned away from the viewer: a closed solid keeps it (seen edge-on, or with + /// Draw Hidden Faces) and draws it behind the facets turned toward the viewer. + pub away: bool, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, @@ -288,6 +294,24 @@ impl Facet { } PathData::from_bezpath(&bp) } + + /// Revolve's face `face` as a facet: its polygon, curved outline, depth, normal and lighting. + /// A face that joins the profile's ends round the axis is a side; a cap is an end. + pub(crate) fn of_face(face: crate::Face) -> Self { + Facet { + contours: vec![face.points], + depth: face.depth, + brightness: face.brightness, + illumination: face.illumination, + normal: face.normal, + rgb_gradient: None, + outline: face.outline, + side: !face.cap, + away: false, + #[cfg(test)] + view: vec![], + } + } } fn finite(v: f64, fallback: f64, min: f64, max: f64) -> f64 { diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 66a22f80fa..0b429409c7 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -9,6 +9,7 @@ use super::{ Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, Point, Rect, Revolve, V3, View, eye_distance, perspective_scale, }; +use crate::shadow::Projection; /// Turns 3D points into document points and shades faces for one view. pub(super) struct Camera { @@ -48,14 +49,19 @@ impl Camera { pub(super) fn brightness(&self, n: V3) -> f64 { crate::brightness(&self.view, n, self.light) } + /// The rotation and projection this camera draws with, for a shadow cast from its faces. + pub(super) fn projection(&self) -> Projection { + Projection { view: self.view, origin: self.origin, eye: self.eye } + } } /// A face of a solid before projection: its contours in view space (holes running the other way) /// and its outward normal. pub(crate) type Face3 = (Vec>, V3); -/// What a solid's builder makes: its facets, or with a mesh asked for, its faces before projection. -pub(crate) type Built = (Vec, Vec); +/// What a solid's builder makes: its facets, or with a mesh asked for, its faces before projection, +/// and the projection it used (`None` when nothing was built). +pub(crate) type Built = (Vec, Vec, Option); /// Facets being collected for one solid. pub(super) struct Builder<'a> { @@ -142,6 +148,8 @@ impl Builder<'_> { normal: [n.0, n.1, n.2], rgb_gradient: None, outline: None, + side: false, + away: behind, #[cfg(test)] view, }); @@ -221,6 +229,11 @@ impl Builder<'_> { } let before = self.facets.len(); self.face(vec![quad], normal, order)?; + if self.facets.len() > before + && let Some(f) = self.facets.last_mut() + { + f.side = true; + } if let Some(w) = curves.as_mut().filter(|_| pieces == 1) && let Some(span) = w.spans.get(i).copied().flatten() { @@ -250,7 +263,7 @@ impl Builder<'_> { /// The facets back to front, and the faces kept for a mesh (none without [`Builder::mesh`]). pub(super) fn finish(mut self) -> Built { self.facets.sort_by(|a, b| a.depth.total_cmp(&b.depth)); - (self.facets, self.mesh.unwrap_or_default()) + (self.facets, self.mesh.unwrap_or_default(), Some(self.camera.projection())) } } @@ -492,7 +505,7 @@ fn steps(o: &Extrude) -> Vec { /// Extrude & Bevel: the shape's outline extruded backwards, with optional twist, taper, bevels /// and caps. pub fn extrude(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result, String> { - extrude_faces(path, rule, bounds, options, view, false).map(|(facets, _)| facets) + extrude_faces(path, rule, bounds, options, view, false).map(|(facets, ..)| facets) } /// [`extrude`], or with `mesh` the solid's faces before projection instead of its facets. @@ -602,7 +615,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio /// Rotate: the flat art turned in 3D about the centre of `bounds` (which may be larger than the /// shape's own, so that every part of one object turns about the same point). pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result, String> { - plane_faces(path, rule, bounds, view, false).map(|(facets, _)| facets) + plane_faces(path, rule, bounds, view, false).map(|(facets, ..)| facets) } /// [`plane`], or with `mesh` its face before projection instead of its facet. diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 20242697f1..47ce3371db 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -62,7 +62,7 @@ pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, /// on its own over the grid of `bounds`, and one eye sees them all, as far away as the highest /// puff needs with Perspective. One result for each shape, in order. pub fn inflate_together(shapes: &[(&PathData, FillRule)], bounds: Rect, options: Inflate, view: View) -> Vec, String>> { - inflate_faces(shapes, bounds, options, view, false).map(|r| r.map(|(facets, _)| facets)).collect() + inflate_faces(shapes, bounds, options, view, false).map(|r| r.map(|(facets, ..)| facets)).collect() } /// [`inflate_together`], or with `mesh` each solid's faces before projection instead of its facets. @@ -81,7 +81,7 @@ pub(crate) fn inflate_faces( let reach = puffs.iter().flatten().flatten().map(|p| p.height).fold(0.0, f64::max); puffs.into_iter().map(move |p| match p { Ok(Some(p)) => inflated(p, bounds, o, view, reach, mesh), - Ok(None) => Ok((vec![], vec![])), + Ok(None) => Ok((vec![], vec![], None)), Err(e) => Err(e), }) } diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index af9322bc12..be887180b2 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -98,6 +98,33 @@ fn hidden_faces_draw_every_face_of_the_solid_behind_the_visible_ones() { } } +/// Each facet says whether it is a piece of the solid's sides and whether it is turned away from +/// the viewer: a box's walls and bevels are sides and its two caps are not; Inflate's sides are +/// sides and its front is not. +#[test] +fn facets_tell_the_sides_from_the_ends_and_the_faces_turned_away() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let v = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + let bevel = Bevel { width: 10.0, height: 10.0, ..Bevel::default() }; + for o in [Extrude { hidden: true, ..Extrude::default() }, Extrude { hidden: true, bevel: Some(bevel), ..Extrude::default() }] { + let all = extrude(&p, FillRule::EvenOdd, b, o, v).unwrap(); + let ends: Vec<&Facet> = all.iter().filter(|f| !f.side).collect(); + let [a, c] = ends[..] else { panic!("two caps among {} facets", all.len()) }; + let along = a.normal[0] * c.normal[0] + a.normal[1] * c.normal[1] + a.normal[2] * c.normal[2]; + assert!(close(along, -1.0, 1e-9), "the caps face opposite ways: {along}"); + assert!(all.len() > 6 || o.bevel.is_none(), "the bevel adds sides"); + // The faces turned away are drawn first, the others after them. + let away = all.iter().take_while(|f| f.away).count(); + assert!(away > 0 && all[away..].iter().all(|f| !f.away), "{away} of {}", all.len()); + } + let shown = extrude(&p, FillRule::EvenOdd, b, Extrude::default(), v).unwrap(); + assert!(shown.iter().all(|f| !f.away)); + let puff = inflate(&p, FillRule::EvenOdd, b, Inflate { depth: 20.0, ..Inflate::default() }, v).unwrap(); + assert!(puff.iter().any(|f| f.side) && puff.iter().any(|f| !f.side)); + let flat = inflate(&p, FillRule::EvenOdd, b, Inflate::default(), v).unwrap(); + assert!(!flat.is_empty() && flat.iter().all(|f| !f.side)); +} + #[test] fn taper_shrinks_the_back_and_twist_turns_it() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); diff --git a/crates/three-d/src/tests/classic.rs b/crates/three-d/src/tests/classic.rs index 1d807b4a3e..f460297453 100644 --- a/crates/three-d/src/tests/classic.rs +++ b/crates/three-d/src/tests/classic.rs @@ -94,3 +94,32 @@ fn surfaces_round_trip_through_their_ids() { assert_eq!(ClassicSurface::parse("glossy"), None); assert_eq!(ClassicSurface::default(), ClassicSurface::Plastic); } + +#[test] +fn revolve_facets_keep_each_face_normal_turned_to_the_viewer() { + // A cylinder of radius 30 about the left edge, with closed ends, tipped toward the viewer. + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((130.0, 0.0)); + b.line_to((130.0, 100.0)); + b.line_to((100.0, 100.0)); + let path = PathData::from_bezpath(&b); + let options = Revolve { rotation_x: -30.0, shade: false, smooth_shading: false, ..Revolve::default() }; + let faces = revolve(&path, path.bounds().unwrap(), options).unwrap(); + let facets = revolve_facets(&path, path.bounds().unwrap(), options).unwrap(); + assert_eq!(facets.len(), faces.len()); + for (facet, face) in facets.iter().zip(&faces) { + let [x, y, z] = facet.normal; + assert!(((x * x + y * y + z * z).sqrt() - 1.0).abs() < 1e-9, "unit length: {:?}", facet.normal); + assert!(z >= 0.0, "turned to the viewer: {:?}", facet.normal); + assert_eq!((facet.depth, facet.side), (face.depth, !face.cap)); + } + // Tipped 30°, the wall faces nearest the viewer turn 30° down from it, and the flat top and bottom + // (the profile's horizontal edges swept round) face up and out at 30°. + let (s, c) = 30f64.to_radians().sin_cos(); + assert!(facets.iter().any(|f| f.normal[2] > c - 0.01 && (f.normal[1] - s).abs() < 0.01), "{facets:?}"); + assert!(facets.iter().any(|f| (f.normal[1] + c).abs() < 1e-6 && (f.normal[2] - s).abs() < 1e-6), "{facets:?}"); + // Moved off the axis, the profile's open ends close with caps, which are ends rather than sides. + let ring = revolve_facets(&path, path.bounds().unwrap(), Revolve { offset: 10.0, ..options }).unwrap(); + assert!(ring.iter().any(|f| !f.side && (f.normal[1] + c).abs() < 1e-6 && (f.normal[2] - s).abs() < 1e-6)); +} diff --git a/crates/three-d/src/visibility.rs b/crates/three-d/src/visibility.rs index f66187fcf9..db8f5b0df7 100644 --- a/crates/three-d/src/visibility.rs +++ b/crates/three-d/src/visibility.rs @@ -293,6 +293,7 @@ mod tests { Face { points: vec![Point::new(rect.x0, rect.y0), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)], depth: brightness, + normal: [0.0, 0.0, 1.0], brightness, gradient: None, illumination: [brightness; 3], diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 68c19cc676..ee7440dde6 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -6,7 +6,8 @@ //! tangent); a drag makes a smooth anchor (Alt held breaks the outgoing handle off, Shift keeps it //! to 45° steps, Space moves the anchor); Tab switches the segment into the anchor being placed, or //! the last one drawn, between straight and curved. A rubber band shows the next segment. A click -//! on the first anchor closes the path, on an end of another open path joins the two, and away +//! on the first anchor closes the path (a drag from it shapes the closing segment as the Pen's +//! closing drag does), on an end of another open path joins the two, and away //! from paths, with no path being drawn, starts a new one. Enter or Esc ends the path. //! //! Editing the shown paths' points: a click selects a point (an end of an open path is then drawn @@ -30,7 +31,7 @@ use vectorcraft_pathops::addons::pen::{leave_handle, straighten_segment}; use crate::direct::hit_handle; use crate::draw2::{anchor_in, hit_segment, segment_in, shown_paths}; use crate::guides::{DrawSnap, Leave}; -use crate::pen::{active_path, continue_from, open_end_at}; +use crate::pen::{active_path, close_drag, continue_from, first_anchor, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The tool's id. @@ -82,11 +83,13 @@ struct Place { #[derive(Clone, Copy, Debug, PartialEq)] enum Target { Place(Place), - /// Closing the path being drawn on its first anchor, at `first`. + /// Closing the path being drawn on its first anchor, at `first`; `anchor` holds that anchor as + /// the press found it and its outgoing handle as the drag last left it. Close { id: NodeId, si: usize, first: Point, + anchor: Option<(Anchor, Point)>, }, /// An anchor of a shown path at `p`; `n` anchors in its subpath, `closed` or not. Point { @@ -285,7 +288,8 @@ impl SmartPenTool { let press = |what| Press { at: ev.pos, mods: ev.mods, dragged: false, begun: false, what }; match self.hit(cx, ev.pos) { Hit::Close(id, si, first) => { - self.press = Some(Press { begun: true, ..press(Target::Close { id, si, first }) }); + let anchor = first_anchor(cx, id, si).map(|a| (a, a.h_out)); + self.press = Some(Press { begun: true, ..press(Target::Close { id, si, first, anchor }) }); let seg = if self.curved { "curved" } else { "straight" }; vec![ Action::Begin("Close Path".into()), @@ -362,10 +366,11 @@ impl SmartPenTool { pr.what = Target::Place(pl); ("", self.place_preview(&pl, true)) } - Target::Close { id, si, first } => { + Target::Close { id, si, first, mut anchor } => { let out = Self::handle_to(cx, first, ev.pos, first, shift, false); - let h_in = first - (out - first); - ("", Action::Preview("path.close".into(), json!({"id": id.0, "subpath": si, "in": xy(h_in), "independent": alt}))) + let act = close_drag(id, Some(si), first - (out - first), alt, anchor.as_mut()); + pr.what = Target::Close { id, si, first, anchor }; + ("", act) } Target::Point { id, si, ai, p, .. } if pr.mods.alt => { let h = Self::handle_to(cx, p, ev.pos, p, shift, false); diff --git a/crates/tools/src/addons/smart_pen/tests.rs b/crates/tools/src/addons/smart_pen/tests.rs index 0f6bd5c912..a7f792c22f 100644 --- a/crates/tools/src/addons/smart_pen/tests.rs +++ b/crates/tools/src/addons/smart_pen/tests.rs @@ -157,7 +157,13 @@ fn a_press_on_the_first_anchor_closes_the_path() { // A drag shapes the closing curve. let (c, params) = preview(&t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 100.0, NO))); assert_eq!((c.as_str(), params["in"].clone()), ("path.close", json!([70.0, 100.0]))); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 100.0, NO)), vec![Action::Commit]); + // Alt pressed mid-drag makes the anchor a corner and keeps its outgoing handle where it was. + let (_, params) = preview(&t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 120.0, ALT))); + assert_eq!( + (params["in"].clone(), params["out"].clone(), params["independent"].clone()), + (json!([70.0, 80.0]), json!([100.0, 100.0]), json!(true)) + ); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 120.0, ALT)), vec![Action::Commit]); assert!(!t.drawing, "the path is finished"); } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index b8e5840c26..1c5a895161 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -37,8 +37,8 @@ use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; use live_paint::LpHover; use live_paint::lp_color; pub use live_paint::{ - LP_BUCKET_EDGE_FRACTION, LP_BUCKET_WIDTH, LP_BUCKET_WIDTH_RANGE, LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE, LivePaintBucketTool, - LivePaintSelectionTool, + LP_BUCKET_EDGE_FRACTION, LP_BUCKET_WIDTH, LP_BUCKET_WIDTH_RANGE, LP_FILL_CHUNK_POINTS, LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE, + LivePaintBucketTool, LivePaintSelectionTool, }; pub use lookup::{ EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, SOURCES_NAME, builder_members, drawn_outlines, edge_near, edges, face_at, faces, diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 08fca14327..010e423743 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -114,7 +114,8 @@ enum LpPaint { } /// Live Paint Bucket: by default, a click fills the face under the cursor with the current fill, -/// and Shift-click paints the nearest edge with the current stroke. Alt-click samples a fill or +/// and dragging fills the faces crossed in that group as one undo step (Escape cancels). +/// Shift-click paints the nearest edge with the current stroke. Alt-click samples a fill or /// stroke into the paint defaults; Alt+Shift-click samples only the color under the pointer. /// Clicking selected ordinary paths without Alt makes them a Live Paint group first. Its Tool /// Options (double-click the tool) are `paintFills` (on) and `paintStrokes` (off), `highlight` @@ -130,6 +131,8 @@ pub struct LivePaintBucketTool { pub(super) hover: LpHover, /// Where the pointer last moved, and whether Shift and Alt were held. at: Option<(Point, bool, bool)>, + /// The fill command and polyline previewed from the press's snapshot. + fill_drag: Option<(Value, Vec>)>, fills: bool, strokes: bool, highlight: bool, @@ -137,12 +140,16 @@ pub struct LivePaintBucketTool { width: f64, } +/// Maximum points in one Live Paint fill path chunk. +pub const LP_FILL_CHUNK_POINTS: usize = 4096; + impl Default for LivePaintBucketTool { fn default() -> Self { Self { cache: RegionCache::live_paint(), hover: LpHover::None, at: None, + fill_drag: None, fills: true, strokes: false, highlight: true, @@ -153,6 +160,36 @@ impl Default for LivePaintBucketTool { } impl LivePaintBucketTool { + fn begin_fill(&mut self, params: Value, p: Point) -> Vec { + self.fill_drag = Some((params.clone(), vec![vec![p]])); + vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), params)] + } + + fn drag_fill(&mut self, p: Point) -> Vec { + let Some((params, chunks)) = &mut self.fill_drag else { return vec![] }; + let Some(points) = chunks.last_mut() else { return vec![] }; + let Some(&last) = points.last() else { return vec![] }; + if last == p { + return vec![]; + } + if points.len() == LP_FILL_CHUNK_POINTS { + // Share the boundary point so no segment is lost between chunks. + chunks.push(vec![last, p]); + } else { + points.push(p); + } + let mut params = params.clone(); + let mut chunks = chunks.iter().map(|chunk| json!(chunk.iter().map(|p| [p.x, p.y]).collect::>())); + if let Some(first) = chunks.next() { + params["points"] = first; + } + let continuation: Vec<_> = chunks.collect(); + if !continuation.is_empty() { + params["continuation"] = Value::Array(continuation); + } + vec![Action::Preview("livePaint.fill".into(), params)] + } + /// What a click paints, Shift held or not. Shift switches Paint Fills alone to Paint Strokes /// alone and back, and switches both to Paint Fills alone. fn paints(&self, shift: bool) -> LpPaint { @@ -191,6 +228,12 @@ impl Tool for LivePaintBucketTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; + // A second press finishes the preceding click, including callers without a release. + if ev.kind == PointerKind::Down && self.fill_drag.take().is_some() { + let mut acts = vec![Action::Commit]; + acts.extend(self.pointer(cx, ev)); + return acts; + } match ev.kind { PointerKind::Move => { self.at = Some((p, ev.mods.shift, ev.mods.alt)); @@ -232,18 +275,42 @@ impl Tool for LivePaintBucketTool { return vec![]; } if let Some(g) = live_paint_at(cx.doc, p) { - return vec![Action::Exec("livePaint.fill".into(), json!({ "group": g.0, "point": point }))]; + return self.begin_fill(json!({ "group": g.0, "point": point }), p); } if self.cache.at(cx, p).is_some() { let roots = sorted_roots(cx.doc, &cx.selection.objects); - return vec![Action::Exec("livePaint.fill".into(), json!({ "ids": json_ids(&roots), "point": point }))]; + return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p); } vec![] } + PointerKind::Drag => self.drag_fill(p), + PointerKind::Up => { + let mut acts = self.drag_fill(p); + if self.fill_drag.take().is_some() { + acts.push(Action::Commit); + } + acts + } _ => vec![], } } + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] } + } + + fn busy(&self) -> bool { + self.fill_drag.is_some() + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.busy() + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] } + } + fn overlays(&self, _cx: &ToolContext) -> Vec { lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32) } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 4e3919db89..eeaf8f0ea7 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1045,6 +1045,25 @@ fn live_square(d: &mut Document, r: Rect) -> (NodeId, [NodeId; 4]) { (gid, ids) } +#[test] +fn bucket_long_drag_keeps_turns_and_release_after_the_point_limit() { + let (d, gid, ..) = live_group_doc(); + let s = Selection::default(); + let paint = paint(); + let cx = cx(&d, &s, &paint); + let mut t = LivePaintBucketTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); + for i in 1..4096 { + t.pointer(&cx, &ev(PointerKind::Drag, 25.0 + f64::from(i) / 10000.0, 25.0)); + } + t.pointer(&cx, &ev(PointerKind::Drag, 25.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 100.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)); + let [Action::Preview(id, params), Action::Commit] = acts.as_slice() else { panic!("release must extend the drag before committing") }; + assert_eq!(id, "livePaint.fill"); + assert_eq!(params["group"], gid.0); +} + #[test] fn bucket_click_fills_face_and_shift_click_strokes_edge() { let (d, gid, f2, _e) = live_group_doc(); @@ -1058,9 +1077,10 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() { let ov = t.overlays(&cx); assert!(matches!(&ov[0], Overlay::Path { color: HIGHLIGHT_RED, .. })); let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)); - let Action::Exec(id, v) = &acts[0] else { panic!() }; + let [Action::Begin(_), Action::Preview(id, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!(id, "livePaint.fill"); assert_eq!(v["group"], gid.0); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)), vec![Action::Commit]); let shift = Mods { shift: true, ..Default::default() }; let acts = t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift)); let Action::Exec(id, _) = &acts[0] else { panic!() }; @@ -1074,9 +1094,15 @@ fn bucket_options_choose_what_a_click_paints() { let p = paint(); let cx = cx(&d, &s, &p); let shift = Mods { shift: true, ..Default::default() }; - let fill = |x: f64| vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))]; + let fill = |x: f64| { + vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))] + }; let stroke = |x: f64| vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 }))]; - let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m)); + let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| { + let acts = t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m)); + t.pointer(&cx, &ev(PointerKind::Up, x, 25.0).with_mods(m)); + acts + }; let hovered = |t: &mut LivePaintBucketTool, x: f64, m: Mods| { t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(m)); match t.overlays(&cx).as_slice() { @@ -1162,7 +1188,9 @@ fn bucket_options_set_the_highlight() { // Highlight off: nothing is highlighted, and a click still paints. t.set_option("highlight", &json!(false)); assert_eq!(highlight(&mut t), None); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)).len(), 1); + let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)); + assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, _)] if id == "livePaint.fill")); + t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)); t.set_option("highlight", &json!(true)); assert!(highlight(&mut t).is_some()); } @@ -1326,7 +1354,7 @@ fn bucket_on_plain_selection_makes_live_paint() { let cx = cx(&d, &s, &p); let mut t = LivePaintBucketTool::default(); let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); - let Action::Exec(id, v) = &acts[0] else { panic!() }; + let [Action::Begin(_), Action::Preview(id, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!(id, "livePaint.fill"); assert_eq!(v["ids"], json!([a.0, b.0])); } @@ -1344,7 +1372,13 @@ fn bucket_rebuilds_its_map_for_a_new_revision_at_the_same_address() { d = two_rects_at(300.0).0; let cx2 = ToolContext { revision: (1, 2), ..cx(&d, &s, &p) }; let acts = t.pointer(&cx2, &ev(PointerKind::Down, 375.0, 50.0)); - assert_eq!(acts, vec![Action::Exec("livePaint.fill".into(), json!({ "ids": [a.0, b.0], "point": [375.0, 50.0] }))]); + assert_eq!( + acts, + vec![ + Action::Begin("Live Paint Bucket".into()), + Action::Preview("livePaint.fill".into(), json!({ "ids": [a.0, b.0], "point": [375.0, 50.0] })) + ] + ); } #[test] @@ -1357,7 +1391,8 @@ fn bucket_keeps_its_map_while_the_document_is_unchanged() { let cx1 = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) }; t.pointer(&cx1, &ev(PointerKind::Move, 75.0, 50.0)); let acts = t.pointer(&cx1, &ev(PointerKind::Down, 75.0, 50.0)); - assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "livePaint.fill"), "{acts:?}"); + assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, _)] if id == "livePaint.fill"), "{acts:?}"); + t.pointer(&cx1, &ev(PointerKind::Up, 75.0, 50.0)); // The fill left the document as it was: the map still fits it. t.pointer(&cx1, &ev(PointerKind::Move, 25.0, 50.0)); assert_eq!(t.cache.builds, 1, "a hover after a fill that changed nothing"); @@ -1745,8 +1780,9 @@ fn live_paint_tools_skip_hidden_faces() { let mut bucket = LivePaintBucketTool::default(); bucket.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); assert_eq!(part(&bucket.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0))); - let fill = Action::Exec("livePaint.fill".into(), json!({ "group": back.0, "point": [75.0, 50.0] })); - assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)), vec![fill]); + let fill = Action::Preview("livePaint.fill".into(), json!({ "group": back.0, "point": [75.0, 50.0] })); + assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)), vec![Action::Begin("Live Paint Bucket".into()), fill]); + bucket.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); let mut sel = LivePaintSelectionTool::default(); sel.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0)); assert_eq!(part(&sel.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0))); diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index c5b0f52327..13e98ec4ee 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -102,6 +102,7 @@ shown_when = [ "The Artboard tool inside an artboard.", "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", + "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", ] hotspot = "The centre." look = "A four-way move cursor." diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index d7d4bb85b4..0ac443c731 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -40,7 +40,7 @@ fn a_press_where_a_mask_hides_a_selected_object_drags_it() { #[test] fn direct_and_group_selection_pick_ruler_guides() { let (mut d, id) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(true, 100.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 100.0)); let (s, p) = (Selection::default(), paint()); let c = cx(&d, &s, &p); let down = |t: &mut DirectSelectionTool, y: f64| t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, y)); @@ -62,7 +62,7 @@ fn direct_and_group_selection_pick_ruler_guides() { #[test] fn a_cmd_shift_double_click_releases_the_guide_under_the_pointer() { let (mut d, id) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 300.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 300.0)); let Some(NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { panic!("the rectangle is a path") }; *guide = true; let (s, p) = (Selection::default(), paint()); @@ -848,7 +848,7 @@ fn crossed_segments_match_testing_a_path_for_each_segment() { #[test] fn marquee_selects_ruler_guides() { let (mut d, id) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 80.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 80.0)); let s = Selection::default(); let p = paint(); let cx = cx(&d, &s, &p); diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 32941c5f71..6f0b50d4b5 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -119,6 +119,13 @@ impl PointSnap { Self { targets } } + /// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the + /// window as targets ([`Targets::for_drawing`]), live text as Snap to Glyph asks. + pub fn drawn(cx: &ToolContext) -> Self { + let glyphs = (cx.snap_to_glyph && cx.smart_guides && cx.alignment_guides).then_some(cx.glyph_snap); + Self::new(cx, || Targets::for_drawing(cx.doc, &[], visible(cx), glyphs)) + } + /// Where `p` goes, and the guides showing why. pub fn snap(&self, cx: &ToolContext, p: Point) -> (Point, Vec) { self.snap_from(cx, p, None) diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index c50889d030..41b9f517ee 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -579,7 +579,7 @@ impl Targets { if cx.guides { self.rulers = cx .doc - .guides + .ruler_guides() .iter() .filter(|g| cx.doc.guide_shown(g)) .map(|g| Ruler { vertical: g.vertical, pos: g.pos, span: cx.doc.guide_span(g) }) diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index c34f9ab7de..a4f3bc49fd 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -442,9 +442,9 @@ fn drawn_points_land_on_intersections() { let id = d.alloc_id(); d.insert(Some(l), 1, Node::path(id, path, Appearance::default_art())).unwrap(); } - d.guides.push(vectorcraft_doc::Guide::new(true, 400.0)); - d.guides.push(vectorcraft_doc::Guide::new(false, 300.0)); - d.guides.push(vectorcraft_doc::Guide::new(false, 150.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 400.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 300.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 150.0)); let (s, p) = (Selection::default(), paint()); let c = ToolContext { guides: true, ..cx(&d, &s, &p) }; let t = Targets::for_drawing(&d, &[], None, None).styled(&c).with_rulers(&c); @@ -612,8 +612,8 @@ fn bisection_finds_what_a_scan_finds() { #[test] fn drawn_points_snap_to_ruler_guides_with_smart_guides_on() { let (mut d, _) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 313.0)); - d.guides.push(vectorcraft_doc::Guide::new(true, 331.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 313.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 331.0)); let (s, p) = (Selection::default(), paint()); let c = cx(&d, &s, &p); let mut snap = DrawSnap::default(); diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index ece5231bd2..9b53d2404c 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -109,6 +109,19 @@ impl PointerEvent { 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())) } + /// Checks the optional keys of a JSON pointer event (control channel, MCP): `pressure`, + /// `holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers, and `space` must be `doc` or + /// `screen`. A key that is absent or null keeps its default. + pub fn json_check(e: &Value) -> Result<(), String> { + let given = |k: &str| e.get(k).filter(|v| !v.is_null()); + if let Some(k) = ["pressure", "holdMs", "tiltX", "tiltY", "rotation"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) { + return Err(format!("`{k}` must be a number")); + } + if given("space").is_some_and(|v| !matches!(v.as_str(), Some("doc" | "screen"))) { + return Err("`space` must be doc or screen".to_owned()); + } + Ok(()) + } } #[cfg(test)] @@ -135,6 +148,27 @@ mod tests { assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}"); } } + + #[test] + fn json_check_refuses_pen_values_and_spaces_of_the_wrong_type() { + use serde_json::json; + for ok in [ + json!({}), + json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "space": "screen"}), + json!({"pressure": null, "space": null}), + json!({"space": "doc"}), + ] { + assert_eq!(PointerEvent::json_check(&ok), Ok(()), "{ok}"); + } + for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation"] { + for bad in [json!("1"), json!(true), json!([1])] { + assert_eq!(PointerEvent::json_check(&json!({k: bad})), Err(format!("`{k}` must be a number")), "{k}: {bad}"); + } + } + for bad in [json!("screeen"), json!(true), json!(1)] { + assert_eq!(PointerEvent::json_check(&json!({"space": bad})), Err("`space` must be doc or screen".to_owned()), "{bad}"); + } + } } /// Keys tools care about. diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index fe5a8b9215..c2f90d0bef 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -20,13 +20,22 @@ //! one. The distance shows next to the pointer in the document's units, the drag is previewed and //! kept as one undo step on release, and Escape cancels it. //! +//! The Move All widget: with one Objects on Path group selected whose objects have room to move +//! along its path, the same tools show a diamond beyond the group's first object, below it. +//! Dragging it along the path moves every object along it as far, keeping the distances between +//! them (`object.objectsOnPath.options` with `start`). On an open path, the widget shows only when +//! the distance from the first object to the last is shorter than the path, and the objects stop +//! at its ends; on a closed path they go on round across its first anchor. The first object's +//! distance along the path shows next to the pointer in the document's units, the drag is +//! previewed and kept as one undo step on release, and Escape cancels it. +//! //! Behavior: , //! . use serde_json::{Value, json}; use vectorcraft_doc::blend::Spine; -use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop}; -use vectorcraft_doc::{Document, NodeId, Selection}; +use vectorcraft_doc::objects_on_path::{CENTER, Member, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop}; +use vectorcraft_doc::{Document, Node, NodeId, Selection}; use vectorcraft_geom::{BezPath, Point, Vec2}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -51,6 +60,14 @@ pub const SPACE_HALF_PX: f32 = 3.5; /// How near (screen px) the pointer must be to hit the Space widget. const SPACE_HIT_PX: f64 = 6.0; +/// The Move All widget's center sits this far (screen px) beyond the first object, on the side its +/// bottom faces. +const MOVE_ALL_OFFSET_PX: f64 = 16.0; +/// Half the diagonal of the Move All widget's diamond (screen px), as the canvas draws it. +pub const MOVE_ALL_HALF_PX: f32 = 4.5; +/// How near (screen px) the pointer must be to hit the Move All widget. +const MOVE_ALL_HIT_PX: f64 = 6.0; + /// The Objects on Path group the widgets show for at `zoom` (screen px per document point), with /// its record, its children and its path: only when the selection is that one editable group, on /// a path with length, and no anchors are Direct-Selected. @@ -73,6 +90,30 @@ fn one_group<'a>( Some((*group, rec, children.as_slice(), path)) } +/// The direction the top of the object `m` faces: the -y direction of the frame it is drawn in +/// (the document's y axis points down), so a reflected or sheared frame turns it with the art's +/// top. A unit vector in the document's axes. +fn top(m: &Member) -> Vec2 { + let [_, _, a2, a3, _, _] = m.frame.as_coeffs(); + let len = a2.hypot(a3); + if len.is_finite() && len > 1e-12 { + Vec2::new(-a2 / len, -a3 / len) + } else { + let (sin, cos) = m.angle.sin_cos(); + Vec2::new(sin, -cos) + } +} + +/// The point `gap` (points) beyond the bounds of the object `m` (one of `children`), from its +/// attachment point `from` in the direction `dir`. `None` when it is not finite. +fn beside(doc: &Document, children: &[std::sync::Arc], m: &Member, from: Point, dir: Vec2, gap: f64) -> Option { + let b = children.iter().find(|c| c.id == m.id)?.geometric_bounds_with(&doc.symbol_boxes())?; + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; + let reach = corners.iter().map(|c| (*c - from).dot(dir)).fold(0.0, f64::max); + let at = from + dir * (reach + gap); + (at.x.is_finite() && at.y.is_finite() && from.x.is_finite() && from.y.is_finite()).then_some(at) +} + /// The Rotate All widget of a selected Objects on Path group. #[derive(Clone, Copy, Debug, PartialEq)] pub struct RotateAllWidget { @@ -93,23 +134,8 @@ impl RotateAllWidget { let (group, rec, children, path) = one_group(doc, selection, zoom)?; let first = rec.members.first()?; let (pivot, _) = stop(path, rec.members.len(), rec.spacing, rec.start, 0)?; - let art = children.iter().find(|c| c.id == first.id)?; - let b = art.geometric_bounds_with(&doc.symbol_boxes())?; - // The object's top is the -y direction of the frame it is drawn in (the document's y axis - // points down), so a reflected or sheared frame moves the widget with the art's top. - let [_, _, a2, a3, _, _] = first.frame.as_coeffs(); - let len = a2.hypot(a3); - let up = if len.is_finite() && len > 1e-12 { - Vec2::new(-a2 / len, -a3 / len) - } else { - let (sin, cos) = first.angle.sin_cos(); - Vec2::new(sin, -cos) - }; - let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; - let reach = corners.iter().map(|c| (*c - pivot).dot(up)).fold(0.0, f64::max); - let at = pivot + up * (reach + ROTATE_ALL_OFFSET_PX / zoom); - let finite = at.x.is_finite() && at.y.is_finite() && pivot.x.is_finite() && pivot.y.is_finite(); - finite.then_some(Self { group, pivot, at, rotate: rec.rotate }) + let at = beside(doc, children, first, pivot, top(first), ROTATE_ALL_OFFSET_PX / zoom)?; + Some(Self { group, pivot, at, rotate: rec.rotate }) } /// The widget of `cx` when `p` is within reach of it. @@ -394,6 +420,160 @@ impl SpaceDrag { } } +/// The Move All widget of a selected Objects on Path group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MoveAllWidget { + pub group: NodeId, + /// The first object's attachment point, in the document. + pub first: Point, + /// The widget's center in the document. + pub at: Point, + /// The length of the path (points). + pub len: f64, + /// Is the path closed? + pub closed: bool, + /// Where the first object attaches along the path (points from its first anchor), as drawn. + pub start: f64, + /// The farthest along an open path the first object can attach with the others still on it + /// (points); the path's length on a closed path. + pub most: f64, + /// The Space value a drag sets with the start: the distance between the objects as drawn, when + /// the saved value would draw them apart differently from another start (Auto, or a Space value + /// an open path is too short for). `None` keeps the saved value. + pub gap: Option, + /// The group's start, as saved. + pub saved: f64, +} + +impl MoveAllWidget { + /// The widget of the selection at `zoom` (screen px per document point): only when the + /// selection is one editable Objects on Path group with at least one object on a path with + /// length, no anchors are Direct-Selected, and the objects have room to move: on an open path, + /// the distance from the first object to the last is shorter than the path. It sits beyond the + /// first object's bounds, on the side its bottom faces. + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { + let (group, rec, children, path) = one_group(doc, selection, zoom)?; + let count = rec.members.len(); + let first = rec.members.first()?; + let (len, closed) = path_length(path)?; + let (start, gap) = layout(len, closed, count, rec.spacing, rec.start); + let most = if closed { len } else { len - gap * count.saturating_sub(1) as f64 }; + if !closed && (!most.is_finite() || most <= 1e-9) { + return None; + } + // On an open path, Auto and a Space value the path is too short for draw the objects apart + // by what is left of the path after the start, so another start would change the distance. + let keeps = closed || count < 2 || rec.spacing.is_some_and(|g| (g - gap).abs() < 1e-9); + let (at_first, _) = stop(path, count, rec.spacing, rec.start, 0)?; + let at = beside(doc, children, first, at_first, -top(first), MOVE_ALL_OFFSET_PX / zoom)?; + let finite = [len, start, most, rec.start].iter().all(|v| v.is_finite()); + finite.then_some(Self { group, first: at_first, at, len, closed, start, most, gap: (!keeps).then_some(gap), saved: rec.start }) + } + + /// The widget of `cx` when `p` is within reach of it. + fn at_point(cx: &ToolContext, p: Point) -> Option { + Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(MOVE_ALL_HIT_PX)) + } +} + +/// Is `p` over the Move All widget? +pub fn over_move_all(cx: &ToolContext, p: Point) -> bool { + MoveAllWidget::at_point(cx, p).is_some() +} + +/// Dragging the Move All widget: the distance the pointer moves along the path moves every object +/// along it as far, keeping the distances between them. On an open path the objects stop at its +/// ends, and on a closed path they go on round across its first anchor. +#[derive(Clone, Debug)] +pub struct MoveAllDrag { + widget: MoveAllWidget, + start: Point, + began: bool, + /// The distance along the path to the point nearest the pointer at the last drag (points). + last: f64, + /// Where the drag puts the first object along the path (points from its first anchor). + to: f64, + at: Point, +} + +impl MoveAllDrag { + /// The drag has left the click: the objects are moving. + pub fn adjusting(&self) -> bool { + self.began + } + + /// Start a drag when the press `ev` is on the Move All widget. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let widget = MoveAllWidget::at_point(cx, ev.pos)?; + let (_, last) = group_spine(cx.doc, widget.group)?.nearest(ev.pos, Some(widget.start))?; + last.is_finite().then_some(Self { widget, start: ev.pos, began: false, last, to: widget.start, at: ev.pos }) + } + + /// The pointer moved to `p`: move the first object as far along the path as the point nearest + /// the pointer moved, the shorter way round a closed path. On an open path it stays between + /// the first anchor and [`MoveAllWidget::most`], so moving back from beyond an end moves the + /// objects back at once. + fn follow(&mut self, doc: &Document, p: Point) { + let w = &self.widget; + let Some((_, t)) = group_spine(doc, w.group).and_then(|s| s.nearest(p, Some(self.last))) else { return }; + let step = if w.closed { (t - self.last + w.len / 2.0).rem_euclid(w.len) - w.len / 2.0 } else { t - self.last }; + if !t.is_finite() || !step.is_finite() { + return; + } + self.last = t; + self.to = if w.closed { + let s = (self.to + step).rem_euclid(w.len); + if s.is_finite() && s < w.len { s } else { 0.0 } + } else { + (self.to + step).clamp(0.0, w.most) + }; + } + + /// The pointer moved to `p`. + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if !self.began { + if p.distance(self.start) < cx.tol(3.0) { + return out; + } + self.began = true; + out.push(Action::Begin("Objects on Path Options".into())); + } + self.follow(cx.doc, p); + self.at = p; + let w = &self.widget; + // Where the objects stay as they are drawn, the group keeps its saved values. + let params = if (self.to - w.start).abs() < 1e-9 { + json!({ "ids": [w.group.0], "start": w.saved }) + } else if let Some(gap) = w.gap { + json!({ "ids": [w.group.0], "start": self.to, "spacing": gap }) + } else { + json!({ "ids": [w.group.0], "start": self.to }) + }; + out.push(Action::Preview("object.objectsOnPath.options".into(), params)); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + /// The first object's distance along the path next to the pointer, in the document's units. + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.began || !cx.measurement_labels { + return vec![]; + } + vec![Overlay::Measure { p: self.at, text: cx.len(self.to) }] + } +} + +/// The path of the Objects on Path group `g` of `doc`, to measure along. +fn group_spine(doc: &Document, g: NodeId) -> Option { + let n = doc.node(g)?; + let rec = n.extras().objects_on_path.as_deref()?; + Spine::new(attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?) +} + /// The path a click at `p` attaches the selected objects to: the path object hit there, when it can /// take objects, is in no Objects on Path group, is not a clipping path or part of a compound path, /// blend, envelope, repeat or Intertwine group ([`vectorcraft_doc::objects_on_path::held`]), and @@ -420,6 +600,8 @@ pub struct ObjectsOnPathTool { rotating: Option, /// The Space widget drag, while the button is down after a press on the widget. spacing: Option, + /// The Move All widget drag, while the button is down after a press on the widget. + moving: Option, /// The reference point of each object attached next (0-8, row by row from the top left). pivot: u8, /// The angle of each object attached next, in degrees counter-clockwise from upright on the path. @@ -428,7 +610,7 @@ pub struct ObjectsOnPathTool { impl Default for ObjectsOnPathTool { fn default() -> Self { - Self { hover: None, press: None, rotating: None, spacing: None, pivot: CENTER, rotate: 0.0 } + Self { hover: None, press: None, rotating: None, spacing: None, moving: None, pivot: CENTER, rotate: 0.0 } } } @@ -453,9 +635,16 @@ impl Tool for ObjectsOnPathTool { _ => vec![], }; } + if let Some(d) = &mut self.moving { + return match ev.kind { + PointerKind::Drag => d.drag(cx, p), + PointerKind::Up => self.moving.take().map(MoveAllDrag::finish).unwrap_or_default(), + _ => vec![], + }; + } match ev.kind { PointerKind::Move => { - self.hover = if over_rotate_all(cx, p) || over_space(cx, p) { None } else { target(cx, p) }; + self.hover = if over_rotate_all(cx, p) || over_space(cx, p) || over_move_all(cx, p) { None } else { target(cx, p) }; vec![] } PointerKind::Down => { @@ -469,6 +658,11 @@ impl Tool for ObjectsOnPathTool { self.hover = None; return vec![]; } + if let Some(d) = MoveAllDrag::hit(cx, ev) { + self.moving = Some(d); + self.hover = None; + return vec![]; + } self.press = Some(p); vec![] } @@ -492,14 +686,20 @@ impl Tool for ObjectsOnPathTool { if let Some(d) = &self.spacing { o.extend(d.overlays(cx)); } + if let Some(d) = &self.moving { + o.extend(d.overlays(cx)); + } o } fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { - if self.rotating.is_some() || (self.spacing.is_none() && over_rotate_all(cx, p)) { + let idle = self.spacing.is_none() && self.moving.is_none(); + if self.rotating.is_some() || (idle && over_rotate_all(cx, p)) { Cursor::Rotate - } else if self.spacing.is_some() || over_space(cx, p) { + } else if self.spacing.is_some() || (self.moving.is_none() && over_space(cx, p)) { Cursor::ArrowHollow + } else if self.moving.is_some() || over_move_all(cx, p) { + Cursor::Move } else if target(cx, p).is_some() { Cursor::ObjectsOnPath } else { @@ -508,14 +708,16 @@ impl Tool for ObjectsOnPathTool { } /// Escape while the button is down cancels the click, so the release attaches nothing, or the - /// Rotate All or Space drag, so the objects go back to the Rotate or Space they had. + /// Rotate All, Space or Move All drag, so the objects go back to the Rotate, Space or place + /// they had. fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape { self.press = None; self.hover = None; let rotated = self.rotating.take().is_some_and(|d| d.adjusting()); let spaced = self.spacing.take().is_some_and(|d| d.adjusting()); - if rotated || spaced { + let moved = self.moving.take().is_some_and(|d| d.adjusting()); + if rotated || spaced || moved { return vec![Action::Cancel]; } } @@ -545,11 +747,13 @@ impl Tool for ObjectsOnPathTool { } fn busy(&self) -> bool { - self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() + self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() } fn transforming(&self) -> bool { - self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) || self.spacing.as_ref().is_some_and(SpaceDrag::adjusting) + self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) + || self.spacing.as_ref().is_some_and(SpaceDrag::adjusting) + || self.moving.as_ref().is_some_and(MoveAllDrag::adjusting) } } @@ -1056,6 +1260,196 @@ mod tests { assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 1000.0, 100.0))), Some((400.0, 0.0)), "half way round at most"); } + /// The start a Move All drag's last action previews, to 1/1,000,000 pt, and whether it also + /// sets a Space value. + fn moved(acts: &[Action]) -> Option<(f64, Option)> { + let round = |v: f64| (v * 1e6).round() / 1e6 + 0.0; + match acts.last() { + Some(Action::Preview(cmd, p)) if cmd == "object.objectsOnPath.options" && p.get("rotate").is_none() => { + Some((round(p["start"].as_f64()?), p.get("spacing").and_then(Value::as_f64).map(round))) + } + _ => None, + } + } + + /// A document holding an Objects on Path group of one 20 × 20 square on the line from (0, 300) + /// to (400, 300), and a selection of the group. + fn single_doc() -> (Document, Selection) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (line, a, g) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let line = Node::path(line, shapes::line(Point::new(0.0, 300.0), Point::new(400.0, 300.0)), Appearance::default_art()); + let a = Node::path(a, shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), Appearance::default_art()); + let rec = vectorcraft_doc::objects_on_path::ObjectsOnPath::new(line.id, &[&a], CENTER, 0.0); + let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a)], clip: false }); + group.extras_mut().objects_on_path = Some(Box::new(rec)); + vectorcraft_doc::objects_on_path::place(&mut group, &Document::new(1.0, 1.0).symbol_boxes()); + d.insert(Some(l), 0, group).unwrap(); + let mut sel = Selection::default(); + sel.set([g]); + (d, sel) + } + + #[test] + fn the_move_all_widget_sits_below_the_first_object_when_the_objects_have_room() { + // Space 100 from 50: the first square spans 290 to 310 down the page, and the widget is + // 16 px below its bottom. The two objects take 100 pt of the 400 pt path, so the first + // one can go from 0 to 300 along it. + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert_eq!(w.group, g); + assert!(near(w.first, Point::new(50.0, 300.0)) && near(w.at, Point::new(50.0, 326.0)), "{w:?}"); + assert!(w.start == 50.0 && (w.most - 300.0).abs() < 1e-9 && w.gap.is_none() && !w.closed, "{w:?}"); + assert!(near(MoveAllWidget::of(&d, &sel, 2.0).unwrap().at, Point::new(50.0, 318.0))); + // Auto spreads the objects from one end of an open path to the other: no room to move. + let (d, _, sel) = group_doc(0.0); + assert!(MoveAllWidget::of(&d, &sel, 1.0).is_none(), "Auto"); + // Nor with a Space value that reaches the end. + let (d, _, sel) = spaced_doc(Some(400.0), 0.0); + assert!(MoveAllWidget::of(&d, &sel, 1.0).is_none(), "the whole path"); + // On a closed path the objects always have room, Auto included. + let (d, sel) = path_doc(shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), None); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(w.closed && (w.most - 800.0).abs() < 1e-9 && w.gap.is_none(), "{w:?}"); + // One object on an open path can move along all of it. + let (d, sel) = single_doc(); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(w.start == 0.0 && (w.most - 400.0).abs() < 1e-9 && w.gap.is_none(), "{w:?}"); + // No widget for an object in the group, or for a locked group. + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let children: Vec = d.node(sel.objects[0]).and_then(|n| n.children()).unwrap().iter().map(|c| c.id).collect(); + let mut one = Selection::default(); + one.set([children[1]]); + assert!(MoveAllWidget::of(&d, &one, 1.0).is_none()); + let (mut d, g, sel) = spaced_doc(Some(100.0), 50.0); + if let Some(n) = d.node_mut(g) { + n.locked = true; + } + assert!(MoveAllWidget::of(&d, &sel, 1.0).is_none()); + } + + /// Dragging the widget 80 pt along the path moves both objects 80 pt, keeping the Space, with + /// the Selection tool and with the Objects on Path tool, previewed while dragging and kept as + /// one undo step on release. On an open path the objects stop at its ends, and coming back + /// moves them back at once. + #[test] + fn dragging_the_move_all_widget_moves_every_object_along_the_path() { + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at; + let tools: [Box; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())]; + for mut t in tools { + let id = t.id(); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::Move, "{id}"); + assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty(), "{id}"); + let a = t.pointer(&c, &ev(PointerKind::Drag, at.x + 80.0, at.y + 10.0)); + assert_eq!(a.first(), Some(&Action::Begin("Objects on Path Options".into())), "{id}"); + assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["ids"] == json!([g.0])), "{a:?}"); + assert_eq!(moved(&a), Some((130.0, None)), "{id}: only the start changes"); + assert!(t.transforming() && t.cursor(&c, at, Mods::default()) == Cursor::Move, "{id}"); + let label = c.len(130.0); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == label)), "{id}"); + // Shift and Alt change nothing. + let mods = Mods { shift: true, alt: true, ..Mods::default() }; + assert_eq!(moved(&t.pointer(&c, &PointerEvent { mods, ..ev(PointerKind::Drag, at.x + 90.0, at.y) })), Some((140.0, None)), "{id}"); + // No further than where the last object reaches the end, and back at once. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 900.0, at.y))), Some((300.0, None)), "{id}"); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 880.0, at.y))), Some((280.0, None)), "{id}"); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, None)), "{id}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert!(!t.busy(), "{id}"); + // A click on the widget that does not move changes nothing. + assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at.x + 1.0, at.y)).is_empty(), "{id}"); + } + } + + /// Where the saved Space would draw the objects apart differently from another start (Auto, + /// or a value the path is too short for), the drag sets the distance as drawn with the start; + /// back where it began, the group keeps its saved values. + #[test] + fn a_move_all_drag_keeps_the_distance_the_objects_are_drawn_at() { + for (spacing, what) in [(Some(1000.0), "a Space value too large for the path"), (None, "Auto")] { + let (d, _, sel) = spaced_doc(spacing, 100.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!((w.most - 100.0).abs() < 1e-9 && w.gap == Some(300.0), "{what}: {w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x - 40.0, w.at.y))), Some((60.0, Some(300.0))), "{what}"); + let a = t.pointer(&c, &ev(PointerKind::Drag, w.at.x, w.at.y)); + assert_eq!(moved(&a), Some((100.0, None)), "{what}: back where it began"); + } + } + + /// On an L-shaped path the drag counts the distance along the path, round the corner. + #[test] + fn a_move_all_drag_follows_the_path_round_a_corner() { + let (d, sel) = corner_doc(Some(100.0)); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.at, Point::new(0.0, 326.0)) && (w.most - 600.0).abs() < 1e-9, "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 200.0, 326.0))), Some((200.0, None))); + // Up the upright leg, 200 pt from the corner. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 426.0, 100.0))), Some((600.0, None)), "no further than the end"); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 426.0, 200.0))), Some((500.0, None))); + } + + /// On a closed path the objects go on round across the first anchor, both ways. + #[test] + fn a_move_all_drag_on_a_closed_path_goes_round_across_the_first_anchor() { + // The square's outline is 800 pt round, from (100, 100) to the right. + let (d, sel) = path_doc(shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), Some(100.0)); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.first, Point::new(100.0, 100.0)) && near(w.at, Point::new(100.0, 126.0)), "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + // Down the left side, back before the first anchor. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 100.0, 150.0))), Some((776.0, None))); + // Round the corner onto the top, ahead of it again. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 130.0, 100.0))), Some((56.0, None))); + } + + /// One object moves along all of an open path. + #[test] + fn a_move_all_drag_moves_a_single_object_to_the_end() { + let (d, sel) = single_doc(); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + let mut t = crate::select::SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x + 150.0, w.at.y))), Some((150.0, None))); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x + 600.0, w.at.y))), Some((400.0, None))); + } + + /// Escape during a Move All drag cancels it: the readout is removed, and the release keeps + /// nothing. + #[test] + fn escape_cancels_a_move_all_drag() { + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at; + let tools: [Box; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())]; + for mut t in tools { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + assert!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 40.0, at.y))).is_some()); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{}", t.id()); + assert!(!t.busy() && !t.transforming(), "{}", t.id()); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. })), "{}", t.id()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, at.x, at.y)).is_empty(), "{}", t.id()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)).is_empty(), "{}: the release keeps nothing", t.id()); + } + } + /// Escape during a Space drag cancels it: the readout is removed, and the release keeps /// nothing. #[test] diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index b70a160d8a..31aabfb38f 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -3,7 +3,11 @@ //! Click adds a corner anchor; click-drag adds a smooth anchor with symmetric handles (Alt breaks //! them: the incoming handle stays where it was when Alt went down and only the outgoing one //! follows the pointer; Space held moves the anchor, handles and all); Shift constrains to 45°. -//! A press on the first anchor closes the path, the drag shaping the closing curve. Clicking the +//! A press on the first anchor closes the path, the drag shaping the closing curve: the anchor's +//! incoming handle mirrors the pointer (a click leaves it retracted and the anchor a corner, so the +//! closing segment comes in straight). Its outgoing handle stays where it is on a corner, so the first segment keeps its +//! shape, and on a smooth anchor turns to stay in line at its own length; Alt makes the anchor a +//! corner, leaving the outgoing handle where it was when Alt went down. Clicking the //! last one retracts its outgoing handle, so the next segment leaves it as a corner; dragging from //! it pulls a new one out on its own. //! Alt held over a handle end, an anchor or a segment of a selected path (the one being drawn too) @@ -27,7 +31,7 @@ use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_geom::{BezPath, Point, Vec2}; +use vectorcraft_geom::{Anchor, BezPath, Point, Vec2}; use crate::direct::hit_handle; use crate::draw2::{AnchorTool, editable_paths, shown_paths}; @@ -47,6 +51,9 @@ pub struct PenTool { hover: Option, /// The incoming handle of the anchor being dragged out, as last previewed. in_h: Point, + /// The first anchor, as it was when a press on it began closing the path, and its outgoing + /// handle as the closing drag last left it: Alt pressed mid-drag keeps the handle there. + first: Option<(Anchor, Point)>, /// The pointer at the last button-down or drag: Space held moves the anchor as far as it moves. last: Point, /// Where the button went down: the drag threshold is measured from it. @@ -289,9 +296,7 @@ impl Tool for PenTool { // Pick at the raw pointer before snapping or constraining a new point. // A one-anchor path doesn't close on itself: its anchor is the last one too. if picked == Some(Endpoint::First) { - self.drag = Some(Place { at: first, path: Some(id), subpath: Some(si), closing: true }); - let params = json!({"id": id.0, "subpath": si}); - return vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)]; + return self.begin_close(cx, id, si, first); } // Alt uses Anchor Point behavior at the terminal anchor too. if let Some(acts) = self.alt_convert(cx, ev) { @@ -307,9 +312,7 @@ impl Tool for PenTool { if raw_other.is_none() && p != ev.pos { let snapped = pick_endpoint(closing_end, last, p, tol, Endpoint::First); if snapped == Some(Endpoint::First) { - self.drag = Some(Place { at: first, path: Some(id), subpath: Some(si), closing: true }); - let params = json!({"id": id.0, "subpath": si}); - return vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)]; + return self.begin_close(cx, id, si, first); } if snapped == Some(Endpoint::Last) && let Some((si, ai)) = end @@ -410,11 +413,7 @@ impl Tool for PenTool { )]; }; if closing { - let mut params = json!({"id": id.0, "in": [2.0 * a.x - out_h.x, 2.0 * a.y - out_h.y], "independent": alt}); - if let Some(si) = subpath { - params["subpath"] = json!(si); - } - return vec![Action::Preview("path.close".into(), params)]; + return vec![close_drag(id, subpath, a - (out_h - a), alt, self.first.as_mut())]; } // Alt pressed mid-drag keeps the curve already shaped into the anchor: only the // outgoing handle follows. Held from the start, the incoming handle stays retracted. @@ -436,6 +435,7 @@ impl Tool for PenTool { } let Some(place) = self.drag.take() else { return vec![] }; if place.closing { + self.first = None; self.stop(); } vec![Action::Commit] @@ -453,6 +453,7 @@ impl Tool for PenTool { /// close it was making: the path being drawn goes on with the next click. fn drop_press(&mut self, _cx: &ToolContext) -> Vec { self.drag = None; + self.first = None; self.handle = None; self.convert = None; self.snap.clear(); @@ -464,6 +465,7 @@ impl Tool for PenTool { self.stop(); self.snap.clear(); let placing = self.drag.take().is_some(); + self.first = None; let handling = self.handle.take().is_some(); // Finish the preview as it stands; clearing state alone leaves its transaction open. let mut acts = self.convert.take().map(|mut t| t.deactivate(cx)).unwrap_or_default(); @@ -577,6 +579,16 @@ impl PenTool { (self.drawing, self.path, self.subpath) = (false, None, None); } + /// A press on the first anchor (at `at`) of subpath `si` of the path being drawn: close it, the + /// anchor a corner with its incoming handle retracted until a drag pulls it out, as a click on + /// the last anchor retracts its outgoing one ([`set_out_handle`]). + fn begin_close(&mut self, cx: &ToolContext, id: NodeId, si: usize, at: Point) -> Vec { + self.drag = Some(Place { at, path: Some(id), subpath: Some(si), closing: true }); + self.first = first_anchor(cx, id, si).map(|a| (a, a.h_out)); + let params = json!({"id": id.0, "subpath": si, "in": [at.x, at.y], "independent": true}); + vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)] + } + /// Hand an Alt press on a selected path's handle, anchor or segment to the Anchor Point tool. fn alt_convert(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { if !alt_converts(cx, ev.pos, ev.mods) { @@ -592,6 +604,32 @@ impl PenTool { } } +/// The first anchor of subpath `si` of path `id`. +pub(crate) fn first_anchor(cx: &ToolContext, id: NodeId, si: usize) -> Option { + cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.first().copied() +} + +/// The preview of a closing drag that puts the first anchor's incoming handle at `in_h`. `first` +/// holds that anchor as it was when the press began closing the path, and its outgoing handle as +/// the drag last left it: a smooth anchor turns that handle to stay in line, and Alt (`alt`), which +/// makes the anchor a corner, keeps it there. +pub(crate) fn close_drag(id: NodeId, subpath: Option, in_h: Point, alt: bool, first: Option<&mut (Anchor, Point)>) -> Action { + let mut params = json!({"id": id.0, "in": [in_h.x, in_h.y], "independent": alt}); + if let Some((anchor, out)) = first { + if alt { + params["out"] = json!([out.x, out.y]); + } else { + let mut a = *anchor; + a.set_handle(false, in_h, false); + *out = a.h_out; + } + } + if let Some(si) = subpath { + params["subpath"] = json!(si); + } + Action::Preview("path.close".into(), params) +} + /// Go on drawing subpath `si` of open path `id` from its last anchor, or from its first /// (`at_first`, the subpath reversed so that it is the last): the path (its compound path) is /// selected. diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index 340a2ea6ed..984f34646a 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -2,6 +2,13 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; +/// What a press on the first anchor, at `first`, of subpath 0 of `id` does: the path closes with +/// the anchor a corner with its incoming handle retracted. +fn close_press(id: NodeId, first: Point) -> Vec { + let params = json!({"id": id.0, "subpath": 0, "in": [first.x, first.y], "independent": true}); + vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)] +} + #[test] fn press_inside_drag_threshold_places_a_corner() { let (d, s) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default()); @@ -131,10 +138,7 @@ fn snapped_first_endpoint_closes_active_path_after_raw_miss() { assert!(open_end_at(&cx, raw, tol, Some((id, 0))).is_none()); assert!(open_end_at(&cx, first, tol, Some((id, 0))).is_none()); - assert_eq!( - pen.pointer(&cx, &PointerEvent::new(PointerKind::Down, raw.x, raw.y)), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(pen.pointer(&cx, &PointerEvent::new(PointerKind::Down, raw.x, raw.y)), close_press(id, first)); let place = pen.drag.unwrap(); assert!(place.closing); assert_eq!((place.path, place.at), (Some(id), first)); @@ -349,10 +353,7 @@ fn terminal_anchor_conversion_precedes_grid_snapping() { assert_eq!(t.cursor(&cx, Point::new(63.0, 303.0), Mods::default()), Cursor::PenContinue); assert!(click(&mut t, &cx, 63.0, 303.0, Mods::default()).is_empty()); assert_eq!(t.active(&cx).map(|a| a.0), Some(id)); - assert_eq!( - t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 13.0, 303.0)), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 13.0, 303.0)), close_press(id, Point::new(13.0, 303.0))); } #[test] @@ -401,7 +402,7 @@ fn overlapping_endpoint_tolerances_pick_the_nearest_end() { let cursor = if first_end { Cursor::PenClose } else { Cursor::PenConvert }; let actual_cursor = pen.cursor(&cx, at, mods); let expected = if first_end { - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] + close_press(id, first) } else { vec![Action::Begin("Convert Anchor Point".into()), set_out(id, 1, last.x, last.y)] }; @@ -459,10 +460,7 @@ fn coincident_endpoints_keep_the_prior_tie_choice() { let cx = ToolContext { zoom, smart_guides: false, snap_to_point: false, ..cx(&d, &selection, &paint) }; let mut drawing = PenTool { drawing: true, ..PenTool::default() }; assert_eq!(drawing.cursor(&cx, at, Mods::default()), Cursor::PenClose); - assert_eq!( - click(&mut drawing, &cx, at.x, at.y, Mods::default()), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(click(&mut drawing, &cx, at.x, at.y, Mods::default()), close_press(id, at)); let mut resuming = PenTool::default(); assert_eq!(resuming.cursor(&cx, at, Mods::default()), Cursor::PenContinue); assert!(click(&mut resuming, &cx, at.x, at.y, Mods::default()).is_empty()); @@ -516,10 +514,7 @@ fn enlarged_anchor_radius_is_used_for_endpoints_and_alt_conversion() { let mut closing = PenTool { drawing: true, ..PenTool::default() }; let first = Point::new(10.0 - 6.0 / zoom, 300.0); assert_eq!(closing.cursor(&cx, first, Mods::default()), Cursor::PenClose); - assert_eq!( - click(&mut closing, &cx, first.x, first.y, Mods::default()), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(click(&mut closing, &cx, first.x, first.y, Mods::default()), close_press(id, Point::new(10.0, 300.0))); let mut alt_pen = PenTool { drawing: true, ..PenTool::default() }; let alt = Mods { alt: true, ..Mods::default() }; assert!(alt_pen.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(alt)).is_empty()); @@ -577,7 +572,8 @@ fn ending_during_a_pen_gesture_commits_and_clears_it() { /// #501: a press on the first anchor closes the path, however far the drag then goes: the /// closing preview leaves the path closed (so not one the pen extends), and each move still -/// previews the close with symmetric handles (Alt breaks them), released as a close. +/// previews the close with the incoming handle mirroring the pointer (Alt keeps the outgoing one +/// where it is), released as a close. #[test] fn a_drag_from_the_first_anchor_always_closes() { let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)]; @@ -585,22 +581,53 @@ fn a_drag_from_the_first_anchor_always_closes() { let p = paint(); let mut t = PenTool { drawing: true, ..PenTool::default() }; let a = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 101.0, 301.0)); - assert_eq!(a, vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))]); + assert_eq!(a, close_press(id, pts[0])); // What the tool sees once the preview applied: the path closed. d.node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].closed = true; let c = cx(&d, &s, &p); - let close = |x: f64, y: f64, alt: bool| { - vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [200.0 - x, 600.0 - y], "independent": alt, "subpath": 0}))] + let close = |x: f64, y: f64| { + vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [200.0 - x, 600.0 - y], "independent": false, "subpath": 0}))] }; for (x, y) in [(105.0, 290.0), (130.0, 260.0), (160.0, 240.0)] { - assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x, y)), close(x, y, false), "at ({x}, {y})"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x, y)), close(x, y), "at ({x}, {y})"); } let alt = Mods { alt: true, ..Mods::default() }; - assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 250.0).with_mods(alt)), close(170.0, 250.0, true)); + let alt_close = json!({"id": id.0, "in": [30.0, 350.0], "out": [100.0, 300.0], "independent": true, "subpath": 0}); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 250.0).with_mods(alt)), + vec![Action::Preview("path.close".into(), alt_close)] + ); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 250.0)), vec![Action::Commit]); assert!(!t.busy() && t.active(&c).is_none(), "the path is done"); } +/// #6634: on a smooth first anchor the closing drag turns the outgoing handle in line with the +/// incoming one; Alt pressed mid-drag sends the outgoing handle where the drag had turned it. +#[test] +fn alt_mid_close_keeps_the_turned_outgoing_handle() { + use vectorcraft_geom::{Anchor, SubPath}; + let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))]; + let (mut d, id, s) = drawing(SubPath { anchors, closed: false }); + let p = paint(); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0))); + d.node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].closed = true; + let c = cx(&d, &s, &p); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 100.0, 200.0)), + vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [100.0, 400.0], "independent": false, "subpath": 0}))] + ); + let alt = Mods { alt: true, ..Mods::default() }; + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 200.0).with_mods(alt)), + vec![Action::Preview( + "path.close".into(), + json!({"id": id.0, "in": [70.0, 400.0], "out": [100.0, 250.0], "independent": true, "subpath": 0}) + )] + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 200.0)), vec![Action::Commit]); +} + #[test] fn a_one_anchor_path_does_not_close_on_itself() { let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0)], false)); diff --git a/crates/tools/src/rulerguide.rs b/crates/tools/src/rulerguide.rs index 3297769382..a90770d3fb 100644 --- a/crates/tools/src/rulerguide.rs +++ b/crates/tools/src/rulerguide.rs @@ -9,30 +9,38 @@ //! ruler's ticks, else to whole pixels, the grid, with Smart Guides the art's and the artboards' //! edges, centres and anchors, or with Snap to Point the anchors. Dropped off the canvas onto its //! ruler, a moved guide is deleted. Hidden or locked guides (View › Guides), and guides on a hidden -//! or locked layer, can't be picked. +//! or locked layer, can't be picked. The rulers' origin, dragged out of their corner +//! ([`OriginDrag`]), snaps as a drawn point does. use serde_json::json; +use vectorcraft_doc::{Guide, NodeId}; use vectorcraft_geom::{Point, Rect}; -use crate::guides::Targets; +use crate::guides::{PointSnap, Targets}; use crate::{Action, Cursor, Overlay, PointerEvent, PointerKind, ToolContext}; -/// The ruler guide under `p`: the nearest within the selection tolerance (the newest of equals). +/// The ruler guide under `p`, by its index in `guide.list`: the nearest within the selection +/// tolerance (the newest of equals). pub fn guide_at(cx: &ToolContext, p: Point) -> Option { + guide_under(cx, p).map(|(i, _)| i) +} + +/// [`guide_at`], with the guide. +fn guide_under(cx: &ToolContext, p: Point) -> Option<(usize, Guide)> { if !cx.guides { return None; } let tol = cx.pick_tol(); let off = |pos: f64, vertical: bool| (if vertical { p.x } else { p.y } - pos).abs(); cx.doc - .guides - .iter() + .ruler_guides() + .into_iter() .enumerate() .filter(|(_, g)| cx.doc.guide_editable(g) && cx.doc.guide_passes(g, p, tol)) - .map(|(i, g)| (i, off(g.pos, g.vertical))) - .filter(|(_, d)| *d <= tol) + .map(|(i, g)| (i, off(g.pos, g.vertical), g)) + .filter(|(_, d, _)| *d <= tol) .min_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0))) - .map(|(i, _)| i) + .map(|(i, _, g)| (i, g)) } /// What a selection tool's marquee `r` does to the ruler guides, after its action selecting the @@ -42,19 +50,20 @@ pub fn guide_at(cx: &ToolContext, p: Point) -> Option { pub fn marquee_select(cx: &ToolContext, r: Rect, enclosed: bool) -> Option { let mut guides = guides_in_rect(cx, r); if enclosed { - guides.retain(|i| cx.doc.guides.get(*i).is_some_and(|g| guide_inside(cx, r, g))); + guides.retain(|(_, g)| guide_inside(cx, r, g)); } + let guides: Vec = guides.into_iter().map(|(i, _)| i).collect(); (!guides.is_empty()).then(|| Action::Exec("guide.select".into(), json!({ "indexes": guides, "toggle": true }))) } -/// The editable ruler guides intersecting marquee rectangle `r`. -fn guides_in_rect(cx: &ToolContext, r: Rect) -> Vec { +/// The editable ruler guides intersecting marquee rectangle `r`, with their `guide.list` indexes. +fn guides_in_rect(cx: &ToolContext, r: Rect) -> Vec<(usize, Guide)> { if !cx.guides { return vec![]; } cx.doc - .guides - .iter() + .ruler_guides() + .into_iter() .enumerate() .filter(|(_, g)| cx.doc.guide_editable(g)) .filter(|(_, g)| { @@ -64,14 +73,13 @@ fn guides_in_rect(cx: &ToolContext, r: Rect) -> Vec { r.min_y() <= g.pos && g.pos <= r.max_y() && cx.doc.guide_span(g).is_none_or(|(x0, x1)| r.max_x() >= x0 && r.min_x() <= x1) } }) - .map(|(i, _)| i) .collect() } /// Does ruler guide `g`, crossed by marquee `r`, run along its line within the marquee? An artboard /// guide does when the marquee spans its artboard; a canvas guide runs across the whole canvas and /// never does. -fn guide_inside(cx: &ToolContext, r: Rect, g: &vectorcraft_doc::Guide) -> bool { +fn guide_inside(cx: &ToolContext, r: Rect, g: &Guide) -> bool { let Some((a, b)) = cx.doc.guide_span(g) else { return false }; let (lo, hi) = if g.vertical { (r.min_y(), r.max_y()) } else { (r.min_x(), r.max_x()) }; lo <= a.min(b) && a.max(b) <= hi @@ -85,6 +93,8 @@ fn guide_cursor(vertical: bool) -> Cursor { #[derive(Clone, Copy, Debug)] struct Drag { index: usize, + /// The guide's node. + id: NodeId, vertical: bool, /// Where the guide was, and where it is now (x of a vertical guide, y of a horizontal one). from: f64, @@ -238,6 +248,39 @@ impl NewGuide { } } +/// The rulers' origin dragged out of the box where they meet, with any tool: it snaps as a drawn +/// point does ([`PointSnap::drawn`]), with Smart Guides onto the anchors, centres, edges and paths +/// of the art and the artboards or into line with them, with Snap to Point onto the anchors and +/// along the ruler guides, else onto whole pixels or the grid. The targets are gathered when the +/// drag begins. It changes nothing: the origin is set where the button is released. +pub struct OriginDrag { + snap: PointSnap, + /// The guides showing what the origin snapped to. + guides: Vec, +} + +impl OriginDrag { + pub fn new(cx: &ToolContext) -> Self { + Self { snap: PointSnap::drawn(cx), guides: vec![] } + } + + /// Where the origin goes with the pointer at `p` (none off the canvas). + pub fn pointer(&mut self, cx: &ToolContext, p: Option) -> Option { + let Some(p) = p else { + self.guides.clear(); + return None; + }; + let (at, guides) = self.snap.snap(cx, p); + self.guides = guides; + Some(at) + } + + /// The guides showing what the origin snapped to. + pub fn overlays(&self) -> Vec { + self.guides.clone() + } +} + /// A selection tool's ruler-guide handling: [`Self::press`] on a press, [`Self::pointer`] for /// the rest of the gesture. #[derive(Default)] @@ -262,11 +305,12 @@ impl GuideEdit { /// A press `ev` on a ruler guide: it gets selected and the drag starts. None (and nothing /// done) when no guide is there. pub fn press(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { - let index = guide_at(cx, ev.pos)?; - let g = cx.doc.guides.get(index)?; - let (shift, selected) = (ev.mods.shift, cx.selection.guides.contains(&index)); + let (index, g) = guide_under(cx, ev.pos)?; + let id = g.id?; + let (shift, selected) = (ev.mods.shift, cx.selection.guides.contains(&id)); self.drag = Some(Drag { index, + id, vertical: g.vertical, from: g.pos, at: g.pos, @@ -307,7 +351,7 @@ impl GuideEdit { vec![Action::Commit] } else if d.deselect { vec![Action::Exec("guide.select".into(), json!({ "indexes": [d.index], "toggle": true }))] - } else if d.key && cx.selection.key_guide == Some(d.index) { + } else if d.key && cx.selection.key_guide == Some(d.id) { // A click on the key guide again: no key. vec![Action::Exec("select.key".into(), json!({}))] } else if d.key { @@ -349,7 +393,7 @@ impl GuideEdit { if let Some(d) = &self.drag { return Some(guide_cursor(d.vertical).turned(cx.view_angle())); } - guide_at(cx, p).and_then(|i| cx.doc.guides.get(i)).map(|g| guide_cursor(g.vertical).turned(cx.view_angle())) + guide_under(cx, p).map(|(_, g)| guide_cursor(g.vertical).turned(cx.view_angle())) } /// While a guide is dragged: the smart guide it snapped to and its position by the pointer. diff --git a/crates/tools/src/rulerguide/tests.rs b/crates/tools/src/rulerguide/tests.rs index 4b4f1be72c..f80f31c776 100644 --- a/crates/tools/src/rulerguide/tests.rs +++ b/crates/tools/src/rulerguide/tests.rs @@ -10,10 +10,16 @@ fn ev(kind: PointerKind, x: f64, y: f64, mods: Mods) -> PointerEvent { fn guides_doc() -> vectorcraft_doc::Document { let (mut d, _) = doc_with_rect(); - d.guides = vec![Guide::new(true, 300.0), Guide::new(false, 400.0)]; + d.add_ruler_guide(&Guide::new(true, 300.0)); + d.add_ruler_guide(&Guide::new(false, 400.0)); d } +/// The node id of ruler guide `i` of `d` (its index in the guide commands). +fn gid(d: &vectorcraft_doc::Document, i: usize) -> vectorcraft_doc::NodeId { + d.ruler_guides()[i].id.unwrap() +} + #[test] fn picks_the_guide_within_the_tolerance_unless_hidden_or_locked() { let (d, s, p) = (guides_doc(), Selection::default(), paint()); @@ -37,7 +43,7 @@ fn a_drag_moves_the_selected_guides_in_one_step() { assert_eq!(g.press(&c, &ev(PointerKind::Down, 300.0, 50.0, m)), Some(vec![Action::Exec("guide.select".into(), json!({"indexes": [0]}))])); // The tool sees the guide selected from now on. let mut s = s; - s.set_guides([0]); + s.set_guides([gid(&d, 0)]); let c = cx(&d, &s, &p); let a = g.pointer(&c, &ev(PointerKind::Drag, 340.0, 60.0, m)).unwrap(); assert_eq!(a[0], Action::Begin("Move Guide".into())); @@ -52,7 +58,7 @@ fn a_drag_moves_the_selected_guides_in_one_step() { fn the_dragged_guide_snaps_to_art_ruler_ticks_and_the_grid() { let d = guides_doc(); let mut s = Selection::default(); - s.set_guides([0]); + s.set_guides([gid(&d, 0)]); let p = paint(); let drag_to = |c: &ToolContext, x: f64, mods: Mods| { let mut g = GuideEdit::default(); @@ -253,7 +259,7 @@ fn new_ruler_guide_alt_snaps_on_the_effective_axis() { fn with_smart_guides_off_snap_to_point_pulls_guides_onto_anchors() { let d = guides_doc(); let mut s = Selection::default(); - s.set_guides([0]); + s.set_guides([gid(&d, 0)]); let p = paint(); let off = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; let moved_to = |c: &ToolContext, x: f64| { @@ -291,7 +297,7 @@ fn an_artboard_guide_is_picked_and_snapped_to_across_its_artboard_only() { color: None, guide_label: None, }); - d.guides = vec![Guide { artboard: Some(id), ..Guide::new(false, 150.0) }]; + d.add_ruler_guide(&Guide { artboard: Some(id), ..Guide::new(false, 150.0) }); let (s, p) = (Selection::default(), paint()); let c = cx(&d, &s, &p); assert_eq!(guide_at(&c, Point::new(700.0, 151.0)), Some(0)); @@ -306,7 +312,7 @@ fn an_artboard_guide_is_picked_and_snapped_to_across_its_artboard_only() { fn shift_click_toggles_and_alt_drag_copies() { let d = guides_doc(); let mut s = Selection::default(); - s.set_guides([0, 1]); + s.set_guides([gid(&d, 0), gid(&d, 1)]); let p = paint(); let c = cx(&d, &s, &p); let (shift, alt) = (Mods { shift: true, ..Default::default() }, Mods { alt: true, ..Default::default() }); @@ -336,20 +342,20 @@ fn a_click_on_a_guide_selected_with_objects_makes_it_the_key() { }; let mut s = Selection::default(); s.set([rect]); - s.toggle_guide(0); + s.toggle_guide(gid(&d, 0)); let make = Action::Exec("select.key".into(), json!({"guide": 0})); assert_eq!(click(&s, Mods::default()), vec![make]); - s.key_guide = Some(0); + s.key_guide = Some(gid(&d, 0)); assert_eq!(click(&s, Mods::default()), vec![Action::Exec("select.key".into(), json!({}))], "the key guide again"); let shift = Mods { shift: true, ..Default::default() }; assert_eq!(click(&s, shift), vec![Action::Exec("guide.select".into(), json!({"indexes": [0], "toggle": true}))]); - s.set_guides([0]); + s.set_guides([gid(&d, 0)]); assert_eq!(click(&s, Mods::default()), vec![], "a guide alone has nothing to align"); // Not selected yet: the first click selects it. s.set([rect]); assert_eq!(click(&s, Mods::default()), vec![Action::Exec("guide.select".into(), json!({"indexes": [0]}))]); // A drag moves it. - s.toggle_guide(0); + s.toggle_guide(gid(&d, 0)); let c = cx(&d, &s, &p); let mut g = GuideEdit::default(); g.press(&c, &ev(PointerKind::Down, 302.0, 50.0, Mods::default())); @@ -362,7 +368,7 @@ fn dropped_on_its_ruler_the_guide_is_deleted() { let d = guides_doc(); let p = paint(); let mut s = Selection::default(); - s.set_guides([1]); + s.set_guides([gid(&d, 1)]); // The window shows the document from (0, 0) at 100 %: above y = 0 is the top ruler. let screen = ScreenFrame { origin: Point::ZERO, right: Vec2::new(1.0, 0.0), down: Vec2::new(0.0, 1.0), size: (800.0, 600.0) }; let c = ToolContext { screen: Some(screen), ..cx(&d, &s, &p) }; @@ -457,7 +463,7 @@ fn ruler_guide_shift_move_uses_document_origin() { let paint = paint(); for (index, vertical, from) in [(0, true, 300.0), (1, false, 400.0)] { let mut selection = Selection::default(); - selection.set_guides([index]); + selection.set_guides([gid(&doc, index)]); let c = ToolContext { unit, zoom, smart_guides: false, snap_to_point: false, ..cx(&doc, &selection, &paint) }; for copy in [false, true] { let mut guide = GuideEdit::default(); @@ -498,7 +504,7 @@ fn ruler_guide_shift_zero_and_invalid_origins_use_zero() { let paint = paint(); for (index, vertical, from, want) in [(0, true, 300.0, 225.0), (1, false, 400.0, 235.0)] { let mut selection = Selection::default(); - selection.set_guides([index]); + selection.set_guides([gid(&doc, index)]); let c = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&doc, &selection, &paint) }; let mods = Mods { shift: true, ..Default::default() }; let mut new = NewGuide::new(&c, vertical, None); @@ -522,7 +528,7 @@ fn ruler_guide_origin_leaves_other_snap_modes_unchanged() { let paint = paint(); for (index, vertical, from) in [(0, true, 300.0), (1, false, 400.0)] { let mut selection = Selection::default(); - selection.set_guides([index]); + selection.set_guides([gid(&doc, index)]); let off = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&doc, &selection, &paint) }; for (c, pointer, expected) in [ (ToolContext { ..off }, Point::new(226.4, 237.6), Point::new(226.4, 237.6)), @@ -561,7 +567,7 @@ fn ruler_guide_origin_readouts_are_relative_for_new_and_moved_guides() { for unit in [vectorcraft_doc::Unit::Points, vectorcraft_doc::Unit::Millimeters] { for (index, vertical, from) in [(0, true, 300.0), (1, false, 400.0)] { let mut selection = Selection::default(); - selection.set_guides([index]); + selection.set_guides([gid(&doc, index)]); let c = ToolContext { unit, smart_guides: false, snap_to_point: false, ..cx(&doc, &selection, &paint) }; let want = format!("{}: {}", if vertical { "X" } else { "Y" }, c.len(if vertical { expected.x } else { expected.y })); let check = |overlays: Vec| { diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 8dbdb461ea..1658346127 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -47,7 +47,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; -use crate::objects_on_path::{RotateAllDrag, SpaceDrag, over_rotate_all, over_space}; +use crate::objects_on_path::{MoveAllDrag, RotateAllDrag, SpaceDrag, over_move_all, over_rotate_all, over_space}; use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; @@ -133,6 +133,8 @@ enum State { RotateAll(RotateAllDrag), /// Dragging an Objects on Path group's Space widget. Space(SpaceDrag), + /// Dragging an Objects on Path group's Move All widget. + MoveAll(MoveAllDrag), /// Move or rotate a live mirror axis. Mirror(crate::mirror::MirrorDrag), /// Drag a grid repeat's row, column or corner handle or a spacing slider. @@ -751,7 +753,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, the Rotate All or Space widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, the Rotate All, Space or Move All widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. @@ -842,6 +844,7 @@ impl Tool for SelectionTool { State::Pie(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), State::Space(d) => d.adjusting(), + State::MoveAll(d) => d.adjusting(), State::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), @@ -1030,6 +1033,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::MoveAll(mut d)) => { + let out = d.drag(cx, p); + self.state = State::MoveAll(d); + out + } + (PointerKind::Up, State::MoveAll(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::Bracket(mut b)) => { let out = b.drag(cx, p, m.cmd); self.state = State::Bracket(b); @@ -1094,6 +1106,7 @@ impl Tool for SelectionTool { State::Pie(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), State::Space(d) => o.extend(d.overlays(cx)), + State::MoveAll(d) => o.extend(d.overlays(cx)), State::Loaded { press: Some((start, cur)), .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))), _ => {} } @@ -1145,6 +1158,7 @@ impl Tool for SelectionTool { State::Pie(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, State::Space(_) => return Cursor::ArrowHollow, + State::MoveAll(_) => return Cursor::Move, State::Bracket(_) => return Cursor::PathBracket, State::Loaded { .. } => return Cursor::LoadedText, _ => {} @@ -1170,6 +1184,9 @@ impl Tool for SelectionTool { if over_space(cx, p) { return Cursor::ArrowHollow; } + if over_move_all(cx, p) { + return Cursor::Move; + } if over_bracket(cx, p) { return Cursor::PathBracket; } @@ -1519,7 +1536,7 @@ impl SelectionTool { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, the Rotate All and Space widgets and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, the Rotate All, Space and Move All widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1537,6 +1554,10 @@ impl SelectionTool { self.state = State::Space(d); return Some(vec![]); } + if let Some(d) = MoveAllDrag::hit(cx, ev) { + self.state = State::MoveAll(d); + return Some(vec![]); + } if let Some(b) = BracketDrag::hit(cx, ev) { self.state = State::Bracket(b); return Some(vec![]); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 67f5c91b5d..9069cda939 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -502,7 +502,7 @@ fn click_selects_object() { #[test] fn a_press_on_a_ruler_guide_picks_it_over_the_art() { let (mut d, _) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 150.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 150.0)); let s = Selection::default(); let p = paint(); let cx = cx(&d, &s, &p); @@ -524,7 +524,7 @@ fn a_press_on_a_ruler_guide_picks_it_over_the_art() { #[test] fn a_cmd_shift_double_click_releases_the_guide_under_the_pointer() { let (mut d, id) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 300.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 300.0)); let Some(vectorcraft_doc::NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { panic!("the rectangle is a path") }; *guide = true; let s = Selection::default(); @@ -679,7 +679,7 @@ fn box_cursors_turn_with_the_view() { let mut s = Selection::default(); s.add(id); let p = paint(); - d.guides.push(vectorcraft_doc::Guide::new(false, 300.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 300.0)); let mut c = cx(&d, &s, &p); c.screen = turned_view(90.0); assert!((c.view_angle() - 90.0).abs() < 1e-9); @@ -752,7 +752,7 @@ fn escape_cancels_a_move_or_an_alt_drag_copy() { #[test] fn a_move_snaps_the_grabbed_point_to_a_ruler_guide_with_smart_guides_on() { let (mut d, id) = doc_with_rect(); - d.guides = vec![vectorcraft_doc::Guide::new(true, 173.4)]; + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 173.4)); let mut s = Selection::default(); s.add(id); let p = paint(); @@ -775,7 +775,7 @@ fn a_move_snaps_the_grabbed_point_to_a_ruler_guide_with_smart_guides_on() { #[test] fn a_shift_move_lands_the_edges_on_a_ruler_guide() { let (mut d, id) = doc_with_rect(); - d.guides = vec![vectorcraft_doc::Guide::new(true, 333.0)]; + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 333.0)); let mut s = Selection::default(); s.add(id); let p = paint(); @@ -1118,7 +1118,7 @@ fn a_shift_move_snapped_by_its_grabbed_point_stays_on_its_line() { let other = d.alloc_id(); let sq = vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 151.5, 350.0, 201.5)); d.insert(Some(l), 1, vectorcraft_doc::Node::path(other, sq, vectorcraft_doc::Appearance::default_art())).unwrap(); - d.guides = vec![vectorcraft_doc::Guide::new(true, 420.5)]; + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 420.5)); let mut s = Selection::default(); s.add(id); let p = paint(); @@ -1132,7 +1132,7 @@ fn a_shift_move_snapped_by_its_grabbed_point_stays_on_its_line() { assert!(moved_by(m, (270.5, 270.5)), "{m:?}"); // Smart Guides on, the selection alone with a ruler guide 1.5 below the grabbed point. let (mut d, id) = doc_with_rect(); - d.guides = vec![vectorcraft_doc::Guide::new(false, 330.5)]; + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 330.5)); let mut s = Selection::default(); s.add(id); let (m, _) = shift_moved(&cx(&d, &s, &p), (329.0, 329.0)); @@ -1259,7 +1259,7 @@ fn a_click_on_a_selected_object_makes_it_the_key() { let mut one = Selection::default(); one.add(rect); assert!(click(&one, 150.0, 150.0).is_empty()); - one.guides = vec![0]; + one.guides = vec![vectorcraft_doc::NodeId(999)]; assert_eq!(click(&one, 150.0, 150.0), vec![Action::Exec("select.key".into(), json!({"id": rect.0}))]); } @@ -1482,8 +1482,8 @@ fn directional_marquee_uses_screen_direction_and_a_dead_zone() { fn e_during_a_marquee_takes_only_the_guides_inside() { let (mut d, id) = doc_with_rect(); let board = d.artboards[0].id; - d.guides.push(vectorcraft_doc::Guide::new(true, 150.0)); - d.guides.push(vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, 150.0) }); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 150.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, 150.0) }); let s = Selection::default(); let p = paint(); let cx = cx(&d, &s, &p); @@ -1506,7 +1506,7 @@ fn e_during_a_marquee_takes_only_the_guides_inside() { #[test] fn marquee_selects_ruler_guides() { let (mut d, id) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 80.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 80.0)); let s = Selection::default(); let p = paint(); let cx = cx(&d, &s, &p); @@ -1523,7 +1523,7 @@ fn marquee_selects_ruler_guides() { #[test] fn marquee_selects_only_guide() { let (mut d, _) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(true, 20.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 20.0)); let s = Selection::default(); let p = paint(); let cx = cx(&d, &s, &p); @@ -1540,7 +1540,7 @@ fn marquee_selects_only_guide() { #[test] fn marquee_ignores_locked_guides() { let (mut d, id) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(false, 80.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(false, 80.0)); let s = Selection::default(); let p = paint(); let mut cx_locked = cx(&d, &s, &p); @@ -1769,7 +1769,7 @@ fn handle_drag_snaps_to_anchors_and_ruler_guides_with_snap_to_point() { let other = d.alloc_id(); let sq = vectorcraft_geom::shapes::rectangle(Rect::new(250.0, 250.0, 300.0, 300.0)); d.insert(Some(l), 1, Node::path(other, sq, Appearance::default_art())).unwrap(); - d.guides = vec![vectorcraft_doc::Guide::new(true, 230.5)]; + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 230.5)); let mut s = Selection::default(); s.add(id); let p = paint(); @@ -2436,7 +2436,7 @@ fn a_thin_shapes_centre_point_gives_the_handles_the_pointer() { #[test] fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() { let (mut d, id) = doc_with_live_rect(); - d.guides.push(vectorcraft_doc::Guide::new(true, 150.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 150.0)); let mut s = Selection::default(); s.add(id); let p = paint(); diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 1631170858..6609ef62aa 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -11,19 +11,20 @@ //! 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 on the -//! selection's centre point (Show Center) moves it, and one just outside a corner of its box turns -//! it about that centre, as the Selection tool's rotate zone does; a press anywhere else draws a -//! new shape (#5477). +//! a live ellipse's pie widget sets its pie angle, as with the Selection tool; a drag on one of the +//! box's eight handles scales the selection, a press on the selection's centre point (Show Center) +//! moves it, and one just outside a corner of its box turns it about that centre, as the Selection +//! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477). use serde_json::{Value, json}; +use vectorcraft_doc::OrientedBox; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; -use crate::bbox::{move_delta, rotate_for_drag}; +use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag}; -use crate::guides::{DrawSnap, Leave, square}; +use crate::guides::{DrawSnap, Leave, PointSnap, Targets, square}; use crate::pie::{self, PieDrag}; -use crate::select::{MoveSnap, hit_center, matrix_json, rotate_zone, shown_box}; +use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; 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 › @@ -31,6 +32,22 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// value stop there too. pub const MAX_CORNER_RADIUS: f64 = 1296.0; +/// How far (screen points, along each axis) from a bounding-box handle's centre a shape tool's +/// press scales the selection: half the drawn handle square, which is 6 points wide at the default +/// Selection & Anchor Display › Size 3 and a point wider or narrower per step. The Selection tool +/// takes 5 points. +fn handle_reach(cx: &ToolContext) -> f64 { + (6.0 + f64::from(cx.anchor_size.clamp(1, 7)) - 3.0) / 2.0 +} + +/// A document offset `d` in screen points: across and down the window. +fn screen_offset(cx: &ToolContext, d: Vec2) -> (f64, f64) { + match cx.screen { + Some(s) if s.right.hypot2() > 0.0 && s.down.hypot2() > 0.0 => (d.dot(s.right) / s.right.hypot2(), d.dot(s.down) / s.down.hypot2()), + _ => (d.x * cx.zoom, d.y * cx.zoom), + } +} + /// 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 { @@ -43,9 +60,15 @@ enum WidgetDrag { Pie(PieDrag), } -/// A drag of the selection itself, taken by a shape tool: the centre point moves it and the zone -/// just outside a corner of its box turns it, as the Selection tool's drags do (#5477). +/// A drag of the selection itself, taken by a shape tool: a handle of its box scales it, the centre +/// point moves it and the zone just outside a corner of its box turns it, as the Selection tool's +/// drags do (#5477). enum SelectionDrag { + /// Scaling the selection by `handle` of its box `bx`, as it was when the press came. `areas`: + /// area type is selected, and its frame resizes while its type keeps its size. `snap` holds + /// what the moved handle snaps to. `last`: where the last drag was, and whether Backtick was + /// down then. + Scale { handle: Handle, bx: OrientedBox, areas: bool, snap: Box, last: Option<(Point, bool)> }, /// Moving the selection by the centre point `hold`: `start` is where the press was, and the /// move has begun once the pointer left the drag threshold. Move { start: Point, hold: Point, began: bool, snap: Box }, @@ -178,6 +201,22 @@ impl ShapeTool { rotate_zone(cx, &self.box_of(cx)?, p) } + /// The handle of the selection's box under `p`, with the box: a press there scales the + /// selection, as with the Selection tool. A shape tool takes only the drawn handle square + /// ([`handle_reach`]), which stays square to the screen when the box or the view is turned, so + /// a press just beside a handle still draws a new shape. + fn over_handle(&self, cx: &ToolContext, p: Point) -> Option<(Handle, OrientedBox)> { + let bx = self.box_of(cx)?; + let reach = handle_reach(cx); + Handle::ALL + .into_iter() + .find(|h| { + let (x, y) = screen_offset(cx, p - bx.to_doc() * h.pos(bx.rect)); + x.abs() <= reach && y.abs() <= reach + }) + .map(|h| (h, bx)) + } + /// Is `p` over the centre point of a selected object (Attributes › Show Center), where a press /// moves the selection? The point shows whatever View › Show Bounding Box says, so the press /// takes it too. @@ -185,22 +224,35 @@ impl ShapeTool { shows_shape_widgets(self.id) && hit_center(cx, p, cx.point_tol()).is_some() } - /// A press on the selection's centre point or just outside a corner of its box: the drag moves - /// or turns the selection instead of drawing a new shape (#5477). A turn begins with the press, - /// as the Selection tool's does; a move begins once the pointer leaves the drag threshold. + /// A press on a handle of the selection's box, on its centre point or just outside a corner of + /// its box: the drag scales, moves or turns the selection instead of drawing a new shape + /// (#5477). The handles come first, as with the Selection tool. A scale or a turn begins with + /// the press, as the Selection tool's do; a move begins once the pointer leaves the drag + /// threshold. fn press_selection(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { if !shows_shape_widgets(self.id) { return None; } - self.selection = match hit_center(cx, ev.pos, cx.point_tol()) { - Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }), - None => self.over_rotate(cx, ev.pos).map(|center| SelectionDrag::Rotate { center, start: ev.pos }), + self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) { + let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type); + let areas = cx.selection.objects.iter().any(is_area); + Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::new(cx, || Targets::for_scale(cx))), last: None }) + } else { + match hit_center(cx, ev.pos, cx.point_tol()) { + Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }), + None => self.over_rotate(cx, ev.pos).map(|center| SelectionDrag::Rotate { center, start: ev.pos }), + } }; self.selection.as_ref()?; self.snap.clear(); self.guides.clear(); self.measure = None; Some(match self.selection { + // Only area type: the step resizes type areas; anything else scales. + Some(SelectionDrag::Scale { areas, .. }) => { + let only_areas = areas && cx.selection.objects.iter().all(|id| cx.doc.node(*id).is_some_and(is_area_type)); + vec![Action::Begin(if only_areas { "Resize Type Area" } else { "Scale" }.into())] + } Some(SelectionDrag::Rotate { .. }) => vec![Action::Begin("Rotate".into())], _ => vec![], }) @@ -235,6 +287,32 @@ impl ShapeTool { self.measure = cx.transform_tools_guides.then(|| (ev.pos, format!("{:.1}°", -deg))); vec![Action::Preview("object.transform".into(), json!({"matrix": matrix_json(a), "copy": false}))] } + (PointerKind::Drag, SelectionDrag::Scale { handle, bx, areas, snap, last }) => { + // As the Selection tool scales: in the box's own frame, the moved handle snapped, + // and with Use Preview Bounds by the visual box's size unless the drag flips it. + *last = Some((ev.pos, ev.backquote)); + let m = ev.mods; + let a = scale_for_drag(bx.rect, *handle, bx.to_local(ev.pos), m.shift, m.alt); + let (a, guides) = snap.snap_scale(cx, bx, *handle, a, m.shift, m.alt); + self.guides = guides; + let nr = a.transform_rect_bbox(bx.rect); + self.measure = cx.transform_tools_guides.then(|| (ev.pos, cx.size_label(nr.width(), nr.height()))); + let [sx, _, _, sy, _, _] = a.as_coeffs(); + let (cmd, mut params) = if !ev.backquote && cx.preview_bounds && sx > 0.0 && sy > 0.0 { + let reference = if m.alt { 4 } else { handle.opposite().reference() }; + ("object.setBounds", json!({ "width": nr.width(), "height": nr.height(), "reference": reference, "copy": false })) + } else { + ("object.transform", json!({ "matrix": matrix_json(bx.conjugate(a)), "copy": false })) + }; + if *areas { + params["typeAreas"] = json!(true); + } + if ev.backquote { + params["objects"] = json!(false); + params["patterns"] = json!(true); + } + vec![Action::Preview(cmd.into(), params)] + } (PointerKind::Up, SelectionDrag::Move { began, .. }) => { let began = *began; self.selection = None; @@ -243,8 +321,22 @@ impl ShapeTool { self.snapped = false; if began { vec![Action::Commit] } else { vec![] } } + (PointerKind::Up, SelectionDrag::Scale { last, .. }) => { + // Backtick pressed or let go after the last drag: the scale is previewed again at + // that drag's position with the key as it is at the release, as the Selection tool + // does. + let again = last.filter(|(_, backquote)| *backquote != ev.backquote).map(|(pos, _)| pos); + let mut out = + again.and_then(|pos| self.selection_pointer(cx, &PointerEvent { kind: PointerKind::Drag, pos, ..*ev })).unwrap_or_default(); + self.selection = None; + self.guides.clear(); + self.measure = None; + out.push(Action::Commit); + out + } (PointerKind::Up, SelectionDrag::Rotate { .. }) => { self.selection = None; + self.guides.clear(); self.measure = None; vec![Action::Commit] } @@ -422,8 +514,9 @@ impl Tool for ShapeTool { fn busy(&self) -> bool { self.start.is_some() || self.widget.is_some() || self.selection.is_some() } - /// A widget or selection drag takes the pointer; otherwise a press draws, unless it lands on - /// the selection's centre point or in the rotate zone just outside its box's corner. + /// A widget or selection drag takes the pointer; otherwise a press draws, unless it lands on a + /// handle of the selection's box, its centre point or the rotate zone just outside its box's + /// corner. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { if let Some(out) = self.widget_pointer(cx, ev) { return out; @@ -434,7 +527,11 @@ impl Tool for ShapeTool { match ev.kind { PointerKind::Move => { // Over a widget a press would drag, no Smart Guide for a new shape's start. - if self.over_widget(cx, ev.pos) || self.over_center(cx, ev.pos) || self.over_rotate(cx, ev.pos).is_some() { + if self.over_widget(cx, ev.pos) + || self.over_handle(cx, ev.pos).is_some() + || self.over_center(cx, ev.pos) + || self.over_rotate(cx, ev.pos).is_some() + { self.snap.clear(); } else { self.snap.hover(cx, ev.pos, &[], None); @@ -566,6 +663,11 @@ impl Tool for ShapeTool { vec![] } } + /// A drag of a handle of the selection's box: the canvas keeps drawing the box at the changing + /// bounds, as for the Selection tool. + fn resizing(&self) -> bool { + matches!(self.selection, Some(SelectionDrag::Scale { .. })) + } /// Adjusting a widget (the canvas hides the bounding box meanwhile, as for the Selection tool). fn transforming(&self) -> bool { match &self.widget { @@ -573,7 +675,7 @@ impl Tool for ShapeTool { Some(WidgetDrag::Pie(d)) => d.adjusting(), None => match &self.selection { Some(SelectionDrag::Move { began, .. }) => *began, - Some(SelectionDrag::Rotate { .. }) => true, + Some(SelectionDrag::Rotate { .. } | SelectionDrag::Scale { .. }) => true, None => false, }, } @@ -630,9 +732,9 @@ impl Tool for ShapeTool { } o } - /// The Selection tool's pointer over a Live Shape widget, the selection's centre point or the - /// rotate zone just outside its box's corner; the crosshair everywhere else, where a press - /// draws. + /// The Selection tool's pointer over a Live Shape widget, a handle of the selection's box, its + /// centre point or the rotate zone just outside its box's corner; the crosshair everywhere + /// else, where a press draws. 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(); @@ -645,13 +747,14 @@ impl Tool for ShapeTool { // move snaps, as the Selection tool's. match &self.selection { Some(SelectionDrag::Rotate { center, .. }) => return Cursor::rotate_about_in_view(*center, p, cx.view_angle()), + Some(SelectionDrag::Scale { handle, bx, .. }) => return handle_cursor(*handle, bx.angle - cx.view_angle()), Some(SelectionDrag::Move { began: true, .. }) if m.alt => return Cursor::SelectionCopy, Some(SelectionDrag::Move { began: true, .. }) => return if self.snapped { Cursor::ArrowHollow } else { Cursor::Arrow }, Some(_) => return Cursor::Arrow, None => {} } - // A press takes the corner and pie widgets first, then the centre point, then the zone - // just outside a corner; everywhere else it draws a new shape. + // A press takes the corner and pie widgets first, then the box's handles, then the centre + // point, then the zone just outside a corner; everywhere else it draws a new shape. if idle { if shows_shape_widgets(self.id) && corners::over_widget(cx, p, false) { return Cursor::CornerRadius; @@ -659,6 +762,9 @@ impl Tool for ShapeTool { if self.over_widget(cx, p) { return Cursor::ArrowHollow; } + if let Some((handle, bx)) = self.over_handle(cx, p) { + return handle_cursor(handle, bx.angle - cx.view_angle()); + } if self.over_center(cx, p) { return Cursor::Move; } diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 580f15c164..663cdab3fd 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -583,6 +583,96 @@ fn a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corn assert_eq!(a.first(), Some(&Action::Begin("Rectangle".into())), "{a:?}"); } +/// With a shape tool, a drag on one of the eight handles of the selection's bounding box scales the +/// selection, as with the Selection tool, instead of drawing a new shape from the handle. +#[test] +fn a_shape_tool_scales_the_selection_by_its_bounding_box_handles() { + let (d, s) = unfilled_live_rect(); + let p = paint(); + let c = cx(&d, &s, &p); + let corner = Point::new(200.0, 200.0); + for id in ["rectangle", "roundedRectangle", "polygon", "star", "ellipse"] { + let mut t = ShapeTool::new(id); + assert_eq!(t.cursor(&c, corner, Mods::default()), handle_cursor(Handle::BottomRight, 0.0), "{id}"); + // No Smart Guide for a new shape's start over a handle. + t.pointer(&c, &PointerEvent::new(PointerKind::Move, corner.x, corner.y)); + assert!(t.overlays(&c).is_empty(), "{id}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, corner.x, corner.y)), vec![Action::Begin("Scale".into())], "{id}"); + // A resize: the canvas keeps the box on show at the changing bounds. + assert!(t.busy() && t.transforming() && t.resizing(), "{id}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 220.0, 230.0)); + let want = scale_for_drag(Rect::new(100.0, 100.0, 200.0, 200.0), Handle::BottomRight, Point::new(220.0, 230.0), false, false); + assert_eq!(a, vec![Action::Preview("object.transform".into(), json!({"matrix": matrix_json(want), "copy": false}))], "{id}"); + assert_eq!(t.cursor(&c, Point::new(220.0, 230.0), Mods::default()), handle_cursor(Handle::BottomRight, 0.0), "{id}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 220.0, 230.0)), vec![Action::Commit], "{id}"); + assert!(!t.busy() && !t.transforming() && !t.resizing(), "{id}"); + } + // The side handles scale along one axis; Escape turns the scale back. + let mut t = ShapeTool::new("rectangle"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)), vec![Action::Begin("Scale".into())]); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 150.0, 80.0)); + let want = scale_for_drag(Rect::new(100.0, 100.0, 200.0, 200.0), Handle::Top, Point::new(150.0, 80.0), false, false); + assert_eq!(a, vec![Action::Preview("object.transform".into(), json!({"matrix": matrix_json(want), "copy": false}))]); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy()); + // Backtick pressed after the last drag: the release previews the scale again for the patterns + // only, then commits. + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, corner.x, corner.y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 220.0, 230.0)); + let a = t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 220.0, 230.0) }); + let want = scale_for_drag(Rect::new(100.0, 100.0, 200.0, 200.0), Handle::BottomRight, Point::new(220.0, 230.0), false, false); + let patterns = json!({"matrix": matrix_json(want), "copy": false, "objects": false, "patterns": true}); + assert_eq!(a, vec![Action::Preview("object.transform".into(), patterns), Action::Commit]); + assert!(!t.busy()); + // View › Hide Bounding Box hides the handles, and a press there draws a new shape. + let hidden = ToolContext { show_bbox: false, ..cx(&d, &s, &p) }; + let mut t = ShapeTool::new("rectangle"); + assert_eq!(t.cursor(&hidden, corner, Mods::default()), Cursor::Crosshair); + t.pointer(&hidden, &PointerEvent::new(PointerKind::Down, corner.x, corner.y)); + let a = t.pointer(&hidden, &PointerEvent::new(PointerKind::Drag, 240.0, 240.0)); + assert_eq!(a.first(), Some(&Action::Begin("Rectangle".into())), "{a:?}"); + // The Line Segment tool shows no box, so its press draws. + let mut t = ShapeTool::new("lineSegment"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, corner.x, corner.y)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 240.0, 240.0)); + assert_eq!(a.first(), Some(&Action::Begin("Line".into())), "{a:?}"); +} + +/// A shape tool's press scales the selection only on the drawn handle square: 3 screen points from +/// the handle's centre along each axis at the default Anchor Size, at any zoom. A press 4 points +/// from it draws a new shape; at Anchor Size 7 the square is 10 points wide and that press scales. +#[test] +fn a_shape_tool_draws_from_a_press_just_beside_a_handle() { + let (d, s) = unfilled_live_rect(); + let p = paint(); + for zoom in [1.0, 4.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let on = Point::new(200.0 + 3.0 / zoom, 200.0 - 3.0 / zoom); + let mut t = ShapeTool::new("rectangle"); + assert_eq!(t.cursor(&c, on, Mods::default()), handle_cursor(Handle::BottomRight, 0.0), "{zoom}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, on.x, on.y)), vec![Action::Begin("Scale".into())], "{zoom}"); + let beside = Point::new(200.0 + 2.0 / zoom, 200.0 + 4.0 / zoom); + let mut t = ShapeTool::new("rectangle"); + assert_eq!(t.cursor(&c, beside, Mods::default()), Cursor::Crosshair, "{zoom}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, beside.x, beside.y)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 260.0, 260.0)); + assert_eq!(a.first(), Some(&Action::Begin("Rectangle".into())), "{zoom}: {a:?}"); + let big = ToolContext { anchor_size: 7, ..c }; + let mut t = ShapeTool::new("rectangle"); + assert_eq!(t.cursor(&big, beside, Mods::default()), handle_cursor(Handle::BottomRight, 0.0), "{zoom}"); + assert_eq!(t.pointer(&big, &PointerEvent::new(PointerKind::Down, beside.x, beside.y)), vec![Action::Begin("Scale".into())], "{zoom}"); + } + // In a view turned 45°, the drawn square stays square to the screen: a press 3 screen points + // right of and below the handle's centre, 4.24 pt along the box's x axis, scales. + let screen = turned_view(45.0); + let c = ToolContext { screen, ..cx(&d, &s, &p) }; + let f = screen.unwrap_or_else(|| panic!("a turned view")); + let corner = Point::new(200.0, 200.0) + f.right * 3.0 + f.down * 3.0; + let mut t = ShapeTool::new("rectangle"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, corner.x, corner.y)), vec![Action::Begin("Scale".into())]); +} + /// Two selected live rectangles, the second placed so that its top-left Live Corners widget (10 pt /// in along the corner's bisector) lands on the first one's centre point. fn two_live_rects() -> (vectorcraft_doc::Document, Selection) { diff --git a/crates/tools/src/slice.rs b/crates/tools/src/slice.rs index 8b092d8ad0..69bbf9051f 100644 --- a/crates/tools/src/slice.rs +++ b/crates/tools/src/slice.rs @@ -41,9 +41,9 @@ fn has_area(r: Rect) -> bool { fn snap(cx: &ToolContext, p: Point) -> (Point, Vec) { let (mut q, ov) = crate::guides::snap_draw(cx, p, &[]); let tol = cx.tol(5.0); + let guides = cx.doc.ruler_guides(); let nearest = |vertical: bool, v: f64| { - cx.doc - .guides + guides .iter() .filter(|g| g.vertical == vertical && (g.pos - v).abs() <= tol && cx.doc.guide_shown(g) && cx.doc.guide_passes(g, p, tol)) .min_by(|a, b| (a.pos - v).abs().total_cmp(&(b.pos - v).abs())) @@ -390,7 +390,7 @@ mod tests { #[test] fn the_slice_tool_drags_out_a_slice_in_one_undo_step() { let (mut d, _) = doc_with_rect(); - d.guides.push(Guide::new(true, 403.0)); + d.add_ruler_guide(&Guide::new(true, 403.0)); let s = Selection::default(); let p = paint(); let mut c = cx(&d, &s, &p); @@ -557,7 +557,7 @@ mod tests { assert!(near(resize(&neither, (60.0, 25.0), (97.0, 25.0), none), Rect::new(10.0, 10.0, 97.0, 40.0))); // A ruler guide at x = 98 takes the side dragged 1 px from it, over the rectangle's edge // 1 px the other way, with Smart Guides on or off. - d.guides.push(Guide::new(true, 98.0)); + d.add_ruler_guide(&Guide::new(true, 98.0)); for c in [cx(&d, &sel, &p), ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &sel, &p) }] { assert!(near(resize(&c, (60.0, 25.0), (99.0, 25.0), none), Rect::new(10.0, 10.0, 98.0, 40.0))); } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index db3aad793e..32e1df2a16 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -1543,7 +1543,7 @@ mod tests { let d = doc_with_live_over_green(|d| { let a = vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 10.0); let red = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 300.0, 420.0, 320.0)), a); - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let content = vec![std::sync::Arc::new(red)]; let n = Node::new( d.alloc_id(), @@ -1574,7 +1574,7 @@ mod tests { use vectorcraft_geom::{Affine, Rect}; let d = doc_with_live_over_green(|d| { let red = solid_rect(d, Rect::new(300.0, 300.0, 420.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); - let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true }; + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; let content = vec![std::sync::Arc::new(red)]; let options = Default::default(); Node::new( diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs index d984504e1f..6c3c76862c 100644 --- a/crates/tools/src/xform/gradient.rs +++ b/crates/tools/src/xform/gradient.rs @@ -20,6 +20,18 @@ //! focal point (where the first stop sits): drag it to make the gradient off-centre, back onto //! the centre to centre it. //! +//! A conic gradient shows the same extent ellipse, aspect handle and center ring, without a focal +//! dot: the bar runs from the center to where the sweep starts, its stops along it by their share +//! of the turn. +//! +//! A diamond gradient shows its square instead of the ellipse, a corner at the end of the bar, +//! with the same aspect handle and center ring and no focal dot: drag the dot across the bar to +//! stretch the square into a rhombus, and the square elsewhere to rotate it. +//! +//! Dragging the aspect handle of a radial or diamond gradient whose file gave it a negative +//! aspect starts from its size (the aspect's magnitude); only a conic's negative aspect mirrors +//! it. +//! //! On a freeform gradient the tool edits its points instead (see `freeform`). use serde_json::{Value, json}; @@ -99,18 +111,25 @@ impl Annotator { fn with(geom: GradientGeom, stops: &[GradientStop]) -> Self { Self { geom, gradient: Gradient::new(GradientKind::Linear, stops.to_vec()) } } + /// Placed by a center and an extent ellipse (radial and conic) or square (diamond)? fn radial(&self) -> bool { + self.gradient.kind.is_centered() + } + /// Has a focal point to drag (radial only)? + fn focal(&self) -> bool { self.gradient.kind == GradientKind::Radial } - /// A radial's aspect handle: on the extent ellipse, across the bar from the stops. + /// A radial's (or conic's) aspect handle: on the extent ellipse, across the bar from the + /// stops (a mirrored conic's too: its negative aspect only turns the sweep the other way). pub fn aspect_point(&self) -> Point { - self.geom.start - self.normal() * (self.vector().hypot() * self.geom.aspect) + self.geom.start - self.normal() * (self.vector().hypot() * self.geom.aspect.abs()) } - /// How far `p` is from a radial's extent ellipse (approximately, along the ray from the - /// centre). + /// How far `p` is from a radial's extent ellipse, or a diamond's square (approximately, along + /// the ray from the center). fn off_ellipse(&self, p: Point) -> Option { let m = self.geom.unit_frame()?; - let rho = (m.inverse() * p).to_vec2().hypot(); + let q = (m.inverse() * p).to_vec2(); + let rho = if self.gradient.kind == GradientKind::Diamond { q.x.abs() + q.y.abs() } else { q.hypot() }; (rho > 1e-12).then(|| p.distance(self.geom.start) * (1.0 - 1.0 / rho).abs()) } fn vector(&self) -> Vec2 { @@ -160,7 +179,7 @@ impl Annotator { return Some(Part::End); } let radial = self.radial(); - if radial && near(Some(self.geom.focal_point()), FOCAL_HIT) { + if self.focal() && near(Some(self.geom.focal_point()), FOCAL_HIT) { return Some(Part::Focal); } if near(Some(self.geom.start), if radial { CENTRE_HIT } else { HANDLE }) { @@ -239,14 +258,19 @@ pub struct GradientTool { } /// Overlays of an annotator: the bar, the handles, the midpoint diamonds and a chip per stop; a -/// radial's extent ellipse with its aspect handle, centre ring and focal dot. +/// radial's extent ellipse (a diamond's square) with its aspect handle, center ring and focal dot. fn annotator_overlays(cx: &ToolContext, a: &Annotator) -> Vec { let (s, e) = (a.geom.start, a.geom.end); let shade = Vec2::new(0.0, cx.tol(1.0)); let mut o = vec![]; if let Some(m) = a.geom.unit_frame().filter(|_| a.radial()) { // Dark dashes over a light line: readable on any art. - let path = vectorcraft_geom::kurbo::Ellipse::from_affine(m).to_path(cx.tol(0.25)); + let path = if a.gradient.kind == GradientKind::Diamond { + // A diamond's extent is its square, a corner at the end of the vector. + super::polygon(&[m * Point::new(1.0, 0.0), m * Point::new(0.0, 1.0), m * Point::new(-1.0, 0.0), m * Point::new(0.0, -1.0)], true) + } else { + vectorcraft_geom::kurbo::Ellipse::from_affine(m).to_path(cx.tol(0.25)) + }; o.push(Overlay::Path { path: path.clone(), color: LIGHT, width: 1.0, dashed: false }); o.push(Overlay::Path { path, color: BAR, width: 1.0, dashed: true }); o.push(Overlay::Handle { p: a.aspect_point(), color: BAR }); @@ -256,7 +280,7 @@ fn annotator_overlays(cx: &ToolContext, a: &Annotator) -> Vec { o.extend([ Overlay::Line { a: s, b: e, color: BAR, dashed: false }, Overlay::Line { a: s + shade, b: e + shade, color: LIGHT, dashed: false }, - Overlay::Handle { p: if a.radial() { a.geom.focal_point() } else { s }, color: BAR }, + Overlay::Handle { p: if a.focal() { a.geom.focal_point() } else { s }, color: BAR }, Overlay::Anchor { p: e, color: BAR, filled: true, size: 7.0 }, ]); let len = a.vector().hypot(); @@ -321,7 +345,9 @@ impl GradientTool { Some((a, Part::End)) => Grab::End(a.geom), Some((a, Part::Rotate)) => Grab::Rotate { geom: a.geom, from: (p - a.geom.start).atan2() - a.vector().atan2() }, Some((a, Part::Focal)) => Grab::Focal(a.geom), - Some((a, Part::Aspect)) => Grab::Aspect(a.geom), + // Only a conic's negative aspect means a mirror (a file's other kinds draw as its size). + Some((a, Part::Aspect)) if a.gradient.kind == GradientKind::Conic => Grab::Aspect(a.geom), + Some((a, Part::Aspect)) => Grab::Aspect(GradientGeom { aspect: a.geom.aspect.abs(), ..a.geom }), None => { if cx.selection.is_empty() { let Some(h) = hit_test(cx.doc, p, cx.hit_options()) else { return out }; @@ -386,10 +412,12 @@ impl GradientTool { ("paint.setGradientGeom", params) } Grab::Aspect(geom) => { - // The pointer's distance across the bar, as a fraction of the radius. + // The pointer's distance across the bar, as a fraction of the radius; a mirrored + // conic (negative aspect) stays mirrored. let across = Annotator::with(*geom, &[]).project(p).1.abs(); let mut params = Self::geom_params(cx, geom.start, geom.end); - params["aspect"] = json!(across / geom.length().max(1e-12) * 100.0); + let sign = if geom.is_mirrored() { -1.0 } else { 1.0 }; + params["aspect"] = json!(sign * across / geom.length().max(1e-12) * 100.0); ("paint.setGradientGeom", params) } Grab::Stop { index, from, copy } => { diff --git a/crates/tools/src/xform/gradient/tests.rs b/crates/tools/src/xform/gradient/tests.rs index c6582152b2..943ed3af7b 100644 --- a/crates/tools/src/xform/gradient/tests.rs +++ b/crates/tools/src/xform/gradient/tests.rs @@ -366,3 +366,90 @@ fn a_radial_shows_its_extent_ellipse_aspect_handle_and_focal_dot() { assert_eq!((hit(100.0, 200.0), hit(0.0, 150.0), hit(100.0, 220.0)), (Some(Part::Rotate), Some(Part::Rotate), None)); assert_eq!(GradientTool::default().cursor(&cx, Point::new(100.0, 200.0), Mods::default()), Cursor::Rotate); } + +/// A conic shows the extent ellipse, aspect handle and center ring of a radial without a focal +/// dot; mirrored (a negative aspect), its aspect handle is still across the bar from the stops, +/// and dragging it keeps the mirror. +#[test] +fn a_conic_shows_its_extent_ellipse_and_aspect_handle_without_a_focal_dot() { + for aspect in [0.5, -0.5] { + let (mut d, s) = graded(two()); + let n = d.node_mut(s.objects[0]).unwrap(); + let Paint::Gradient(mut g) = n.appearance.fill_paint() else { panic!("a gradient fill") }; + g.gradient.kind = GradientKind::Conic; + g.geom.as_mut().unwrap().aspect = aspect; + n.appearance.set_fill(Paint::Gradient(g)); + let p = paint(); + let cx = cx(&d, &s, &p); + let o = GradientTool::default().overlays(&cx); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { dashed: true, .. })).count(), 1, "the extent ellipse"); + // The aspect handle 50 pt above the center, the start handle on the center. + assert!(o.contains(&Overlay::Handle { p: Point::new(100.0, 100.0), color: BAR }), "{aspect}: {o:?}"); + assert!(o.contains(&Overlay::Handle { p: Point::new(100.0, 150.0), color: BAR }), "{aspect}: {o:?}"); + let a = Annotator::of(&cx).unwrap(); + let hit = |x: f64, y: f64| a.hit(&cx, Point::new(x, y)); + assert_eq!((hit(100.0, 150.0), hit(100.0, 100.0), hit(0.0, 150.0)), (Some(Part::Start), Some(Part::Aspect), Some(Part::Rotate))); + // Dragged 20 pt further out, the aspect grows to 70% and keeps its sign. + let mut t = GradientTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, Point::new(100.0, 100.0))); + let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(100.0, 80.0)))).clone(); + let want = 70.0f64.copysign(aspect); + assert!((v["aspect"].as_f64().unwrap() - want).abs() < 1e-9, "{aspect}: {v}"); + } +} + +/// A diamond shows its square (a corner at the end of the vector) with the aspect handle and +/// center ring of a radial, without a focal dot. Dragging the aspect handle of one a file gave a +/// negative aspect sets a positive one. +#[test] +fn a_diamond_shows_its_square_and_aspect_handle() { + for aspect in [0.5, -0.5] { + let (mut d, s) = graded(two()); + let n = d.node_mut(s.objects[0]).unwrap(); + let Paint::Gradient(mut g) = n.appearance.fill_paint() else { panic!("a gradient fill") }; + g.gradient.kind = GradientKind::Diamond; + g.geom.as_mut().unwrap().aspect = aspect; + let geom = g.geom.unwrap(); + n.appearance.set_fill(Paint::Gradient(g)); + let p = paint(); + let cx = cx(&d, &s, &p); + let o = GradientTool::default().overlays(&cx); + let squares: Vec<_> = o.iter().filter_map(|o| if let Overlay::Path { path, dashed: true, .. } = o { Some(path) } else { None }).collect(); + assert_eq!(squares.len(), 1, "the square"); + // Four straight sides through the corners: the end of the vector, the aspect handle and + // their mirrors about the center. + let corners: Vec = squares[0].elements().iter().filter_map(|e| e.end_point()).collect(); + let u = geom.end - geom.start; + let w = Vec2::new(u.y, -u.x) * 0.5; + for want in [geom.end, geom.start - w, geom.start - u, geom.start + w] { + assert!(corners.iter().any(|c| c.distance(want) < 1e-9), "{aspect}: {want:?} in {corners:?}"); + } + assert!(!squares[0].elements().iter().any(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::CurveTo(..))), "straight sides"); + assert!(o.contains(&Overlay::Handle { p: Point::new(100.0, 100.0), color: BAR }), "{aspect}: {o:?}"); + let a = Annotator::of(&cx).unwrap(); + assert_eq!(a.hit(&cx, Point::new(100.0, 100.0)), Some(Part::Aspect)); + let mut t = GradientTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, Point::new(100.0, 100.0))); + let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(100.0, 80.0)))).clone(); + assert!((v["aspect"].as_f64().unwrap() - 70.0).abs() < 1e-9, "{aspect}: {v}"); + } +} + +/// Dragging the aspect handle of a radial a file gave a negative aspect (which the commands +/// refuse) sets a positive one, as for a diamond: only a conic's sign mirrors it. +#[test] +fn a_radial_with_a_negative_aspect_drags_to_a_positive_one() { + let (mut d, s) = graded(two()); + let n = d.node_mut(s.objects[0]).unwrap(); + let Paint::Gradient(mut g) = n.appearance.fill_paint() else { panic!("a gradient fill") }; + g.gradient.kind = GradientKind::Radial; + g.geom.as_mut().unwrap().aspect = -0.5; + n.appearance.set_fill(Paint::Gradient(g)); + let p = paint(); + let cx = cx(&d, &s, &p); + assert_eq!(Annotator::of(&cx).unwrap().hit(&cx, Point::new(100.0, 100.0)), Some(Part::Aspect)); + let mut t = GradientTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, Point::new(100.0, 100.0))); + let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(100.0, 80.0)))).clone(); + assert!((v["aspect"].as_f64().unwrap() - 70.0).abs() < 1e-9, "{v}"); +} diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index e3a0090561..cccb1ebcae 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -281,7 +281,7 @@ mod tests { #[test] fn shift_drag_meets_a_ruler_guide() { let (mut d, _) = doc_with_rect(); - d.guides.push(vectorcraft_doc::Guide::new(true, 50.0)); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 50.0)); let s = Selection::default(); let p = paint(); let mut cx = cx(&d, &s, &p); diff --git a/crates/trace/src/raster.rs b/crates/trace/src/raster.rs index fc7cd10f67..3e61c58953 100644 --- a/crates/trace/src/raster.rs +++ b/crates/trace/src/raster.rs @@ -56,6 +56,37 @@ pub struct Raster { pub rgba: Vec, } +/// The pixels the first frame of GIF `bytes` declares in its image descriptor, which the decoder +/// allocates for before it crops the frame to the logical screen the dimension check reads. `None` +/// when the bytes aren't a GIF or hold no frame header. +fn gif_first_frame_pixels(bytes: &[u8]) -> Option { + if !bytes.starts_with(b"GIF8") { + return None; + } + let flags = *bytes.get(10)?; + let mut at = 13 + if flags & 0x80 != 0 { 3 << ((flags & 7) + 1) } else { 0 }; + loop { + match *bytes.get(at)? { + // An extension: its data sub-blocks end at a zero length. + 0x21 => { + at += 2; + loop { + let len = usize::from(*bytes.get(at)?); + at += 1 + len; + if len == 0 { + break; + } + } + } + 0x2C => { + let d = bytes.get(at + 5..at + 9)?; + return Some(u64::from(u16::from_le_bytes([d[0], d[1]])) * u64::from(u16::from_le_bytes([d[2], d[3]]))); + } + _ => return None, + } + } +} + impl Raster { /// A raster from RGBA bytes, which must be exactly `width * height * 4` of them: any other /// length (bytes from a file, a plug-in or a message) is a [`TraceError::Decode`] error, not @@ -85,7 +116,7 @@ impl Raster { if w == 0 || h == 0 { return Err(TraceError::Empty); } - if u64::from(w) * u64::from(h) > MAX_PIXELS { + if u64::from(w) * u64::from(h) > MAX_PIXELS || gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_PIXELS) { return Err(TraceError::TooLarge { width: w, height: h, max: MAX_PIXELS >> 20 }); } let img = image::load_from_memory(bytes).map_err(decode_err)?.to_rgba8(); @@ -112,6 +143,9 @@ impl Raster { } // Decoded within the allocation the source limit needs; the web keeps file import's 512 MB. // A deeper image (16 bits a channel) that needs more fails with a decode error. + if gif_first_frame_pixels(bytes).is_some_and(|p| p > MAX_SOURCE_PIXELS) { + return Err(TraceError::TooLarge { width: w, height: h, max: MAX_SOURCE_PIXELS >> 20 }); + } let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| TraceError::Decode(e.to_string()))?; let mut limits = image::Limits::default(); limits.max_alloc = Some(if cfg!(target_arch = "wasm32") { 512 << 20 } else { MAX_SOURCE_PIXELS * 4 }); diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 19f2081751..4e138dfd5b 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -2908,3 +2908,15 @@ fn noise_keeps_a_kept_rare_colours_regions_but_not_its_specks() { assert_eq!(a, b); assert!(a.iter().all(|&v| v == 0)); } + +/// A GIF whose logical screen is one pixel but whose frame declares 65535 × 65535 is refused before +/// the decoder allocates for the frame. +#[test] +fn a_gif_frame_larger_than_its_screen_is_refused_before_decoding() { + let mut gif = b"GIF89a".to_vec(); + gif.extend([1, 0, 1, 0, 0, 0, 0]); // screen 1 × 1, no color table + gif.extend([0x2C, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0]); // frame at 0,0 of 65535 × 65535 + gif.extend([2, 1, 0, 0, 0x3B]); + assert!(matches!(Raster::decode(&gif), Err(TraceError::TooLarge { .. })), "{:?}", Raster::decode(&gif).err()); + assert!(matches!(Raster::decode_to_fit(&gif), Err(TraceError::TooLarge { .. }))); +} diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 6cacf1c0d6..522f82bd2b 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -5,8 +5,10 @@ pub mod cleanup; pub mod color; pub mod compounds; pub mod contour; +pub mod cutting; pub mod document; pub mod enclosing_lasso; +pub mod image; pub mod pathtools; pub mod pen; pub mod select; @@ -24,8 +26,10 @@ pub fn plugin_menu() -> Vec { Item::Sub("Color Effects", color::menu()), Item::Sub("Compound Shapes", compounds::menu()), Item::Sub("Contour", contour::menu()), + Item::Sub("Cutting Tools", cutting::menu()), Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), + Item::Sub("Image Tools", image::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), diff --git a/crates/ui-egui/src/addons/cutting.rs b/crates/ui-egui/src/addons/cutting.rs new file mode 100644 index 0000000000..82fd2d6e3b --- /dev/null +++ b/crates/ui-egui/src/addons/cutting.rs @@ -0,0 +1,20 @@ +//! Cutting Tools in the interface: its submenu (Object › Plug-ins › Cutting Tools). Stencil +//! Bridges… opens the generic command dialog (`ui.paramDialog`, `dialogs::command`) on the options +//! of `addon.cutting.bridges`. + +use serde_json::json; + +use crate::menus::Item; + +/// Stencil Bridges' command. +pub const BRIDGES: &str = "addon.cutting.bridges"; +/// Stencil Bridges › Direction: what the command's `direction` takes, by name. +pub const BRIDGE_DIRECTIONS: &[(&str, &str)] = &[("Vertical", "vertical"), ("Horizontal", "horizontal"), ("Shortest Crossing", "shortest")]; + +/// Object › Plug-ins › Cutting Tools. +pub fn menu() -> Vec { + vec![Item::Cmd("Stencil Bridges…", BRIDGES, json!({"width": 2, "count": 1, "direction": "vertical", "keepOriginal": true}))] +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs new file mode 100644 index 0000000000..d5620f717b --- /dev/null +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -0,0 +1,54 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// Object › Plug-ins › Cutting Tools › Stencil Bridges… opens the command dialog on a 2 pt width, one +/// bridge per island, vertical bridges and Keep Original on; the direction is a list of its three +/// ways; OK cuts the bridges as one undo step, and a message shows when there are no islands. +#[test] +fn stencil_bridges_opens_its_dialog_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let outer = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].clone(); + let inner = app.run("shape.rectangle", json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [outer, inner]})).unwrap(); + let o = app.run("object.pathfinder.minusFront", json!({})).unwrap()["ids"][0].clone(); + app.run("select.set", json!({"ids": [o]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let n = steps(&app); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Cutting Tools"] && e.label == "Stencil Bridges…").expect("listed"); + 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::BRIDGES.to_string(), "Stencil Bridges".to_string())); + assert_eq!((d.f64("width", 0.0), d.f64("count", 0.0), d.str("direction"), d.bool("keepOriginal")), (2.0, 1.0, "vertical".to_string(), true)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Stencil Bridges", "Width:", "Count:", "Direction:", "Vertical", "Keep Original"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + // Each way the list offers is one the command takes. + for (_, way) in super::BRIDGE_DIRECTIONS { + assert!(app.session.execute(super::BRIDGES, &json!({"direction": way, "width": 1000})).is_ok(), "{way}"); + } + assert_eq!(steps(&app), n, "no bridge fits that wide: nothing changed"); + + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + let layers = &app.session.doc().unwrap().doc.layers; + assert!(layers.iter().any(|l| l.name.as_deref() == Some("Stencil Original") && !l.visible), "the original is on a hidden layer"); + + // Run again on the result, which has no islands left: a message, and nothing changes. + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), n + 1); + assert!(app.ui.status.contains("no islands"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/addons/image.rs b/crates/ui-egui/src/addons/image.rs new file mode 100644 index 0000000000..f8aa72b8a1 --- /dev/null +++ b/crates/ui-egui/src/addons/image.rs @@ -0,0 +1,26 @@ +//! Image Tools in the interface: its submenu (Object › Plug-ins › Image Tools). Remove Background's +//! menu item opens the generic command dialog (`ui.paramDialog`) on its options, with a Preview +//! (`dialogs::command`). + +use serde_json::json; + +use crate::menus::Item; + +/// Remove Background's command. +pub const REMOVE_BACKGROUND: &str = "addon.image.removeBackground"; +/// Remove Background › Background: what the command's `background` takes, by name. +pub const BACKGROUNDS: &[(&str, &str)] = &[("Edge Color", "edges"), ("Corner Color", "corners"), ("Picked Colors", "colors")]; +/// Remove Background › Match: what the command's `match` takes, by name. +pub const MATCHES: &[(&str, &str)] = &[("Distance", "distance"), ("Each Channel", "channels")]; + +/// Object › Plug-ins › Image Tools. +pub fn menu() -> Vec { + vec![Item::Cmd( + "Remove Background…", + REMOVE_BACKGROUND, + json!({"background": "edges", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 10, "softness": 10}), + )] +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs new file mode 100644 index 0000000000..64563e611b --- /dev/null +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -0,0 +1,131 @@ +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_engine::Session; + +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with one image open and selected: 12 × 10 pixels, white, a near-white ring one pixel in +/// (13.7 % from white) and a red block inside it. +fn app() -> VectorcraftApp { + let img = image::RgbaImage::from_fn(12, 10, |x, y| { + image::Rgba(if (3..9).contains(&x) && (3..7).contains(&y) { + [200, 0, 0, 255] + } else if (1..11).contains(&x) && (1..9).contains(&y) && (x == 1 || x == 10 || y == 1 || y == 8) { + [220, 220, 220, 255] + } else { + [255; 4] + }) + }); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("document.open", json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app +} + +/// The selected image's pixel key and bytes. +fn image(app: &VectorcraftApp) -> (String, Arc>) { + let st = app.session.doc().unwrap(); + let Some(NodeKind::Image(im)) = st.selection.objects.first().and_then(|id| st.doc.node(*id)).map(|n| &n.kind) else { panic!("an image") }; + (im.key.clone(), st.doc.images[&im.key].bytes.clone()) +} + +/// The alpha of the selected image's pixels at the corner, on the ring and in the block. +fn alphas(app: &VectorcraftApp) -> [u8; 3] { + let px = image::load_from_memory(&image(app).1).unwrap().to_rgba8(); + [(0, 0), (1, 1), (4, 4)].map(|(x, y)| px.get_pixel(x, y).0[3]) +} + +fn open(app: &mut VectorcraftApp) { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Image Tools"] && e.label == "Remove Background…").unwrap(); + assert!(item.enabled); + let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &id, p); +} + +fn show(app: &mut VectorcraftApp) -> String { + painted_text(app, |app, ui| crate::dialogs::show(app, ui.ctx())) +} + +fn set(app: &mut VectorcraftApp, key: &str, v: serde_json::Value) { + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), key.into(), v); +} + +/// Properties' Quick Actions and the Control bar offer Remove Background for a selected image, and +/// the Control bar's button removes it at once (no dialog) with the defaults, as one step. +#[test] +fn properties_and_the_control_bar_remove_the_background_at_once() { + use crate::tests_removeanchors::{at, click_control, control_frame, has, properties_frame}; + let mut app = app(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let n = steps(&app); + assert!(has(&properties_frame(&mut app, 280.0), "Remove Background"), "Properties offers it"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let bar = control_frame(&mut app, &ctx, vec![]); + click_control(&mut app, &ctx, at(&bar, "Remove Background")); + assert!(app.ui.dialog.is_none(), "it runs at once"); + assert_eq!(steps(&app), n + 1, "one undo step"); + // The defaults (tolerance and softness 10): the white goes, the near-white ring fades. + let [corner, ring, block] = alphas(&app); + assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app)); +} + +/// Object › Plug-ins › Image Tools › Remove Background… opens the command dialog on Edge Color +/// with Preview off. With Preview on the canvas shows the result for the values in the dialog, +/// each change worked out again from the image as it was; Cancel puts the image back with no step +/// of history, and OK keeps the result for the values in the dialog as one step. +#[test] +fn remove_background_previews_cancels_and_runs_on_ok() { + let mut app = app(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (image(&app), steps(&app)); + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::REMOVE_BACKGROUND.to_string(), "Remove Background".to_string())); + assert_eq!((d.str("background"), d.bool("preview")), ("edges".to_string(), false)); + assert!(crate::dialogs::accepts_field(d, "preview")); + assert_eq!((d.bool("contiguous"), d.str("match")), (true, "distance".to_string())); + let shown = show(&mut app); + for s in ["Remove Background", "Edge Color", "Contiguous", "Match", "Distance", "Tolerance", "Softness", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(image(&app), start, "no preview without the checkbox"); + + // Preview on: at tolerance 10 the ring fades; at 20 it is cleared; at 0, with no softness, + // only the white is cleared and the ring is whole again. + set(&mut app, "preview", json!(true)); + show(&mut app); + let [corner, ring, block] = alphas(&app); + assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app)); + set(&mut app, "tolerance", json!(20)); + show(&mut app); + assert_eq!(alphas(&app), [0, 0, 255]); + set(&mut app, "tolerance", json!(0)); + set(&mut app, "softness", json!(0)); + show(&mut app); + assert_eq!(alphas(&app), [0, 255, 255], "worked out again from the image as it was"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!((image(&app), steps(&app)), (start.clone(), n), "Cancel restores the image and adds no undo step"); + assert!(!app.session.in_interaction()); + + // OK: the values in the dialog, as one step. + open(&mut app); + set(&mut app, "preview", json!(true)); + set(&mut app, "tolerance", json!(20)); + show(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(alphas(&app), [0, 0, 255]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(image(&app), start); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7b69fbfb8d..3ce7143224 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -135,6 +135,7 @@ impl VectorcraftApp { last_window_title: String::new(), fullscreen_for_mode: false, graphics_adapter: None, + beacon: &crate::hang_beacon::BEACON, place: Default::default(), system_paste: false, clipboard_image_request: None, diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index d97d111812..16e8a14cc1 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -73,6 +73,7 @@ fn substitute_warnings_follow_current_font_inventory() { 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 { + self.beacon.command(id); let touch_workspace = self.session.prefs.touch_workspace; // A file dialog it shows off the UI thread runs it again with the path picked. let result = if self.picks.is_entry_free() { @@ -109,6 +110,30 @@ impl VectorcraftApp { } } + /// Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align, + /// Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols + /// panel act on the active artboard, the view's, which the app adds to command `id`'s `params` as + /// `artboard`. A batch passes it on to those steps. While the Artboard tool has several artboards + /// selected, the paste commands get those as `artboards` instead, and paste a copy on each; in a + /// document without artboards they get neither. + fn add_active_artboard(&self, id: &str, params: &mut Value) { + let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); + if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch") + && params.get("artboard").is_none() + && !(paste && params.get("artboards").is_some()) + && self.view().is_some() + && let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !paste) + && let Some(p) = params.as_object_mut() + { + let picked = panels::artboards::picked(self, n); + if paste && picked.len() > 1 { + p.insert("artboards".into(), serde_json::json!(picked)); + } else { + p.insert("artboard".into(), serde_json::json!(panels::artboards::selected(self, n))); + } + } + } + /// [`Self::run`] it, inside what asks for file dialogs. fn run_now(&mut self, id: &str, params: Value) -> Result { crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); @@ -129,18 +154,7 @@ impl VectorcraftApp { return r; } let mut params = params; - // Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align, - // Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols - // panel act on the active artboard, the view's, which the app passes as `artboard`. A batch passes - // it on to those steps. - if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch") - && params.get("artboard").is_none() - && self.view().is_some() - && let Some(n) = self.session.active().map(|d| d.doc.artboards.len()) - && let Some(p) = params.as_object_mut() - { - p.insert("artboard".into(), serde_json::json!(panels::artboards::selected(self, n))); - } + self.add_active_artboard(id, &mut params); // Edit Symbol from the Symbols panel in a document without artboards centers the symbol's // art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit // steps too. diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 8674942538..3bb451bfd6 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,4 +1,5 @@ use super::{VectorcraftApp, io, place}; +use crate::services::Inbox; impl VectorcraftApp { /// A file dialog is open off the UI thread (a sheet on macOS, [`picks`]): what asked for it runs @@ -13,13 +14,25 @@ impl VectorcraftApp { self.services.dialogs_are_sheets && self.file_dialog_open() } - pub(super) fn drain_inbox(&mut self) { - let arrived: Vec<(String, Vec)> = - self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - for (name, bytes) in arrived { - if let Err(e) = io::open_bytes(self, &name, &bytes, None) { - io::report_open_error(self, &name, &e); - } + pub(crate) fn drain_inbox(&mut self) { + fn take(q: Option<&Inbox>) -> Vec<(String, Vec)> { + q.map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default() + } + let answers = self.services.picked_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))); + // The web's file picker answers for automation when automation opened it; the page's script + // is automation. + let mut arrived: Vec<_> = take(self.services.inbox.as_ref()).into_iter().map(|f| (f, false)).collect(); + for answer in answers.unwrap_or_default() { + let automated = self.picks.answer_web_open(); + arrived.extend(answer.map(|f| (f, automated))); + } + arrived.extend(take(self.services.page_inbox.as_ref()).into_iter().map(|f| (f, true))); + for ((name, bytes), automated) in arrived { + crate::picks::as_automated(self, automated, |app| { + if let Err(e) = io::open_bytes(app, &name, &bytes, None) { + io::report_open_error(app, &name, &e); + } + }); } place::drain(self); } diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 8f4ce246f5..b27bb494aa 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -36,6 +36,13 @@ impl VectorcraftApp { self.ui.answering_control || self.synthetic_frame } + /// Did automation ask for what is being handled now: [`Self::automation_is_acting`], or the + /// answer of a file dialog that automation opened ([`crate::picks::as_automated`]), even when a + /// person picked the file in it? + pub(crate) fn automation_asked(&self) -> bool { + self.automation_is_acting() || self.picks.automated() + } + /// Run a Help link command and open the URL it returns. pub fn open_link(&mut self, id: &str) { if let Ok(v) = self.run(id, serde_json::json!({})) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 56f121ad6d..6e6806e075 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -50,7 +50,7 @@ use fill::fill_uncovered; use fill::{fill_view, polygon_area}; #[cfg(test)] use grid::ruler_rects; -use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, textured_quad, view_bounds}; +use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, rulers_hidden, textured_quad, view_bounds}; pub(crate) use grid::{RulerScale, checker_texture, ruler_label, ruler_origin_dragging}; #[cfg(test)] pub(crate) use grid::{TRANSPARENCY_GRID, vertical_label_height}; @@ -283,7 +283,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.ctx().request_repaint_after_secs(secs as f32); } let hover_still = wait.is_none(); - let origin_preview = if app.ui.view.rulers && app.ui.screen_mode < 3 { ruler_input(app, ui, full, rect, &xf) } else { None }; + let origin_preview = if app.ui.view.rulers && app.ui.screen_mode < 3 { ruler_input(app, ui, full, rect, &xf) } else { rulers_hidden(app, ui) }; crate::document_drag::drop_on_canvas(app, &resp, &xf); panel_drop(app, ui, &resp, &xf); // In Presentation Mode a right click or a long touch opens no context menu. @@ -1119,11 +1119,12 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, let look = LineLook::guides(&app.session.prefs, t); let picked = LineLook { color: t.selection, ..look }; let labels = guide_labels(doc); - let selected: &[usize] = &st.selection.guides; + let selected: &[vectorcraft_doc::NodeId] = &st.selection.guides; let key = st.selection.key_guide; let view = view_bounds(xf); // Guides on a hidden layer hide with it. - for (i, g) in doc.guides.iter().enumerate().filter(|(_, g)| doc.guide_shown(g)) { + for g in doc.ruler_guides().iter().filter(|g| doc.guide_shown(g)) { + let Some(i) = g.id else { continue }; let at = |along: f64| xf.to_screen(if g.vertical { Point::new(g.pos, along) } else { Point::new(along, g.pos) }); // An artboard guide runs across its artboard, a canvas guide across the window (the part // of its document line that the canvas shows, turned with the view). diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index c5bbe90882..cd98a214b7 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -53,7 +53,10 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the /// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on -/// top of its appearance). A chip follows the pointer meanwhile. +/// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` +/// for a brush library's). A Brushes panel scatter, art or pattern +/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`). A chip +/// follows the pointer meanwhile. pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) { crate::panels::swatches::drag_preview(app, ui.ctx()); let Some(pos) = ui.input(|i| i.pointer.interact_pos()) else { return }; @@ -86,7 +89,19 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } - let Some(hit) = hit_at(app, xf.to_doc(pos), xf.zoom) else { return }; + let hit = hit_at(app, xf.to_doc(pos), xf.zoom); + // A scatter, art or pattern brush from the Brushes panel dropped where there is no art: a copy + // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. + if let (None, widgets::PanelDrag::Brush { name, def }) = (&hit, &*d) + && matches!(def["type"].as_str(), Some("scatter" | "art" | "pattern")) + { + let at = xf.to_doc(pos); + if let Err(e) = app.run("brush.placeArt", json!({"name": name, "x": at.x, "y": at.y})) { + app.status(e); + } + return; + } + let Some(hit) = hit else { return }; let Some(st) = app.session.active() else { return }; let (cmd, params) = match &*d { widgets::PanelDrag::Paint { params, .. } => { diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 930daf8fd4..1a385d5642 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -293,9 +293,7 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response, let tool = app.session.tool_id(); let Some(st) = app.session.active().filter(|_| matches!(tool, "selection" | "directSelection" | "groupSelection")) else { return false }; // The tool's interaction while it moves (or Alt-copies) the selection. - if !st.interaction.as_ref().is_some_and(|i| i.label == "Move" || i.label == "Copy") { - return false; - } + let Some(it) = st.interaction.as_ref().filter(|i| i.label == "Move" || i.label == "Copy") else { return false }; if tool != "selection" && st.selection.objects.iter().any(|id| st.selection.partial(*id).is_some() || st.selection.segments.contains_key(id)) { return false; } @@ -305,7 +303,9 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response, if on_canvas(ui, resp, p) && ui.input(|i| i.pointer.has_pointer()) { return false; } - let ids = st.selection.objects.clone(); + // The art the drag started with: the release rolls the move back to it, and an Alt-copy's + // copies, selected while it previews, go with that. + let ids = it.selection.objects.clone(); egui::DragAndDrop::set_payload(ui.ctx(), widgets::PanelDrag::Art(ids)); true } diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 7f000ee787..2c99c618db 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -181,8 +181,9 @@ pub(super) fn ruler_rects(full: egui::Rect) -> [egui::Rect; 3] { /// it makes none. A double-click on a ruler (both clicks on that ruler) makes a guide at the /// pointer, across the ruler's axis (a vertical one on the top ruler, a horizontal one on the /// left; swapped in a view turned 90°, where the rulers read the other document axis, and the -/// nearer axis in between), unsnapped, as one `guide.add` and so one undo step. The corner drags the rulers' origin or resets it on a -/// double-click. +/// nearer axis in between), unsnapped, as one `guide.add` and so one undo step. The corner drags +/// the rulers' origin, snapped as a drawn point is (`Session::ruler_origin_drag`), or resets it on +/// a double-click. pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, canvas: egui::Rect, xf: &Xf) -> Option { let [top, left, corner] = ruler_rects(full); // Right-click on a ruler or the origin box: the document units, to swap between them as @@ -274,9 +275,17 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c let mut preview = None; if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option, bool)>(drag_id)) { cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape)); - let at = corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p)); + let pointer = + corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p)); + // The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid). + let at = if cancelled { + app.session.end_ruler_origin_drag(); + None + } else { + app.session.ruler_origin_drag(pointer, app.view_info()) + }; if corner.drag_stopped_by(egui::PointerButton::Primary) { - ui.data_mut(|d| d.remove::<(Option, bool)>(drag_id)); + end_ruler_origin_drag(app, ui); if !cancelled && let Some(at) = at && let Err(e) = app.run("document.setRulerOrigin", json!({"x": at.x, "y": at.y, "artboard": app.view().map_or(0, |v| v.artboard)})) @@ -284,7 +293,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c app.status(e.to_string()); } } else if !ui.input(|i| i.pointer.primary_down()) { - ui.data_mut(|d| d.remove::<(Option, bool)>(drag_id)); + end_ruler_origin_drag(app, ui); } else { ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled))); if !cancelled { @@ -295,6 +304,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c preview } +/// The rulers are hidden (View › Rulers, Presentation Mode): a drag of their origin they were +/// showing for is cancelled, so its snapping guides don't stay on the canvas. Nothing previews. +pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option { + if ruler_origin_dragging(ui.ctx()) { + end_ruler_origin_drag(app, ui); + } + None +} + +/// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go. +fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) { + ui.data_mut(|d| d.remove::<(Option, bool)>(ruler_origin_drag_id())); + app.session.end_ruler_origin_drag(); +} + /// The key of the ruler origin drag's state in egui's temporary data. fn ruler_origin_drag_id() -> egui::Id { egui::Id::unique("ruler-origin-drag") diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index fcda53def0..8ff6faaf79 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -123,7 +123,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: // 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())) + let show_box = (app.session.tool_id() == "selection" || lends_selection || (shape_tool && (!app.session.tool_busy() || resizing))) && (resizing || !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()); @@ -238,7 +238,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: rotate_all_widget(p, xf, tool, &st.doc, &st.selection); } -/// The Rotate All and Space widgets (Selection and Objects on Path tools, one Objects on Path +/// The Rotate All, Space and Move All widgets (Selection and Objects on Path tools, one Objects on Path /// group selected). The Rotate All widget is joined by a line to the first object's attachment /// point. It stays while dragged. fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { @@ -253,6 +253,7 @@ fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_d p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); } space_widget(p, xf, doc, selection); + move_all_widget(p, xf, doc, selection); } /// The Space widget (beside the Rotate All widget, with two or more objects on the path): a square @@ -267,6 +268,19 @@ fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, sel p.rect_stroke(r, 0.0, Stroke::new(1.0, color), StrokeKind::Inside); } +/// The Move All widget (beside the Rotate All widget, when the objects have room to move along the +/// path): a diamond below the first object joined by a line to its attachment point. It stays while +/// dragged. +fn move_all_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { + use vectorcraft_tools::objects_on_path::{MOVE_ALL_HALF_PX, MoveAllWidget}; + let Some(w) = MoveAllWidget::of(doc, selection, xf.zoom) else { return }; + let (on, c, color) = (xf.to_screen(w.first), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + let h = MOVE_ALL_HALF_PX; + p.line_segment([on, c], Stroke::new(1.0, color)); + let corners = vec![c + vec2(0.0, -h), c + vec2(h, 0.0), c + vec2(0.0, h), c + vec2(-h, 0.0)]; + p.add(Shape::convex_polygon(corners, Color32::WHITE, Stroke::new(1.0, color))); +} + /// Record where the Type tool's IME candidate window goes this pass, if it has an editor. /// /// The descriptor itself is observed once at the end of the pass (`crate::ime::end_of_pass`), diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 0ccba73dee..da4edbf54e 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -96,11 +96,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } else { // Edit Path: the Direct Selection tool, to edit the path's anchors. let edit_path = || (tl!("Edit Path"), "dc-direct", "tool.select", json!({"tool": "directSelection"})); - // As in the reference app, an image offers Image Trace and Crop Image, and traced art offers - // Expand (). + // As in the reference app, an image offers Image Trace, Crop Image and Remove Background, and + // traced art offers Expand (, + // ). if n == 1 && is_image { items.push((tl!("Image Trace"), "image", TASK_BAR_IMAGE_TRACE, none())); items.push((tl!("Crop Image"), "dc-pf-crop", "ui.cropImage", none())); + items.push((tl!("Remove Background"), "eraser", crate::addons::image::REMOVE_BACKGROUND, none())); } // Direct-selected anchors take the place of a path's Offset Path and Simplify. For them the bar // offers Remove, Connect, Cut and Convert to corner or smooth, as the reference app does @@ -151,7 +153,16 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { match kind { TextKind::Area { .. } => items.push((tl!("Convert To Point Type"), "type", "type.convertToPointType", none())), TextKind::Point => items.push((tl!("Convert To Area Type"), "dc-type-area", "type.convertToAreaType", none())), - TextKind::OnPath { .. } => items.push((tl!("Type on a Path Options"), "dc-type-path", "type.pathOptions", none())), + TextKind::OnPath { .. } => { + items.push((tl!("Type on a Path Options"), "dc-type-path", "type.pathOptions", none())); + center_on_path_items(app, &mut items); + } + } + // Dynamic Text turns on or off for type on a path and area type (Block), as the Type menu's item does; + // left out for point type and type in a thread, which is VectorCraft's own rule + // (). + if crate::menus::enabled(app, "type.dynamicText") { + items.push((tl!("Dynamic Text"), "maximize-2", "type.dynamicText", none())); } } else if is_image { // Offset Path and Simplify don't apply to an image. @@ -342,6 +353,18 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } } +/// The Contextual Task Bar's Center on Top and Center on Bottom, as in the Type menu, for type on a +/// closed path. +fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>) { + for (label, icon, id) in + [(tl!("Center on Top"), "dc-al-top", "type.pathCenter.top"), (tl!("Center on Bottom"), "dc-al-bottom", "type.pathCenter.bottom")] + { + if crate::menus::enabled(app, id) { + items.push((label, icon, id, json!({}))); + } + } +} + /// The Contextual Task Bar's Image Trace button: a trace with the Default preset. const TASK_BAR_IMAGE_TRACE: &str = "taskBar.imageTrace"; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 81008bb0be..503178a22b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1173,6 +1173,56 @@ fn a_click_just_outside_the_canvas_does_not_reach_the_tool() { assert_eq!(selected(&app), vec![vectorcraft_doc::NodeId(id)]); } +/// The box-drawing shape tools show the bounding box of the shape just drawn (#5477). A drag of +/// its bottom-right handle with the tool still active scales that shape, as with the Selection +/// tool, rather than drawing a second shape from the handle. +#[test] +fn a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle() { + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for tool in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let drag = |app: &mut VectorcraftApp, a: Pos2, b: Pos2| { + for ev in [ + egui::Event::PointerMoved(a), + button(a, true), + egui::Event::PointerMoved(a.lerp(b, 0.5)), + egui::Event::PointerMoved(b), + button(b, false), + ] { + frame(app, &ctx, vec![ev]); + } + frame(app, &ctx, vec![]); + }; + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + drag(&mut app, xf.to_screen(Point::new(150.0, 120.0)), xf.to_screen(Point::new(210.0, 170.0))); + let objects = |app: &VectorcraftApp| { + let mut n = 0; + app.session.active().unwrap().doc.walk(|node| n += usize::from(node.path_data().is_some())); + n + }; + assert_eq!(objects(&app), 1, "{tool}: the drag draws one shape"); + let before = app.selection_box().unwrap_or_else(|| panic!("{tool}: the shape just drawn shows its box")); + // The bottom-right handle, dragged 40 pt along the box's width and 30 pt along its height + // (a polygon's or star's box turns with the shape). + let (corner, to) = (Point::new(before.rect.x1, before.rect.y1), Point::new(before.rect.x1 + 40.0, before.rect.y1 + 30.0)); + drag(&mut app, xf.to_screen(before.to_doc() * corner), xf.to_screen(before.to_doc() * to)); + let after = app.selection_box().unwrap_or_else(|| panic!("{tool}: the shape stays selected")); + let label = app.session.active().and_then(|st| st.history.undo.last().map(|e| e.label.clone())); + assert_eq!(objects(&app), 1, "{tool}: no second shape, last step {label:?}"); + assert!( + (after.rect.width() - before.rect.width() - 40.0).abs() < 0.5 && (after.rect.height() - before.rect.height() - 30.0).abs() < 0.5, + "{tool}: {:?} -> {:?}, last step {label:?}", + before.rect, + after.rect + ); + assert_eq!(label.as_deref(), Some("Scale"), "{tool}"); + } +} + #[test] fn a_drag_from_a_ruler_onto_the_canvas_makes_a_guide() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -1192,7 +1242,7 @@ fn a_drag_from_a_ruler_onto_the_canvas_makes_a_guide() { frame(app, &ctx, vec![egui::Event::PointerMoved(to)]); frame(app, &ctx, vec![button(to, false)]); }; - let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect::>(); + let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect::>(); // From the top ruler: a horizontal guide where the button was released. let to = pos2(rect.center().x, rect.top() + 120.0); drag(&mut app, pos2(rect.center().x, rect.top() - RULER / 2.0), to); @@ -1234,8 +1284,8 @@ fn artboard_guide_label_colors_only_its_own_guides() { { let st = app.session.active_mut().unwrap(); let doc = std::sync::Arc::make_mut(&mut st.doc); - let last = doc.guides.len() - 1; - doc.guides[last].artboard = Some(gone); + let last = doc.ruler_guides().last().and_then(|g| g.id).unwrap(); + assert!(doc.edit_ruler_guide(last, |g| g.artboard = Some(gone))); } app.ui.view.guides = true; let ctx = egui::Context::default(); @@ -1304,7 +1354,7 @@ fn a_guide_dragged_out_of_a_ruler_shows_while_dragged() { }; assert!(shapes(&mut app, &ctx).iter().any(across), "real-time drawing {real_time}: the guide shows while dragged"); frame(&mut app, &ctx, vec![button(at, false)]); - assert_eq!(app.session.active().unwrap().doc.guides.len(), 1, "real-time drawing {real_time}: released, it is made"); + assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "real-time drawing {real_time}: released, it is made"); } } @@ -1383,7 +1433,7 @@ fn new_ruler_guides_follow_alt_through_preview_release_and_undo() { frame(&mut app, &ctx, vec![button(from, true, initially_alt)]); frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); let assert_guide = |app: &VectorcraftApp, alt: bool, pos: Point| { - let guides = &app.session.active().unwrap().doc.guides; + let guides = &app.session.active().unwrap().doc.ruler_guides(); assert_eq!(guides.len(), 1); assert_eq!(guides[0].vertical, source_vertical != alt); let expected = if source_vertical != alt { pos.x } else { pos.y }; @@ -1463,7 +1513,7 @@ fn new_ruler_guide_alt_cancel_keeps_document_and_redo() { frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::ALT), Event::PointerMoved(from)]); frame(&mut app, &ctx, vec![button(from, true)]); frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); - let guides = &app.session.active().unwrap().doc.guides; + let guides = &app.session.active().unwrap().doc.ruler_guides(); assert_eq!(guides.len(), 1); assert_eq!(guides[0].vertical, !source_vertical); let artboard = (tool == "artboard").then_some(before.artboards[0].id); @@ -1474,7 +1524,7 @@ fn new_ruler_guide_alt_cancel_keeps_document_and_redo() { assert_eq!(history(&app), before_history); app.session.execute("edit.redo", &json!({})).unwrap(); assert!(app.session.active().unwrap().doc.art_bounds().is_some()); - assert!(app.session.active().unwrap().doc.guides.is_empty()); + assert!(app.session.active().unwrap().doc.ruler_guides().is_empty()); } } } @@ -1513,14 +1563,14 @@ fn cmd_ruler_drags_make_artboard_guides_with_the_preference_on() { let board = app.session.active().unwrap().doc.artboards[0].id; drag(&mut app, Point::new(80.0, 120.0)); let st = app.session.active().unwrap(); - assert_eq!(st.doc.guides.len(), 1, "vertical {source_vertical}, on {on}"); - assert_eq!(st.doc.guides[0].vertical, source_vertical); - assert_eq!(st.doc.guides[0].artboard, on.then_some(board), "vertical {source_vertical}, on {on}"); + assert_eq!(st.doc.ruler_guides().len(), 1, "vertical {source_vertical}, on {on}"); + assert_eq!(st.doc.ruler_guides()[0].vertical, source_vertical); + assert_eq!(st.doc.ruler_guides()[0].artboard, on.then_some(board), "vertical {source_vertical}, on {on}"); // Beyond the artboard's right or bottom edge. let beyond = xf.to_doc(rect.right_bottom() - egui::vec2(2.0, 2.0)); assert!(beyond.x > 400.0 && beyond.y > 300.0, "{beyond:?}"); drag(&mut app, beyond); - assert_eq!(app.session.active().unwrap().doc.guides.len(), if on { 1 } else { 2 }, "vertical {source_vertical}, on {on}"); + assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), if on { 1 } else { 2 }, "vertical {source_vertical}, on {on}"); } } } @@ -1547,7 +1597,7 @@ fn guides_from_the_rulers_snap_and_artboard_guides_span_their_artboard() { frame(app, &ctx, vec![egui::Event::PointerMoved(to)]); frame(app, &ctx, vec![button(to, false)]); }; - let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect::>(); + let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect::>(); // 3 px off the middle of the top and bottom sides: onto the line through them. let mid = xf.to_screen(Point::new(200.0, 150.0)); drag(&mut app, pos2(rect.left() - RULER / 2.0, mid.y), mid + vec2(3.0, 40.0)); @@ -1596,7 +1646,7 @@ fn the_selection_tool_moves_and_deletes_ruler_guides() { frame(app, &ctx, vec![egui::Event::PointerMoved(to)]); frame(app, &ctx, vec![button(to, false)]); }; - let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect::>(); + let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| (g.vertical, g.pos)).collect::>(); // Two guides out of the rulers. let (h, v) = (pos2(rect.center().x + 30.0, rect.center().y + 20.0), pos2(rect.center().x - 40.0, rect.center().y)); drag(&mut app, pos2(h.x, rect.top() - RULER / 2.0), h); @@ -1607,7 +1657,7 @@ fn the_selection_tool_moves_and_deletes_ruler_guides() { drag(&mut app, h, to); let st = app.session.active().unwrap(); assert_eq!(guides(&app), [(false, xf.to_doc(to).y), (true, xf.to_doc(v).x)]); - assert_eq!((st.selection.guides.clone(), st.selection.objects.clone()), (vec![0], vec![])); + assert_eq!((vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides), st.selection.objects.clone()), (vec![0], vec![])); assert_eq!(st.history.undo.last().unwrap().label, "Move Guide"); let picked = Tokens::get(&ctx).selection; let s = shapes(&mut app, &ctx); @@ -2800,10 +2850,13 @@ fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { "{old_rot}° -> {new_rot}°, DPI {old_ppp} -> {new_ppp}, pixel={pixel}: {vertex:?}" ); } - // Deliver the actual replacement and verify that it replaces the cached key. + // Deliver the actual replacement and verify that it replaces the cached key. The frame + // reports a slow render: when a parallel test makes a placed document's bitmap, the key's + // process-wide `placed` generation moves, and the next frame goes to the controlled worker + // instead of rendering over the delivered frame on this thread. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false }).unwrap(); + completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false }).unwrap(); frame(&mut app, size, new_ppp); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived"); } @@ -4806,6 +4859,45 @@ fn a_selected_objects_on_path_group_shows_its_space_widget() { assert_eq!(widgets(&mut app), 0, "one object"); } +/// A selected Objects on Path group whose objects have room to move along the path shows its Move +/// All widget, a white diamond below its first object, with the Selection and Objects on Path tools; +/// objects spread evenly to both ends of an open path have no room, and show none. +#[test] +fn a_selected_objects_on_path_group_shows_its_move_all_widget_when_it_has_room() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let line = id(app.session.execute("shape.line", &json!({"x1": 20, "y1": 200, "x2": 380, "y2": 200})).unwrap()); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 80, "y": 40, "width": 20, "height": 20})).unwrap()); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = id(app.session.execute("object.objectsOnPath.attach", &json!({"path": line})).unwrap()); + let ctx = egui::Context::default(); + // A diamond: its top and bottom corners one above the other, its full height apart. + let diamond = |d: &egui::epaint::PathShape| { + let h = 2.0 * vectorcraft_tools::objects_on_path::MOVE_ALL_HALF_PX; + let [top, _, bottom, _] = d.points[..] else { return false }; + d.closed && d.fill == Color32::WHITE && top.x == bottom.x && (bottom.y - top.y - h).abs() < 1e-3 + }; + let widgets = |app: &mut VectorcraftApp| shapes(app, &ctx).iter().filter(|s| matches!(s, Shape::Path(d) if diamond(d))).count(); + app.select_tool("selection"); + assert_eq!(widgets(&mut app), 0, "Auto: the objects reach both ends"); + app.session.execute("object.objectsOnPath.options", &json!({"ids": [g], "spacing": 60})).unwrap(); + assert_eq!(widgets(&mut app), 1); + app.select_tool("objectsOnPath"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("directSelection"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(widgets(&mut app), 0, "an object in the group, not the group"); + // One object can move along the path whatever its Space. + app.session.execute("object.objectsOnPath.options", &json!({"ids": [g], "spacing": "auto"})).unwrap(); + app.run("edit.clear", json!({"ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + assert_eq!(widgets(&mut app), 1, "one object"); +} + /// The shapes Type → Show Hidden Characters draws in one frame, seen through `xf`. fn hidden_chars(app: &mut VectorcraftApp, ctx: &egui::Context, xf: &Xf) -> Vec { let raw = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; @@ -6891,6 +6983,49 @@ fn a_brush_dropped_on_a_path_is_applied_to_it() { assert_eq!(brush(&app).as_deref(), Some("Arrow")); } +#[test] +fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("path.create", &json!({"anchors": [{"x": 100, "y": 150}, {"x": 300, "y": 150}]})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, name: &str, at: Point| { + let def = app.session.execute("brush.get", &json!({"name": name})).unwrap(); + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Brush { name: name.into(), def }); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let undo = app.session.active().unwrap().history.undo.len(); + // A calligraphic brush has no art: nothing. + drop(&mut app, "3 pt. Round", Point::new(200.0, 250.0)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + // An art brush: a copy of its art, centered where it lands, selected. + drop(&mut app, "Arrow", Point::new(200.0, 250.0)); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo + 1); + assert_eq!(st.history.undo.last().unwrap().label, "Place Brush Art"); + let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; + let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); + assert!((b.center() - Point::new(200.0, 250.0)).hypot() < 0.1, "{b:?}"); + // A scatter brush and a pattern brush (its tiles, in one group) place their art too. + for (i, name) in ["Dots", "Chain"].into_iter().enumerate() { + let at = Point::new(80.0 + 200.0 * i as f64, 60.0); + drop(&mut app, name, at); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo + 2 + i, "{name}"); + let [placed] = st.selection.objects.as_slice() else { panic!("{name}: one object selected: {:?}", st.selection.objects) }; + let n = st.doc.node(*placed).unwrap(); + assert!((n.geometric_bounds().unwrap().center() - at).hypot() < 0.1, "{name}"); + if name == "Chain" { + assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Side Tile")); + } + } +} + #[test] fn a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -7074,6 +7209,36 @@ fn art_moved_off_the_canvas_waits_and_drops_on_the_panel() { assert_eq!(st.history.undo.len(), undo); } +/// Art Alt-dragged off the canvas (a copy while it moves there) reaches the panels as the art the +/// drag started with, which is what stays when the release over a panel takes the copy back. +#[test] +fn art_alt_dragged_off_the_canvas_reaches_the_panels_as_the_original() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + app.select_tool("selection"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let before = app.session.active().unwrap().doc.clone(); + let button = |pos: Pos2, pressed: bool| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::ALT }; + let start = xf.to_screen(Point::new(100.0, 100.0)); + frame(&mut app, &ctx, vec![Event::ModifiersChanged(Modifiers::ALT), Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(start + vec2(40.0, 0.0))]); + let st = app.session.active().unwrap(); + assert_eq!(st.interaction.as_ref().map(|i| i.label.as_str()), Some("Copy")); + assert!(!st.selection.objects.contains(&id), "the copy is selected while it moves"); + frame(&mut app, &ctx, vec![Event::PointerMoved(pos2(850.0, 100.0))]); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&widgets::PanelDrag::Art(vec![id]))); + frame(&mut app, &ctx, vec![button(pos2(850.0, 100.0), false)]); + let st = app.session.active().unwrap(); + assert!(st.interaction.is_none()); + assert_eq!(*st.doc, *before, "the copy goes, the original stays"); + assert!(st.doc.node(id).is_some()); +} + /// #4233: the Direct and Group Selection tools hand art they move whole to the panels too (Asset /// Export, Graphic Styles…), as the Selection tool does; the move waits and nothing is recorded. #[test] @@ -9188,6 +9353,33 @@ fn the_task_bar_traces_an_image_then_expands_the_trace() { assert_eq!(images, 0, "only the traced paths are kept"); } +/// For a selected image the Contextual Task Bar offers Remove Background, which clears the +/// background in the image's pixels at once (no dialog) with the command's defaults. +#[test] +fn the_task_bar_removes_a_selected_images_background() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let img = + image::RgbaImage::from_fn(20, 20, |x, y| image::Rgba(if (6..14).contains(&x) && (6..14).contains(&y) { [200, 0, 0, 255] } else { [255; 4] })); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let data = vectorcraft_format::base64_encode(&png); + app.run("file.place", json!({"name": "dot.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + let labels = task_bar_labels(&mut app, &ctx); + let at = labels.iter().find(|(t, _)| t == "Remove Background").map(|(_, r)| r.center()).expect("Remove Background is offered"); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + assert!(app.ui.dialog.is_none(), "it runs at once"); + let st = app.session.active().unwrap(); + let Some(NodeKind::Image(im)) = st.selection.objects.first().and_then(|id| st.doc.node(*id)).map(|n| &n.kind) else { panic!("an image") }; + let px = image::load_from_memory(&st.doc.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0[3]), (0, 255), "the white background is cleared, the red dot kept"); +} + /// The labels the Contextual Task Bar draws in a headless frame (after one to lay it out), with /// their rects; none while it isn't shown. The SVG loaders are installed so the icons draw as /// images instead of egui's ⚠ placeholder, which the label list would otherwise pick up. @@ -9512,7 +9704,7 @@ fn ruler_guide_origin_ui(alt: bool, cancel: bool) { frame(&mut app, &ctx, vec![button(from, true)]); frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); let check = |app: &VectorcraftApp, switched: bool, expected: Point| { - let guides = &app.session.active().unwrap().doc.guides; + let guides = &app.session.active().unwrap().doc.ruler_guides(); assert_eq!(guides.len(), 1); let vertical = source_vertical != switched; assert_eq!(guides[0].vertical, vertical); @@ -9522,7 +9714,7 @@ fn ruler_guide_origin_ui(alt: bool, cancel: bool) { assert_eq!(history(&app).0, original_history.0, "preview has no undo entry"); if cancel { // Cancellation is a baseline positive control, independent of snap correctness. - assert_eq!(app.session.active().unwrap().doc.guides.len(), 1); + assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1); frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, false)]); assert_eq!(app.session.active().unwrap().doc, before); assert_eq!(app.session.active().unwrap().selection, selection); @@ -9543,7 +9735,17 @@ fn ruler_guide_origin_ui(alt: bool, cancel: bool) { check(&app, alt, release); let st = app.session.active().unwrap(); assert_eq!(st.doc.ruler_origin_for(0), origin); - assert_eq!(st.doc.layers, before.layers, "the rectangle tool draws no artwork"); + let art = |d: &vectorcraft_doc::Document| { + d.layers + .iter() + .map(|l| { + let mut l = vectorcraft_doc::Node::clone(l); + l.strip_ruler_guides(); + l + }) + .collect::>() + }; + assert_eq!(art(&st.doc), art(&before), "the rectangle tool draws no artwork"); assert_eq!(st.selection, selection); assert_eq!(history(&app), (original_history.0 + 1, 0, true)); assert_eq!(st.history.undo.last().unwrap().label, "New Guide"); @@ -9621,8 +9823,9 @@ fn ruler_guide_origin_tooltip_matches_selected_guide_fields() { frame(&mut app, &ctx, vec![Event::PointerMoved(from)]); frame(&mut app, &ctx, vec![button(from, true)]); frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); - assert!((app.session.active().unwrap().doc.guides[0].pos - target).abs() < 1e-4); - assert_eq!(app.session.active().unwrap().selection.guides, vec![0]); + assert!((app.session.active().unwrap().doc.ruler_guides()[0].pos - target).abs() < 1e-4); + let st = app.session.active().unwrap(); + assert_eq!(vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides), vec![0]); // Observe the real selected-guide field; no expected strings are inserted into UI state. let fields = egui::Context::default(); crate::theme::install_fonts(&fields); @@ -9652,7 +9855,7 @@ fn ruler_guide_origin_tooltip_matches_selected_guide_fields() { assert_eq!(app.session.active().unwrap().history.undo.len(), undo); frame(&mut app, &ctx, vec![button(to, false)]); assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); - assert!((app.session.active().unwrap().doc.guides[0].pos - target).abs() < 1e-4, "stored coordinate remains absolute"); + assert!((app.session.active().unwrap().doc.ruler_guides()[0].pos - target).abs() < 1e-4, "stored coordinate remains absolute"); app.run("edit.undo", json!({})).unwrap(); assert_eq!(app.session.active().unwrap().doc, before); } diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index f49851ad2c..513aa54df4 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -20,7 +20,7 @@ mod tabs; #[cfg(test)] use control_bar::ISOLATION_BUTTON; -pub use control_bar::{AnchorControls, CONTROL_BAR_EDGES, anchor_buttons, anchor_controls, control_bar}; +pub use control_bar::{AnchorControls, CONTROL_BAR_EDGES, CONTROL_BAR_GROUPS, anchor_buttons, anchor_controls, control_bar, read_hidden_groups}; #[cfg(test)] use hints::hint_segments; pub use hints::{hint_bar, hint_strings}; @@ -72,8 +72,9 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // With the macOS menu bar the menus are at the top of the screen instead. let menus_end = if app.services.native_menu.is_some() { ui.cursor().min.x } else { menus::menu_bar(app, ui) }; // The right-side group fills the space after the menus from the right; when it runs - // short, Discord goes first (it is also under Help), then the search icon (the palette - // stays under its shortcut), then the workspace switcher narrows. + // short, Discord goes first (it is also under Help), then Explore tutorials (also + // Window › Learn), then the search icon (the palette stays under its shortcut), then + // the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if custom { full.right() - titlebar::WIDTH - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -97,7 +98,9 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let icon = 28.0; let search = switcher && room >= 64.0 + 8.0 + gap + icon; let ws_w = ws_w.min(room - 8.0 - gap - if search { icon } else { 0.0 }).max(64.0); - let discord = search && room >= ws_w + 8.0 + gap + icon + 10.0 + gap + crate::community::discord_width(ui, false); + // Explore tutorials, beside the search icon, opens the Learn panel. + let learn = search && room >= ws_w + 8.0 + 2.0 * (gap + icon); + let discord = learn && room >= ws_w + 8.0 + 2.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; // Workspace switcher: shows the current workspace, opens Window → Workspace. @@ -127,6 +130,14 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.palette_query.clear(); } } + if learn { + let shown = crate::panels::learn::visible(&app.ui); + if widgets::icon_button(ui, "graduation-cap", tl!("Explore tutorials"), shown, icon).clicked() + && let Err(e) = app.run("window.learn", json!({})) + { + app.ui.status = e; + } + } if discord { ui.add_space(10.0); crate::community::discord_button(app, ui, false); diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 1c326609ee..53bfb98c1c 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -180,7 +180,8 @@ fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { 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. +/// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and +/// the height of its Align To menu. const BUTTON: f32 = 24.0; /// The space ahead of the separator that ends a group of the Control bar's controls. @@ -218,55 +219,130 @@ fn separator_width(ui: &Ui) -> f32 { } /// 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) } +/// and Preferences with nothing selected, or none while the panel menu has that group off. The +/// groups ahead of them (the Paragraph section, area type's vertical alignment, the Align buttons, +/// the Align To menu and the 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(app: &VectorcraftApp, ui: &Ui, nothing_selected: bool) -> f32 { + if nothing_selected { + if group_on(app, "documentOptions") { DOCUMENT_SETUP_WIDTH + ui.spacing().item_spacing.x + PREFERENCES_WIDTH } else { 0.0 } + } else if group_on(app, "transform") { + crate::panels::transform::link_width(ui) + } else { + 0.0 + } } /// 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. +/// Setup and Preferences, drawn here, end the bar, or the Transform group is off). The groups are +/// the Paragraph section and area type's vertical alignment (#3759), then the Align buttons, the +/// Align To menu 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. Groups the panel menu has +/// off are left out, and take no 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)) { + let end = end_width(app, ui, nothing); + if group_on(app, "paragraph") && crate::panels::paragraph::control_bar(app, ui, BUTTON, |ui| group_end_width(ui) + end) { 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) + if group_on(app, "verticalAlignment") + && crate::panels::properties::vertical_align::shown(app).is_some() + && ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end && 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(); + if group_on(app, "documentOptions") { + 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 { + let transform = group_on(app, "transform"); + let end = if transform { separator_width(ui) + end } else { 0.0 }; + if group_on(app, "alignDistribute") && 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); + if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x + end { + crate::panels::align::align_to_menu(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); + } + } + if transform { + separator(ui); } - separator(ui); } - true + transform } /// The edges of the window the Control bar docks to (`window.control.dock {edge}`): the top, then /// the bottom. pub const CONTROL_BAR_EDGES: [&str; 2] = ["top", "bottom"]; +/// The groups of the Control bar's options that its panel menu turns on or off +/// (`window.control.options {group, visible?}`), by id, in the menu's order. Every group is on +/// until it is turned off. A group that is off stays out of the bar even while its tool or object +/// is selected; one that is on still shows only while the selection or the tool calls for it. +pub const CONTROL_BAR_GROUPS: [&str; 15] = [ + "snapping", + "anchors", + "toolOptions", + "objectOptions", + "imageOptions", + "fillStroke", + "opacity", + "graphicStyle", + "character", + "paragraph", + "verticalAlignment", + "alignDistribute", + "transform", + "artboardOptions", + "documentOptions", +]; + +/// The panel menu's label for group `group` of [`CONTROL_BAR_GROUPS`], translated. +fn group_label(group: &str) -> &'static str { + match group { + "snapping" => tl!("Snapping"), + "anchors" => tl!("Anchor Points"), + "toolOptions" => tl!("Tool Options"), + "objectOptions" => tl!("Object Options"), + "imageOptions" => tl!("Image Options"), + "fillStroke" => tl!("Fill and Stroke"), + "opacity" => tl!("Opacity"), + "graphicStyle" => tl!("Graphic Style"), + "character" => tl!("Character"), + "paragraph" => tl!("Paragraph"), + "verticalAlignment" => tl!("Vertical Alignment"), + "alignDistribute" => tl!("Align and Distribute"), + "transform" => tl!("Transform"), + "artboardOptions" => tl!("Artboard Options"), + _ => tl!("Document Options"), + } +} + +/// Whether group `group` of [`CONTROL_BAR_GROUPS`] is on, so its controls may show in the bar. +pub(crate) fn group_on(app: &VectorcraftApp, group: &str) -> bool { + !app.ui.control_bar_hidden_groups.contains(group) +} + +/// Reads the groups of [`CONTROL_BAR_GROUPS`] that are off, as kept in the preferences and in a +/// workspace. Ids the list does not hold are dropped, and a value that is not a list of strings +/// reads as no group off, so every group shows. +pub fn read_hidden_groups<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let value = ::deserialize(d)?; + let ids = value.as_array().into_iter().flatten().filter_map(serde_json::Value::as_str); + Ok(ids.filter(|id| CONTROL_BAR_GROUPS.contains(id)).map(str::to_string).collect()) +} + /// The side of the Control bar's panel menu button, at the bar's right end. const MENU_BUTTON: f32 = 16.0; @@ -278,20 +354,84 @@ fn dock(app: &mut VectorcraftApp, edge: &str) { crate::menus::invoke(app, "window.control.dock", json!({ "edge": edge })); } -/// The Control bar's panel menu: Dock to Top and Dock to Bottom, the edge the bar is docked to -/// checked. +/// The Control bar's panel menu: an item for each group of [`CONTROL_BAR_GROUPS`], checked while +/// the group is on, which turns it on or off; then Dock to Top and Dock to Bottom, the edge the bar +/// is docked to checked. In a window too short for every item, the list scrolls. fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { let resp = crate::panels::menu_button(ui, "control", rect); egui::Popup::menu(&resp).show(|ui| { ui.set_min_width(160.0); - for (i, label) in [tl!("Dock to Top"), tl!("Dock to Bottom")].into_iter().enumerate() { - if widgets::menu_item(ui, label, true, usize::from(app.ui.control_bar_bottom) == i) { - dock(app, CONTROL_BAR_EDGES[i]); + widgets::menu_scroll(ui, |ui| { + for group in CONTROL_BAR_GROUPS { + if widgets::menu_item(ui, group_label(group), true, group_on(app, group)) { + crate::menus::invoke(app, "window.control.options", json!({ "group": group })); + } } - } + ui.separator(); + for (i, label) in [tl!("Dock to Top"), tl!("Dock to Bottom")].into_iter().enumerate() { + if widgets::menu_item(ui, label, true, usize::from(app.ui.control_bar_bottom) == i) { + dock(app, CONTROL_BAR_EDGES[i]); + } + } + }); }); } +/// The Control bar's Fill and Stroke group: the fill and stroke chips, the Stroke link, the weight +/// and the width profile, and the separator after them. +fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui) { + let shown_stroke = crate::panels::current_stroke(app); + let mixed = crate::panels::stroke_mixed(app, ui.ctx()); + let weight = stroke_panel::shown_weight(app, shown_stroke.as_ref(), &mixed); + crate::panels::paint_chip(app, ui, false, 22.0, true); + crate::panels::paint_chip(app, ui, true, 22.0, true); + // The link opens the Stroke panel as a popover under it; then the weight spinner + // (with presets) and the width profile. + stroke_panel::link(app, ui, tl!("Stroke:")); + stroke_panel::weight_field(app, ui, "cb-stroke", weight, 100.0); + if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { + app.run("stroke.set", json!({"profile": id})).ok(); + } + ui.add_space(4.0); + ui.separator(); +} + +/// The Control bar's Opacity group (its link and field, showing `opacity`) and, with something +/// `selected`, its Graphic Style group (Style, Recolor Artwork and Global Edit Options), each while +/// the panel menu has it on, and the separator after them. +fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: f32, selected: bool) { + let (opacity_on, style_on) = (group_on(app, "opacity"), group_on(app, "graphicStyle") && selected); + if opacity_on { + // 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) + && selected + { + app.run("transparency.set", json!({"opacity": o.clamp(0.0, 100.0)})).ok(); + } + } + if style_on { + // Style picker: the selection's graphic style; its menu applies another. + ui.add_space(4.0); + if ui.link(egui::RichText::new(tl!("Style:")).size(12.0).color(t.text).underline()).clicked() { + app.ui.open_panel = Some("graphicStyles".into()); + } + let resp = widgets::chip_button_named(ui, 22.0, true, tl!("Graphic Style"), |ui, r| crate::panels::graphic_styles::paint_linked(app, ui, r)); + egui::Popup::menu(&resp).show(|ui| crate::panels::graphic_styles::picker(app, ui)); + // Recolor Artwork, when the selection has colours to recolour. + let colored = app.session.active().is_some_and(|st| crate::canvas::has_colors(&st.doc, &st.selection.objects)); + if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 24.0).clicked() { + crate::menus::invoke(app, "ui.recolorDialog", json!({})); + } + global_edit_options(app, ui); + } + if opacity_on || style_on { + ui.separator(); + } +} + /// The Control bar's gripper. Dragging it shows a band along the top or the bottom edge of the /// window, whichever the pointer is nearer, and docks the bar there on release. fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens) { @@ -345,7 +485,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { return; } // The Artboard tool's controls fill the narrowest window, so they keep it to themselves there. - if app.session.tool_id() != "artboard" || ui.available_width() >= ARTBOARD_SNAPPING_WIDTH { + if group_on(app, "snapping") && (app.session.tool_id() != "artboard" || ui.available_width() >= ARTBOARD_SNAPPING_WIDTH) { snapping_menu(app, ui); } let Some(st) = app.session.active() else { return }; @@ -374,64 +514,40 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { 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. - if crate::panels::artboards::control_bar(app, ui) { + let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform")); + if crate::panels::artboards::control_bar(app, ui, artboard_options, transform) { return; } - if anchors != AnchorControls::None { + if anchors != AnchorControls::None && group_on(app, "anchors") { anchor_buttons(app, ui, anchors); } - isolation_button(app, ui); + let object_options = group_on(app, "objectOptions"); + if object_options { + isolation_button(app, ui); + } ui.add_space(6.0); - // An image or an Image Trace object shows its own controls in place of Fill and Stroke. - let image = crate::place::control_bar_details(app, ui) || crate::panels::image_trace::control_bar(app, ui); - crate::toolbar::control_bar_options(app, ui); - crate::dialogs::envelope::control_bar(app, ui); - crate::panels::symbols::control_bar(app, ui); + // An image or an Image Trace object shows its own controls in place of Fill and Stroke, + // and leaves Fill and Stroke out while the Image Options group is off too. + let image = if group_on(app, "imageOptions") { + crate::place::control_bar_details(app, ui) || crate::panels::image_trace::control_bar(app, ui) + } else { + crate::place::selected_image_info(app).is_some() || crate::panels::image_trace::selected_trace(app).is_some() + }; + if group_on(app, "toolOptions") { + crate::toolbar::control_bar_options(app, ui); + } + if object_options { + crate::dialogs::envelope::control_bar(app, ui); + crate::panels::symbols::control_bar(app, ui); + } 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()); - let weight = stroke_panel::shown_weight(app, shown_stroke.as_ref(), &mixed); - crate::panels::paint_chip(app, ui, false, 22.0, true); - crate::panels::paint_chip(app, ui, true, 22.0, true); - // The link opens the Stroke panel as a popover under it; then the weight spinner - // (with presets) and the width profile. - stroke_panel::link(app, ui, tl!("Stroke:")); - stroke_panel::weight_field(app, ui, "cb-stroke", weight, 100.0); - if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { - app.run("stroke.set", json!({"profile": id})).ok(); - } - ui.add_space(4.0); - ui.separator(); + if !image && group_on(app, "fillStroke") { + fill_and_stroke(app, ui); } - // 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()); + opacity_and_style(app, ui, &t, opacity, !sel.is_empty()); + if group_on(app, "character") { + crate::panels::character::control_bar(app, ui); } - if let Some(o) = widgets::plain_field(ui, "cb-opacity", opacity as f64 * 100.0, "%", 0, 56.0) - && !sel.is_empty() - { - app.run("transparency.set", json!({"opacity": o.clamp(0.0, 100.0)})).ok(); - } - if !sel.is_empty() { - // Style picker: the selection's graphic style; its menu applies another. - ui.add_space(4.0); - if ui.link(egui::RichText::new(tl!("Style:")).size(12.0).color(t.text).underline()).clicked() { - app.ui.open_panel = Some("graphicStyles".into()); - } - let resp = widgets::chip_button_named(ui, 22.0, true, tl!("Graphic Style"), |ui, r| { - crate::panels::graphic_styles::paint_linked(app, ui, r) - }); - egui::Popup::menu(&resp).show(|ui| crate::panels::graphic_styles::picker(app, ui)); - // Recolor Artwork, when the selection has colours to recolour. - let colored = app.session.active().is_some_and(|st| crate::canvas::has_colors(&st.doc, &st.selection.objects)); - if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 24.0).clicked() { - crate::menus::invoke(app, "ui.recolorDialog", json!({})); - } - global_edit_options(app, ui); - } - ui.separator(); - crate::panels::character::control_bar(app, ui); if !groups_before_transform(app, ui, sel.len()) { return; } diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 062059e6d7..02f34438a6 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -1,4 +1,4 @@ -use super::status_bar::ANIMATED_ZOOM_HINT; +use super::status_bar::{ANIMATED_ZOOM_HINT, clipped_label}; use super::{Cow, Sense, Stroke, Tokens, Ui, VectorcraftApp, menus, theme, vec2, widgets}; fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { @@ -249,7 +249,7 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let font = if bold { theme::semibold(12.5) } else { egui::FontId::proportional(12.5) }; job.append(&txt, 0.0, egui::TextFormat { font_id: font, color: if bold { t.text_strong } else { t.text }, ..Default::default() }); } - ui.label(job); + clipped_label(ui, job); }); }); widgets::set_menu_floor(ui.ctx(), panel.response.rect.top()); diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 8995080215..1e946b56da 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -80,13 +80,48 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if crate::i18n::current() == crate::i18n::Lang::EN { shown.trim_end_matches(" Tool") } else { shown } }) .unwrap_or(""); - ui.label(egui::RichText::new(tool).size(11.5).color(t.text_dim)); + // The tool name leaves the status message its least width and ends in an ellipsis first. + let room = (ui.available_width() - MESSAGE_MIN - ui.spacing().item_spacing.x).max(0.0); + ui.scope(|ui| { + ui.set_max_width(room); + clipped_label(ui, egui::RichText::new(tool).size(11.5).color(t.text_dim)); + }); status_readouts(app, ui, &t); }); }); widgets::set_menu_floor(ui.ctx(), panel.response.rect.top()); } +/// The least width the status message keeps when the window is narrow. +const MESSAGE_MIN: f32 = 180.0; + +/// A label that ends in an ellipsis when it is wider than the room left in `ui`. Only a cut label +/// shows its full text in a tooltip; screen readers always receive the full text. +pub(super) fn clipped_label(ui: &mut Ui, text: impl Into) -> egui::Response { + let galley = text.into().into_galley(ui, Some(egui::TextWrapMode::Truncate), ui.available_width(), egui::FontSelection::Default); + let full = galley.elided.then(|| egui::text::LayoutJob { + sections: galley.job.sections.clone(), + text: galley.job.text.clone(), + language: galley.job.language.clone(), + ..Default::default() + }); + let response = ui.add(egui::Label::new(galley).show_tooltip_when_elided(false)); + match full { + Some(job) => full_text_tooltip(response, job), + None => response, + } +} + +/// Show `text` on hover in a tooltip that wraps to fit inside the window. +fn full_text_tooltip(response: egui::Response, text: impl Into) -> egui::Response { + let text = text.into(); + response.on_hover_ui(|ui| { + let margins = ui.spacing().menu_margin.sum().x + 2.0 * ui.spacing().item_spacing.x; + ui.set_max_width(ui.spacing().tooltip_width.min(ui.ctx().content_rect().width() - margins).max(0.0)); + ui.add(egui::Label::new(text).wrap()); + }) +} + /// The most recently measured status widths, scoped to this UI and display settings. pub(super) struct StatusReadoutWidths { pub(super) key: (crate::i18n::Lang, vectorcraft_doc::Unit, f32), @@ -125,7 +160,6 @@ fn status_readout_widths(ui: &Ui, lang: crate::i18n::Lang, unit: vectorcraft_doc /// Allocate the remaining row once, then paint each field inside its own bounded rectangle. /// Child UIs requested with a desired width can shrink to their contents; these rectangles cannot. pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { - const MESSAGE_MIN: f32 = 180.0; let mono = theme::mono(10.5); let proportional = egui::FontId::proportional(10.5); let unit = app.session.general_unit(); @@ -196,24 +230,74 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { .collect(); // Reserve the spinner's space while idle too: starting a background job changes the text, // not its origin. Messages take priority over optional readouts in a narrow window. - let message = if let Some(job) = busy.first() { + let (message, notes) = if let Some(job) = busy.first() { let spinner = egui::Rect::from_center_size(egui::pos2(area.left() + 6.0, area.center().y), vec2(12.0, 12.0)); ui.put(spinner, egui::Spinner::new().size(12.0).color(t.accent)); let label = crate::i18n::msg(job); let more = busy.len() - 1; - if more > 0 { format!("{label}… (+{more})") } else { format!("{label}…") } + (if more > 0 { format!("{label}… (+{more})") } else { format!("{label}…") }, &[][..]) } else { - crate::i18n::msg(&app.ui.status) + (crate::i18n::msg(&app.ui.status), status_notes(&app.ui)) }; if !message.is_empty() { let rect = egui::Rect::from_min_max(egui::pos2((area.left() + 18.0).min(right), area.top()), egui::pos2(right, area.bottom())); - status_field(ui, "message", rect, message, egui::FontId::proportional(11.0), t.text); + status_field_with_notes(ui, "message", rect, message, egui::FontId::proportional(11.0), t.text, notes); } } +/// Most notes the status message's hover and access information list. +const MAX_LISTED_NOTES: usize = 30; + +/// The notes behind the status message (an open's, a save's or an export's, +/// [`crate::state::UiState::status_notes`]) when there are several and the status bar still shows +/// the message they came with, else none. +fn status_notes(ui: &crate::state::UiState) -> &[String] { + let notes = ui.status_notes.as_ref().filter(|(status, notes)| *status == ui.status && notes.len() > 1); + notes.map(|(_, notes)| notes.as_slice()).unwrap_or_default() +} + +/// `notes` in the interface language, one to a line, the first `most` of them (at most +/// [`MAX_LISTED_NOTES`]) and how many more. +pub(super) fn listed_notes(notes: &[String], most: usize) -> String { + let lang = crate::i18n::current(); + let most = most.min(MAX_LISTED_NOTES); + let mut lines: Vec = notes.iter().take(most).map(|n| format!("• {}", crate::i18n::message(lang, n))).collect(); + if notes.len() > most { + lines.push(format!("… (+{})", notes.len() - most)); + } + lines.join("\n") +} + +/// The hover of the status message `text` with `notes`: the message, then as many of the notes +/// ([`listed_notes`]) as fit in the window above or below the field `field`, wrapped within the +/// window's width. +fn notes_tooltip(response: egui::Response, field: egui::Rect, text: &str, notes: &[String]) -> egui::Response { + response.on_hover_ui(|ui| { + let screen = ui.ctx().content_rect(); + let margins = ui.spacing().menu_margin.sum() + 2.0 * ui.spacing().item_spacing; + let width = ui.spacing().tooltip_width.min(screen.width() - margins.x).max(0.0); + ui.set_max_width(width); + let room = (field.top() - screen.top()).max(screen.bottom() - field.bottom()) - 2.0 * margins.y; + let tip = |most: usize| format!("{text}\n{}", listed_notes(notes, most)); + let height = + |s: &str| egui::WidgetText::from(s).into_galley(ui, Some(egui::TextWrapMode::Wrap), width, egui::FontSelection::Default).size().y; + let mut most = notes.len().min(MAX_LISTED_NOTES); + while most > 0 && height(&tip(most)) > room { + most -= 1; + } + ui.add(egui::Label::new(tip(most)).wrap()); + }) +} + /// A field never grows with its text. Clipping also bounds over-wide glyphs; hover and access /// information retain the complete value when its on-screen label is truncated. fn status_field(ui: &mut Ui, id: &str, rect: egui::Rect, text: String, font: egui::FontId, color: egui::Color32) { + status_field_with_notes(ui, id, rect, text, font, color, &[]); +} + +/// [`status_field`], whose hover, when there are `notes`, lists them ([`notes_tooltip`]) and whose +/// access information has them after the text. +fn status_field_with_notes(ui: &mut Ui, id: &str, rect: egui::Rect, text: String, font: egui::FontId, color: egui::Color32, notes: &[String]) { if rect.width() <= 0.0 || rect.height() <= 0.0 { return; } @@ -227,9 +311,17 @@ fn status_field(ui: &mut Ui, id: &str, rect: egui::Rect, text: String, font: egu let elided = galley.elided; ui.painter().with_clip_rect(ui.clip_rect().intersect(rect)).galley(at, galley, color); let response = ui.interact(rect, ui.scope_id().with(("status-field", id)), Sense::hover()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text)); - if elided { - response.on_hover_text(text); + if notes.is_empty() { + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text)); + if elided { + full_text_tooltip(response, text); + } + return; + } + // The list is made only for a hover or a screen reader. + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text}\n{}", listed_notes(notes, MAX_LISTED_NOTES)))); + if response.hovered() { + notes_tooltip(response, rect, &text, notes); } } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 452fec1cc0..d7620e8d03 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -64,6 +64,18 @@ use crate::theme::Tokens; use serde_json::json; use vectorcraft_engine::Session; +/// `layers` without their ruler guides: the art. +fn art_of(layers: &[Arc]) -> Vec { + layers + .iter() + .map(|l| { + let mut l = vectorcraft_doc::Node::clone(l); + l.strip_ruler_guides(); + l + }) + .collect() +} + #[test] fn help_bar_and_status_bar_render_independently() { for (help, status, screen_mode) in [(true, true, 0), (false, true, 0), (true, false, 0), (false, false, 0), (true, true, 3)] { @@ -163,22 +175,7 @@ fn status_readout_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, wi /// Collect status-bar text, positions, clips and elision state with explicit pointer events. fn status_readout_frame_events(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32, events: Vec) -> Vec { - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0)); - let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::status_bar(app, ui)); - out.textures_delta.clear(); - out.shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Text(t) => Some(StatusText { - text: t.galley.job.text.clone(), - at: t.pos, - clip: s.clip_rect, - bounds: egui::Rect::from_min_size(t.pos, t.galley.size()), - elided: t.galley.elided, - }), - _ => None, - }) - .collect() + bar_frame(app, ctx, width, None, events, super::status_bar).0 } /// Find a required text record by prefix, failing the test when it is absent. @@ -373,6 +370,186 @@ fn narrow_status_bars_preserve_the_message_and_hide_optional_readouts() { assert!(message.clip.left() >= status_text(&texts, "Selection").bounds.right()); } +/// A function that draws one of the bars at the bottom of the window. +type DrawBar = fn(&mut crate::VectorcraftApp, &mut egui::Ui); + +/// The texts (positions, clips and elision state) and the screen-reader tree of one frame of +/// `draw` in a window `width` points wide, at `time` with `events`. +fn bar_frame( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + width: f32, + time: Option, + events: Vec, + draw: DrawBar, +) -> (Vec, Vec) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0)); + let input = egui::RawInput { screen_rect: Some(screen), time, events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| draw(app, ui)); + out.textures_delta.clear(); + let texts = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(StatusText { + text: t.galley.job.text.clone(), + at: t.pos, + clip: s.clip_rect, + bounds: egui::Rect::from_min_size(t.pos, t.galley.size()), + elided: t.galley.elided, + }), + _ => None, + }) + .collect(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default(); + (texts, nodes) +} + +/// The texts of `draw` with the pointer away, the screen-reader tree, and the texts after the +/// pointer has rested on the first text that starts with `prefix` for longer than the tooltip delay. +fn bar_hover( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + width: f32, + prefix: &str, + draw: DrawBar, +) -> (Vec, Vec, Vec) { + let t = ctx.input(|i| i.time) + 1.0; + bar_frame(app, ctx, width, Some(t), vec![egui::Event::PointerGone], draw); + let (texts, nodes) = bar_frame(app, ctx, width, Some(t + 0.1), vec![], draw); + let at = status_text(&texts, prefix); + let pos = at.clip.intersect(at.bounds).center(); + bar_frame(app, ctx, width, Some(t + 1.0), vec![egui::Event::PointerMoved(pos)], draw); + bar_frame(app, ctx, width, Some(t + 3.0), vec![], draw); + let (hovered, _) = bar_frame(app, ctx, width, Some(t + 3.1), vec![], draw); + (texts, nodes, hovered) +} + +/// Checks the field whose full text is `full`: in a window `narrow` wide it ends in an ellipsis +/// inside the window, screen readers get the full text, and resting the pointer on it shows the +/// full text in a tooltip no wider than the window; in a window `wide` wide it shows in full with no +/// tooltip. +fn assert_clipped_text_shows_on_hover(app: &mut crate::VectorcraftApp, ctx: &egui::Context, full: &str, narrow: f32, wide: f32, draw: DrawBar) { + let prefix: String = full.chars().take(4).collect(); + let (texts, nodes, hovered) = bar_hover(app, ctx, narrow, &prefix, draw); + let field = status_text(&texts, &prefix); + assert_eq!(field.text, full); + assert!(field.elided, "{narrow}: the text is clipped: {field:?}"); + assert!(field.bounds.right() <= narrow, "{narrow}: the ellipsis is inside the window: {field:?}"); + assert!(nodes.iter().any(|n| n.value() == Some(full)), "{narrow}: screen readers receive the full text"); + let tip: Vec<_> = hovered.iter().filter(|t| t.text == full && !t.elided).collect(); + assert_eq!(tip.len(), 1, "{narrow}: the tooltip shows the full text: {hovered:?}"); + assert!(tip[0].bounds.left() >= 0.0 && tip[0].bounds.right() <= narrow, "{narrow}: the tooltip wraps within the window: {tip:?}"); + + let (texts, _, hovered) = bar_hover(app, ctx, wide, &prefix, draw); + assert!(!status_text(&texts, &prefix).elided, "{wide}: the text fits"); + assert_eq!(hovered.iter().filter(|t| t.text == full).count(), 1, "{wide}: no tooltip: {hovered:?}"); +} + +/// A status message too long for the bar ends in an ellipsis and shows in full on hover, in a +/// tooltip that wraps within the window (#6622). +#[test] +fn a_clipped_status_message_shows_in_full_on_hover() { + let (mut app, ctx) = status_readout_app(); + ctx.enable_accesskit(); + let long = format!("Saved recovery data for {}illustration.vectorcraft", "a-long-folder-name/".repeat(12)); + app.ui.status = long.clone(); + assert_clipped_text_shows_on_hover(&mut app, &ctx, &long, 700.0, 20000.0, super::status_bar); + app.ui.status = "Saved recovery data for Untitled-1".to_owned(); + let (texts, _, hovered) = bar_hover(&mut app, &ctx, 700.0, "Saved", super::status_bar); + assert!(!status_text(&texts, "Saved").elided); + assert_eq!(hovered.iter().filter(|t| t.text.starts_with("Saved")).count(), 1, "a message that fits has no tooltip: {hovered:?}"); +} + +/// The status message of an open with several notes lists them all on hover, and screen readers +/// receive them after the message, while the status bar shows that message. A later message +/// leaves the list out, and so does an open with one note. +#[test] +fn the_message_of_an_open_with_several_notes_lists_them_on_hover() { + let (mut app, ctx) = status_readout_app(); + ctx.enable_accesskit(); + let notes = vec!["the file's layers weren't read".to_string(), "a brush wasn't read".to_string()]; + app.ui.status = crate::io::opened_with_notes(2, ¬es[0]); + app.ui.status_notes = Some((app.ui.status.clone(), notes)); + let listed = "• the file's layers weren't read\n• a brush wasn't read"; + let full = format!("{}\n{listed}", app.ui.status); + let (texts, nodes, hovered) = bar_hover(&mut app, &ctx, 1400.0, "Opened", super::status_bar); + assert!(!status_text(&texts, "Opened").elided); + assert!(nodes.iter().any(|n| n.value() == Some(full.as_str())), "screen readers receive the notes: {nodes:?}"); + assert!(hovered.iter().any(|t| t.text == full), "the tooltip lists the notes: {hovered:?}"); + + app.ui.status = "Saved recovery data for Untitled-1".to_owned(); + let (_, nodes, hovered) = bar_hover(&mut app, &ctx, 1400.0, "Saved", super::status_bar); + assert!(!nodes.iter().any(|n| n.value().is_some_and(|v| v.contains("• "))), "{nodes:?}"); + assert_eq!(hovered.iter().filter(|t| t.text.starts_with("Saved")).count(), 1, "no tooltip: {hovered:?}"); + + // One note is the message itself: no list. + app.ui.status = crate::io::opened_with_notes(1, "a brush wasn't read"); + app.ui.status_notes = Some((app.ui.status.clone(), vec!["a brush wasn't read".to_string()])); + let (_, nodes, hovered) = bar_hover(&mut app, &ctx, 1400.0, "Opened", super::status_bar); + assert!(!nodes.iter().any(|n| n.value().is_some_and(|v| v.contains("• "))), "{nodes:?}"); + assert_eq!(hovered.iter().filter(|t| t.text.starts_with("Opened")).count(), 1, "no tooltip: {hovered:?}"); +} + +/// The list has at most 30 notes, then how many more there are. +#[test] +fn the_hover_lists_thirty_notes_and_counts_the_rest() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let notes: Vec = (1..=32).map(|i| format!("note {i}")).collect(); + let listed = super::status_bar::listed_notes(¬es, usize::MAX); + let lines: Vec<&str> = listed.lines().collect(); + assert_eq!((lines.len(), lines[0], lines[29], lines[30]), (31, "• note 1", "• note 30", "… (+2)")); + assert_eq!(super::status_bar::listed_notes(¬es[..2], usize::MAX), "• note 1\n• note 2"); + assert_eq!(super::status_bar::listed_notes(¬es[..3], 1), "• note 1\n… (+2)"); +} + +/// A hover with more long notes than the window can show lists the ones that fit and how many +/// more there are, inside the window. A window 300 points tall is shorter than the main window's +/// smallest size (500 points) at UI Scaling 1.5. +#[test] +fn the_hover_of_many_notes_stays_inside_a_small_window() { + let (mut app, ctx) = status_readout_app(); + let notes: Vec = (1..=32).map(|i| format!("note {i}: {}", "this file's PostScript couldn't be read ".repeat(3))).collect(); + app.ui.status = crate::io::opened_with_notes(notes.len(), ¬es[0]); + app.ui.status_notes = Some((app.ui.status.clone(), notes)); + let (_, _, hovered) = bar_hover(&mut app, &ctx, 700.0, "Opened", super::status_bar); + let tip: Vec<_> = hovered.iter().filter(|t| t.text.contains("\n• note 1:")).collect(); + let [tip] = &tip[..] else { panic!("one tooltip lists the notes: {hovered:?}") }; + assert!(tip.bounds.top() >= 0.0 && tip.bounds.bottom() <= 300.0 && tip.bounds.right() <= 700.0, "{tip:?}"); + let last = tip.text.lines().last().unwrap_or_default(); + assert!(last.starts_with("… (+") && !tip.text.contains("• note 30:"), "{last:?}"); +} + +/// The Help Bar's hint ends in an ellipsis when it is wider than the window and shows in full on +/// hover, in a tooltip that wraps within the window (#6622). The Dimension tool's hint is wider +/// than the smallest main window (800 points); 400 points is that window at UI Scaling 2.0. +#[test] +fn a_clipped_help_bar_hint_shows_in_full_on_hover() { + let (mut app, ctx) = status_readout_app(); + ctx.enable_accesskit(); + app.select_tool("dimension"); + let hint: String = super::hint_segments(app.session.tool_id()).into_iter().map(|(s, _)| s).collect(); + for narrow in [800.0, 400.0] { + assert_clipped_text_shows_on_hover(&mut app, &ctx, &hint, narrow, 3000.0, super::hint_bar); + } +} + +/// In a narrow status bar the tool name ends in an ellipsis, shows in full on hover, and leaves +/// the status message its room (#6622). 640 and 500 points are the smallest main window (800 +/// points) at UI Scaling 1.25 and 1.6. +#[test] +fn a_clipped_tool_name_shows_in_full_on_hover() { + let (mut app, ctx) = status_readout_app(); + ctx.enable_accesskit(); + for narrow in [640.0, 500.0] { + assert_clipped_text_shows_on_hover(&mut app, &ctx, "Selection", narrow, 1400.0, super::status_bar); + let (texts, _) = bar_frame(&mut app, &ctx, narrow, None, vec![], super::status_bar); + let tool = status_text(&texts, "Selection"); + let message = status_text(&texts, "Saved recovery data"); + assert!(message.clip.left() >= tool.bounds.right() && message.clip.width() >= 24.0, "{narrow}: the message keeps room: {texts:?}"); + } +} + /// Busy-job transitions preserve message placement, labels and accessibility. #[test] fn background_activity_keeps_the_status_message_origin() { @@ -1556,8 +1733,8 @@ fn artboard_document_tab_roundtrip_properties_delete_uses_shown_board() { assert_eq!(selected_before_delete, json!([1])); assert_eq!(active_before_delete, json!(1)); assert_eq!(st.doc.artboards, vec![before.artboards[0].clone()], "the original first board survives"); - assert_eq!(st.doc.guides, vec![before.guides[0].clone()], "only the deleted board's guide is removed"); - assert_eq!(st.doc.layers, before.layers, "artwork and symbol instances stay unchanged"); + assert_eq!(st.doc.ruler_guides(), vec![before.ruler_guides()[0].clone()], "only the deleted board's guide is removed"); + assert_eq!(art_of(&st.doc.layers), art_of(&before.layers), "artwork and symbol instances stay unchanged"); assert_eq!(st.doc.symbols, before.symbols, "symbol definitions stay unchanged"); assert_eq!(st.selection, selection); assert_eq!(app.run_count, commands.wrapping_add(1), "one command from the actual Properties control"); @@ -1853,9 +2030,9 @@ fn delete_shown_board(app: &mut crate::VectorcraftApp, ctx: &egui::Context, base "ARTBOARD_CLOSE_TARGET_WRONG_SURVIVOR: Properties showing Shown must delete Shown after closing B" ); assert_eq!(st.doc.as_ref(), expected, "only Shown and its attached guide may be removed from the full document"); - assert_eq!(st.doc.layers, before.layers, "all artwork and symbol instances stay unchanged"); + assert_eq!(art_of(&st.doc.layers), art_of(&before.layers), "all artwork and symbol instances stay unchanged"); assert_eq!(st.doc.symbols, before.symbols); - assert_eq!(st.doc.guides, vec![before.guides[0].clone()]); + assert_eq!(st.doc.ruler_guides(), vec![before.ruler_guides()[0].clone()]); assert_eq!(&st.selection, selection); assert_eq!(st.uid, *uid); assert_eq!(st.revision, revision + 1); @@ -1915,13 +2092,14 @@ fn artboard_close_active_tab_properties_delete_uses_shown_board() { let history_before = history_of(st); let history_limits = (st.history.limit, st.history.byte_budget); assert_eq!(before.artboards.iter().map(|a| a.name.as_str()).collect::>(), vec!["Keep", "Shown"]); - assert_eq!(before.guides.len(), 2); + assert_eq!(before.ruler_guides().len(), 2); assert!(!selection.objects.is_empty()); assert!(history_before.1.is_empty()); assert!(!st.is_dirty()); let mut expected = before.as_ref().clone(); expected.artboards = vec![before.artboards[0].clone()]; - expected.guides = vec![before.guides[0].clone()]; + let keep = before.ruler_guides()[0].id; + expected.retain_guides(&mut vectorcraft_doc::Selection::default(), |g| g.id == keep); let base = Baseline { uid, revision, before, selection, history_before, history_limits, expected }; close_b_tab(&mut app, &ctx, &base); delete_shown_board(&mut app, &ctx, &base); @@ -2072,9 +2250,22 @@ fn the_control_bar_snapping_menu_shares_glyph_and_alignment_settings() { /// The window the Control bar docking tests draw the bar in. const DOCK_SCREEN: egui::Rect = egui::Rect { min: egui::Pos2::ZERO, max: egui::pos2(1200.0, 300.0) }; +/// The window the Control bar panel menu tests draw the bar in, tall enough for the whole menu. +const MENU_SCREEN: egui::Rect = egui::Rect { min: egui::Pos2::ZERO, max: egui::pos2(1200.0, 700.0) }; + /// One headless frame of the Control bar alone; returns its accessibility nodes. fn control_bar_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { - let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(DOCK_SCREEN), ..Default::default() }, |ui| super::control_bar(app, ui)); + control_bar_frame_in(app, ctx, DOCK_SCREEN, events) +} + +/// [`control_bar_frame`] in window `screen`. +fn control_bar_frame_in( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + screen: egui::Rect, + events: Vec, +) -> Vec { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); out.textures_delta.clear(); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() } @@ -2100,31 +2291,69 @@ fn the_control_bar_panel_menu_docks_it_to_the_top_or_the_bottom() { let ctx = egui::Context::default(); ctx.enable_accesskit(); crate::theme::install_fonts(&ctx); + let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, MENU_SCREEN, events); let pick = |app: &mut crate::VectorcraftApp, item: &str| { - control_bar_frame(app, &ctx, vec![]); - let menu = node_center(&control_bar_frame(app, &ctx, vec![]), "Panel menu").unwrap_or_else(|| panic!("the bar has a panel menu")); - control_bar_frame(app, &ctx, vec![egui::Event::PointerMoved(menu), press_at(menu, true)]); - control_bar_frame(app, &ctx, vec![press_at(menu, false)]); - let nodes = control_bar_frame(app, &ctx, vec![]); - let checked: Vec = nodes.iter().filter_map(|n| n.label()).filter(|l| l.starts_with('✓')).map(str::to_string).collect(); + frame(app, vec![]); + let menu = node_center(&frame(app, vec![]), "Panel menu").unwrap_or_else(|| panic!("the bar has a panel menu")); + frame(app, vec![egui::Event::PointerMoved(menu), press_at(menu, true)]); + frame(app, vec![press_at(menu, false)]); + let nodes = frame(app, vec![]); + // The groups of options are listed first, every one on; the edge items follow. + let checked: Vec = + nodes.iter().filter_map(|n| n.label()).filter(|l| l.starts_with('✓') && l.contains("Dock")).map(str::to_string).collect(); + let groups = nodes.iter().filter_map(|n| n.label()).filter(|l| CONTROL_BAR_GROUP_LABELS.iter().any(|g| *l == format!("✓ {g}"))).count(); + assert_eq!(groups, CONTROL_BAR_GROUP_LABELS.len(), "every group is listed, on"); let at = node_center(&nodes, item).unwrap_or_else(|| panic!("the menu lists {item}")); // Below the button at the top, and above it at the bottom: the menu opens inside the window. - assert!(DOCK_SCREEN.contains(at) && (at.y < menu.y) == app.ui.control_bar_bottom, "{item} at {at:?}, the button at {menu:?}"); - control_bar_frame(app, &ctx, vec![egui::Event::PointerMoved(at), press_at(at, true)]); - control_bar_frame(app, &ctx, vec![press_at(at, false)]); - control_bar_frame(app, &ctx, vec![]); - let menu = node_center(&control_bar_frame(app, &ctx, vec![]), "Panel menu").unwrap_or_else(|| panic!("the bar still shows")); + assert!(MENU_SCREEN.contains(at) && (at.y < menu.y) == app.ui.control_bar_bottom, "{item} at {at:?}, the button at {menu:?}"); + frame(app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(app, vec![press_at(at, false)]); + frame(app, vec![]); + let menu = node_center(&frame(app, vec![]), "Panel menu").unwrap_or_else(|| panic!("the bar still shows")); (checked, menu.y) }; let (checked, y) = pick(&mut app, "Dock to Bottom"); assert_eq!(checked, ["✓ Dock to Top"], "the bar starts docked at the top"); assert!(app.ui.control_bar_bottom, "Dock to Bottom docks it at the bottom"); - assert!(y > DOCK_SCREEN.bottom() - 34.0, "the bar is drawn along the bottom of the window: {y}"); + assert!(y > MENU_SCREEN.bottom() - 34.0, "the bar is drawn along the bottom of the window: {y}"); let (checked, y) = pick(&mut app, "Dock to Top"); assert_eq!(checked, ["✓ Dock to Bottom"]); assert!(!app.ui.control_bar_bottom && y < 34.0, "Dock to Top docks it at the top again: {y}"); } +/// In a window too short for the whole Control bar panel menu, the menu stays inside the window and +/// scrolls, so Dock to Bottom, its last item, can still be reached and clicked. +#[test] +fn the_control_bar_panel_menu_scrolls_in_a_short_window() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + control_bar_frame(&mut app, &ctx, vec![]); + let menu = node_center(&control_bar_frame(&mut app, &ctx, vec![]), "Panel menu").unwrap_or_else(|| panic!("the bar has a panel menu")); + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(menu), press_at(menu, true)]); + control_bar_frame(&mut app, &ctx, vec![press_at(menu, false)]); + let nodes = control_bar_frame(&mut app, &ctx, vec![]); + let first = node_center(&nodes, "Snapping").filter(|p| p.y > 34.0).unwrap_or_else(|| panic!("the menu lists Snapping")); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -200.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..6 { + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(first), wheel.clone()]); + } + let nodes = control_bar_frame(&mut app, &ctx, vec![]); + let at = node_center(&nodes, "Dock to Bottom").unwrap_or_else(|| panic!("the menu lists Dock to Bottom")); + assert!(DOCK_SCREEN.shrink(1.0).contains(at), "scrolled into the window: {at:?}"); + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + control_bar_frame(&mut app, &ctx, vec![press_at(at, false)]); + assert!(app.ui.control_bar_bottom, "Dock to Bottom docks the bar at the bottom"); +} + /// Dragging the Control bar's gripper docks the bar at the edge of the window the pointer is /// released nearer; a drag released nearer the edge it is at leaves it there. #[test] @@ -2170,6 +2399,243 @@ fn the_control_bar_dock_command_takes_top_or_bottom() { assert!(!app.ui.control_bar_bottom); } +/// The labels of the Control bar panel menu's groups of options, in the menu's order. +const CONTROL_BAR_GROUP_LABELS: [&str; 15] = [ + "Snapping", + "Anchor Points", + "Tool Options", + "Object Options", + "Image Options", + "Fill and Stroke", + "Opacity", + "Graphic Style", + "Character", + "Paragraph", + "Vertical Alignment", + "Align and Distribute", + "Transform", + "Artboard Options", + "Document Options", +]; + +/// Opens the Control bar's panel menu, at the right end of the bar `control_frame` draws, unless +/// it is open, and returns the text the bar and the menu show. +fn open_control_bar_menu(app: &mut crate::VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::Rect)> { + use crate::tests_removeanchors::{click_control, control_frame}; + let open = |texts: &[(String, egui::Rect)]| texts.iter().any(|(t, _)| t.ends_with("Dock to Bottom")); + let texts = control_frame(app, ctx, vec![]); + if open(&texts) { + return texts; + } + click_control(app, ctx, egui::pos2(1387.0, 17.0)); + let texts = control_frame(app, ctx, vec![]); + assert!(open(&texts), "the panel menu opens: {texts:?}"); + texts +} + +/// Turns group `label` of the Control bar's panel menu on or off with a click on its item, which +/// shows checked while the group is on. +fn toggle_control_bar_group(app: &mut crate::VectorcraftApp, ctx: &egui::Context, label: &str, on: bool) { + let menu = open_control_bar_menu(app, ctx); + let item = if on { format!("✓ {label}") } else { format!(" {label}") }; + crate::tests_removeanchors::click_control(app, ctx, crate::tests_removeanchors::at(&menu, &item)); +} + +/// The Control bar's panel menu lists every group of options, each checked while it is on, and a +/// click on one turns that group off or on again. A group that is off stays out of the bar when +/// the selection changes, the other groups and the menu button stay, and with no document the +/// menu still lists every group. +#[test] +fn the_control_bar_panel_menu_turns_each_group_on_or_off() { + use crate::tests_removeanchors::{control_frame, has}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let on = |app: &crate::VectorcraftApp, group: &str| crate::menus::checked(app, "window.control.options", &json!({ "group": group })); + let menu = open_control_bar_menu(&mut app, &ctx); + for label in CONTROL_BAR_GROUP_LABELS { + assert!(has(&menu, &format!("✓ {label}")), "{label} is listed, on"); + } + assert!(has(&menu, "✓ Dock to Top") && has(&menu, " Dock to Bottom"), "the edge items stay: {menu:?}"); + toggle_control_bar_group(&mut app, &ctx, "Fill and Stroke", true); + assert_eq!(on(&app, "fillStroke"), Some(false)); + assert!(has(&open_control_bar_menu(&mut app, &ctx), " Fill and Stroke"), "listed, off, with no document"); + toggle_control_bar_group(&mut app, &ctx, "Fill and Stroke", false); + assert_eq!(on(&app, "fillStroke"), Some(true)); + + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + let bar = control_frame(&mut app, &ctx, vec![]); + for s in ["Snapping", "Stroke:", "Opacity:", "Style:", "Transform"] { + assert!(has(&bar, s), "{s} shows with every group on"); + } + toggle_control_bar_group(&mut app, &ctx, "Fill and Stroke", true); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(!has(&bar, "Stroke:"), "Fill and Stroke is off"); + for s in ["Snapping", "Opacity:", "Style:", "Transform"] { + assert!(has(&bar, s), "{s} stays"); + } + app.run("select.set", json!({ "ids": [] })).unwrap(); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(has(&bar, "Document Setup") && !has(&bar, "Stroke:"), "still off with nothing selected"); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + assert!(!has(&control_frame(&mut app, &ctx, vec![]), "Stroke:"), "still off with the rectangle selected again"); + toggle_control_bar_group(&mut app, &ctx, "Fill and Stroke", false); + assert!(has(&control_frame(&mut app, &ctx, vec![]), "Stroke:"), "on again"); +} + +/// With every group of options off, the Control bar keeps its gripper, the selection's label and +/// its panel menu, which lists every group off; nothing selected shows no Document Setup either. +#[test] +fn the_control_bar_keeps_its_label_and_menu_with_every_group_off() { + use crate::tests_removeanchors::{control_frame, has}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + for group in crate::chrome::CONTROL_BAR_GROUPS { + app.run("window.control.options", json!({ "group": group, "visible": false })).unwrap(); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(has(&bar, crate::panels::appearance::object_label(&app)), "the label stays: {bar:?}"); + for s in ["Snapping", "Stroke:", "Opacity:", "Style:", "Transform", "X:"] { + assert!(!has(&bar, s), "{s} is off"); + } + let menu = open_control_bar_menu(&mut app, &ctx); + for label in CONTROL_BAR_GROUP_LABELS { + assert!(has(&menu, &format!(" {label}")), "{label} is listed, off"); + } + app.run("select.set", json!({ "ids": [] })).unwrap(); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(!has(&bar, "Document Setup") && !has(&bar, "Preferences"), "{bar:?}"); +} + +/// `window.control.options {group, visible?}` turns a group of the Control bar's options on or +/// off, or toggles it, and the panel menu's item shows it; an unknown or missing group, or a +/// `visible` that is not true or false, is an error and changes nothing. +#[test] +fn the_control_bar_options_command_turns_a_group_on_or_off() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let checked = |app: &crate::VectorcraftApp, group: &str| crate::menus::checked(app, "window.control.options", &json!({ "group": group })); + for group in crate::chrome::CONTROL_BAR_GROUPS { + assert_eq!(checked(&app, group), Some(true), "{group} starts on"); + } + let run = |app: &mut crate::VectorcraftApp, p: serde_json::Value| app.run("window.control.options", p); + assert_eq!(run(&mut app, json!({"group": "opacity", "visible": false})).unwrap(), json!({"group": "opacity", "visible": false})); + assert_eq!(checked(&app, "opacity"), Some(false)); + assert_eq!(run(&mut app, json!({"group": "opacity", "visible": false})).unwrap(), json!({"group": "opacity", "visible": false}), "off stays off"); + assert_eq!(run(&mut app, json!({"group": "opacity"})).unwrap(), json!({"group": "opacity", "visible": true}), "toggled on"); + assert_eq!(run(&mut app, json!({"group": "transform"})).unwrap(), json!({"group": "transform", "visible": false}), "toggled off"); + assert_eq!(run(&mut app, json!({"group": "transform", "visible": null})).unwrap(), json!({"group": "transform", "visible": true})); + assert_eq!(run(&mut app, json!({"group": "paragraph", "visible": false})).unwrap()["visible"], json!(false)); + let before = app.ui.control_bar_hidden_groups.clone(); + for (p, err) in [ + (json!({"group": "stroke"}), "`group` must be one of"), + (json!({"group": "Opacity"}), "`group` must be one of"), + (json!({"group": 1}), "`group` must be one of"), + (json!({}), "`group` must be one of"), + (json!({"group": "paragraph", "visible": "true"}), "`visible` must be true or false"), + (json!({"group": "opacity", "visible": 0}), "`visible` must be true or false"), + ] { + let e = run(&mut app, p.clone()).unwrap_err(); + assert!(e.starts_with(err), "{p}: {e}"); + assert_eq!(app.ui.control_bar_hidden_groups, before, "{p} changes nothing"); + } + assert_eq!(checked(&app, "paragraph"), Some(false)); + assert_eq!(checked(&app, "stroke"), Some(false), "an unknown group is never checked"); +} + +/// A group of options that is off takes no room in the Control bar: with Fill and Stroke, Opacity +/// and Graphic Style off, or Transform off, the Align buttons fit a narrower window, and the panel +/// menu button still shows there. +#[test] +fn groups_that_are_off_leave_their_room_to_the_later_groups() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let ids: Vec = + [10, 100].iter().map(|x| app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + // The narrowest window, in steps of 10 points, whose bar shows the Align buttons. + let narrowest = |app: &mut crate::VectorcraftApp| { + (40..=240).map(|w| w as f32 * 10.0).find(|&w| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, 300.0)); + control_bar_frame_in(app, &ctx, screen, vec![]); + let nodes = control_bar_frame_in(app, &ctx, screen, vec![]); + node_center(&nodes, "Horizontal Align Left").is_some() && node_center(&nodes, "Panel menu").is_some() + }) + }; + let all = narrowest(&mut app).expect("the Align buttons show in a wide window"); + for group in ["fillStroke", "opacity", "graphicStyle"] { + app.run("window.control.options", json!({ "group": group, "visible": false })).unwrap(); + } + let fewer = narrowest(&mut app).expect("they show with fewer groups"); + assert!(fewer < all, "the Align buttons fit {fewer} wide with three groups off, {all} with every group on"); + for group in ["fillStroke", "opacity", "graphicStyle"] { + app.run("window.control.options", json!({ "group": group, "visible": true })).unwrap(); + } + app.run("window.control.options", json!({"group": "transform", "visible": false})).unwrap(); + let no_transform = narrowest(&mut app).expect("they show without Transform"); + assert!(no_transform < all, "without the Transform link's room the Align buttons fit {no_transform} wide, {all} with it"); +} + +/// With the Artboard tool, the Artboard Options group holds the artboard's own controls and the +/// Transform group the Transform link and the X/Y/W/H fields; each one off leaves the other, and +/// with Artboard Options off the fields find room in a window that is too narrow for them otherwise. +#[test] +fn the_artboard_tool_s_control_bar_follows_its_two_groups() { + use crate::tests_removeanchors::{control_frame, has}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let bar = control_frame(&mut app, &ctx, vec![]); + for s in ["Artboard", "Name:", "Transform", "Move Artwork with Artboard"] { + assert!(has(&bar, s), "{s} shows with every group on: {bar:?}"); + } + assert!(!has(&bar, "X:"), "the fields need more room than is left: {bar:?}"); + app.run("window.control.options", json!({"group": "artboardOptions", "visible": false})).unwrap(); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(!has(&bar, "Name:") && !has(&bar, "Move Artwork with Artboard"), "{bar:?}"); + assert!(has(&bar, "Artboard") && has(&bar, "Transform") && has(&bar, "X:"), "{bar:?}"); + app.run("window.control.options", json!({"group": "artboardOptions", "visible": true})).unwrap(); + app.run("window.control.options", json!({"group": "transform", "visible": false})).unwrap(); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(!has(&bar, "Transform") && !has(&bar, "X:"), "{bar:?}"); + assert!(has(&bar, "Name:") && has(&bar, "Move Artwork with Artboard"), "{bar:?}"); +} + +/// The Anchor Points group holds Convert and Anchors for direct-selected anchors; off, the bar keeps +/// its Anchor Point label. +#[test] +fn the_anchor_points_group_holds_convert_and_anchors() { + use crate::tests_removeanchors::{control_frame, has}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(has(&bar, "Convert:") && has(&bar, "Anchors:"), "{bar:?}"); + app.run("window.control.options", json!({"group": "anchors", "visible": false})).unwrap(); + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(!has(&bar, "Convert:") && !has(&bar, "Anchors:"), "{bar:?}"); + assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}"); +} + /// Menus stop above a Control bar docked at the bottom when the status bar is hidden, above the /// status and hint bars when they show, and at the bottom of the window when the bar is docked at /// the top or a screen mode hides it. @@ -2256,6 +2722,109 @@ fn the_control_bar_shows_the_distribute_buttons_for_two_or_more_objects() { assert_eq!((left(&app, &a), left(&app, &b), left(&app, &c)), (10.0, 105.0, 200.0), "{}", app.ui.status); } +/// The Control bar's Align To menu follows its Align buttons. It shows the Align panel's Align To +/// choice (Artboard for one object, which the buttons align to the artboard) and screen readers +/// get it as the value of a combo box named "Align To:". Its menu checks that choice, has Align to +/// Key Object off while no key object can be made, and a pick chooses as the Align panel does: +/// Artboard and Selection are stored with the UI state and let go of the key object, and Key +/// Object makes the topmost selected object the key, keeping the stored choice. The Align +/// buttons then align to the choice. +#[test] +fn the_control_bar_align_to_menu_chooses_what_align_aligns_to() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 40, "width": 30, "height": 20})).unwrap()["id"].clone() + }; + let (a, b) = (rect(&mut app, 50.0), rect(&mut app, 150.0)); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 300.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + // A control by its name; a menu row's name follows its check column. + let find = |nodes: &Nodes, name: &str| { + nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim_start_matches(['✓', ' ']) == name)).map(|(_, n)| n.clone()) + }; + 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 crate::VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + let menu = |app: &mut crate::VectorcraftApp| { + frame(app, vec![]); + let nodes = frame(app, vec![]); + find(&nodes, "Align To:").unwrap_or_else(|| panic!("the Control bar has the Align To menu")) + }; + // Opens the menu, checks its rows and picks `pick`, or closes it with Escape. + let choose = |app: &mut crate::VectorcraftApp, checked: &str, key_on: bool, pick: Option<&str>| { + let at = center(&menu(app)); + let nodes = click(app, at); + for name in ["Align to Selection", "Align to Key Object", "Align to Artboard"] { + let row = find(&nodes, name).unwrap_or_else(|| panic!("the menu lists {name}")); + assert_eq!(row.label().is_some_and(|l| l.starts_with('✓')), name == checked, "{name} checked"); + assert_eq!(row.is_disabled(), name == "Align to Key Object" && !key_on, "{name} off"); + } + let nodes = match pick { + Some(pick) => click(app, center(&find(&nodes, pick).unwrap_or_else(|| panic!("{pick}")))), + None => { + let escape = + |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(app, vec![escape(true)]); + frame(app, vec![escape(false)]); + frame(app, vec![]) + } + }; + assert!(find(&nodes, "Align to Artboard").is_none(), "the menu closes"); + }; + let key = |app: &crate::VectorcraftApp| app.session.active().unwrap().selection.key; + let x0 = |app: &crate::VectorcraftApp, id: &serde_json::Value| { + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap().x0 + }; + + // One object: the buttons align it to the artboard, and Align to Key Object is off. + app.run("select.set", json!({"ids": [a]})).unwrap(); + let m = menu(&mut app); + assert_eq!(m.role(), egui::accesskit::Role::ComboBox); + assert_eq!(m.value(), Some("Align to Artboard"), "one object shows Artboard"); + choose(&mut app, "Align to Artboard", false, None); + assert_eq!(key(&app), None); + + // Two objects: the stored choice, Selection. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(menu(&mut app).value(), Some("Align to Selection")); + choose(&mut app, "Align to Selection", true, Some("Align to Artboard")); + assert_eq!(app.ui.align_to, crate::panels::align::AlignTo::Artboard, "the choice the Align panel shows"); + assert_eq!(menu(&mut app).value(), Some("Align to Artboard")); + let left = find(&frame(&mut app, vec![]), "Horizontal Align Left").unwrap_or_else(|| panic!("Horizontal Align Left")); + click(&mut app, center(&left)); + assert_eq!((x0(&app, &a), x0(&app, &b)), (0.0, 0.0), "aligned to the artboard: {}", app.ui.status); + + // Key Object makes the topmost the key and keeps the stored choice. + choose(&mut app, "Align to Artboard", true, Some("Align to Key Object")); + assert_eq!(key(&app), Some(vectorcraft_doc::NodeId(b.as_u64().unwrap())), "the topmost object is the key"); + assert_eq!(app.ui.align_to, crate::panels::align::AlignTo::Artboard, "the stored choice stays"); + assert_eq!(menu(&mut app).value(), Some("Align to Key Object")); + + // Selection lets go of the key and is stored. + choose(&mut app, "Align to Key Object", true, Some("Align to Selection")); + assert_eq!(key(&app), None, "the key object is let go"); + assert_eq!(app.ui.align_to, crate::panels::align::AlignTo::Selection); + assert_eq!(menu(&mut app).value(), Some("Align to Selection")); +} + /// The Control bar shows the Global Edit Options dropdown while Start Global Edit can run. Its /// options are the session's, which the Properties panel's dropdown also sets: Match Size from /// the Control bar narrows the Results and the objects Start Global Edit takes. The dropdown is off @@ -2358,7 +2927,8 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { crate::theme::install_fonts(&ctx); let mut seen = false; let mut menu_seen = false; - // The Align group, then for two objects the Distribute group (#5372): each by its controls. + // The Align group and the Align To menu, then for two objects the Distribute group (#5372): + // each by its controls. let mut groups: Vec<(&str, Vec<&str>)> = vec![( "Align", vec![ @@ -2371,6 +2941,7 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { "Vertical Align Bottom", ], )]; + groups.push(("Align To", vec!["Align To:"])); if count == 2 { groups.push(( "Distribute", diff --git a/crates/ui-egui/src/clipboard_probe.rs b/crates/ui-egui/src/clipboard_probe.rs index 902024bac2..d492893ce0 100644 --- a/crates/ui-egui/src/clipboard_probe.rs +++ b/crates/ui-egui/src/clipboard_probe.rs @@ -14,8 +14,11 @@ use crate::sysclip::ClipboardProbeFactory; /// How often the worker looks at the clipboard while the UI wants to know. const PROBE_INTERVAL: Duration = Duration::from_millis(250); -/// How long dropping the probe waits for the worker to let go of its clipboard handle. -const STOP_WAIT: Duration = Duration::from_millis(250); +/// How long dropping the probe (when the app quits) waits for the worker to let go of its clipboard +/// handle (VectorCraft's own bound). arboard's X11 reads wait up to 4 s for each text format they +/// ask for; when a look is still waiting after this bound, the app quits without waiting longer, +/// and what it copied may not reach the clipboard manager. +const STOP_WAIT: Duration = Duration::from_secs(5); /// The background clipboard check ([`crate::VectorcraftApp`]'s `clipboard_probe`). pub(crate) struct Probe { @@ -89,8 +92,8 @@ impl Probe { } impl Drop for Probe { - /// Wake the worker to stop and wait (a moment at most: it may be stuck on an owner that never - /// answers) until it has let go of its clipboard handle. + /// Wake the worker to stop and wait ([`STOP_WAIT`] at most: it may be stuck on an owner that + /// never answers) until it has let go of its clipboard handle. fn drop(&mut self) { self.wants = None; let end = Instant::now() + STOP_WAIT; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b02c3b6e1d..11edb6de6e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -324,9 +324,10 @@ const PANEL_FIELDS: [&str; 7] = /// loaded without a path is named. The UI state refers to a library by its bare id in a library panel /// and the Color Guide's limit, and by a panel id (`library::loaded/`) in the fields of /// [`PANEL_FIELDS`] and the workspaces' layouts. Text the person types (a command palette query, a -/// workspace's name) is not read. When another of those ids already shows that name, the next free one -/// of `loaded/ (2)`, `(3)` and so on is shown, in the sorted order of the full ids, so that -/// two libraries stay two and `ui.inspect` and `ui.docking` show a library under the same id. +/// workspace's name) is not read. The ids are numbered with the session's loaded libraries as the +/// library commands number them ([`vectorcraft_engine::cmd::swatchlib::concealed_library_ids`]), so +/// that two libraries stay two and `ui.inspect`, `ui.docking` and the library commands show a library +/// under the same id. fn unreadable_library_ids(app: &VectorcraftApp) -> Vec<(String, String)> { let mut ids = std::collections::BTreeSet::new(); let ui = serde_json::to_value(&app.ui).unwrap_or_default(); @@ -342,30 +343,9 @@ fn unreadable_library_ids(app: &VectorcraftApp) -> Vec<(String, String)> { for id in app.ui.library_panels.iter().map(|p| p.id.as_str()).chain([app.ui.color_guide_limit.as_str()]) { add_library_id(id, &mut ids); } - let mut hidden = Vec::new(); - let mut taken = std::collections::BTreeSet::new(); - for id in ids { - let path = &id["loaded/".len()..]; - let name = vectorcraft_engine::cmd::fileio::file_name(path); - if name != path && !readable(path) { - hidden.push((id, name)); - } else { - taken.insert(id); - } - } - let mut hidden = hidden - .into_iter() - .map(|(id, name)| { - let mut shown = format!("loaded/{name}"); - let mut n = 2; - while taken.contains(&shown) { - shown = format!("loaded/{name} ({n})"); - n += 1; - } - taken.insert(shown.clone()); - (id, shown) - }) - .collect::>(); + let mut hidden = vectorcraft_engine::cmd::swatchlib::concealed_library_ids(&app.session, ids.iter().cloned()); + // Only the ids the UI state refers to are replaced in the reply. + hidden.retain(|(id, _)| ids.contains(id)); // The longest first, so that an id that begins another one does not replace part of it. hidden.sort_by_key(|(id, _)| std::cmp::Reverse(id.len())); hidden @@ -494,9 +474,24 @@ fn key_from(name: &str) -> Option { /// The modifier keys a request holds down (`cmd`, `ctrl`, `alt`, `shift`; `cmd` is Command on /// macOS, Ctrl elsewhere). -fn modifiers(p: &Value) -> egui::Modifiers { - let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false); - egui::Modifiers { alt: b("alt"), ctrl: b("ctrl"), shift: b("shift"), mac_cmd: b("cmd") && cfg!(target_os = "macos"), command: b("cmd") } +fn modifiers(p: &Value) -> Result { + let b = |n: &str| crate::menus::opt_bool(p, n).map(|on| on.unwrap_or(false)); + let cmd = b("cmd")?; + Ok(egui::Modifiers { alt: b("alt")?, ctrl: b("ctrl")?, shift: b("shift")?, mac_cmd: cmd && cfg!(target_os = "macos"), command: cmd }) +} + +/// An optional number param of a control request as `f32`, `default` when it is omitted or null. +fn coord(p: &Value, key: &str, default: f32) -> Result { + crate::menus::opt_number(p, key).map(|n| n.map_or(default, |n| n as f32)) +} + +/// A pointer packet's `mods`: none when omitted or null, else an object of booleans. +fn packet_mods(value: Option<&Value>) -> Result, String> { + match value { + None | Some(Value::Null) => Ok(None), + Some(m) if !m.is_object() => Err("`mods` must be an object of true or false values".to_string()), + Some(m) => serde_json::from_value(m.clone()).map(Some).map_err(|e| format!("`mods` must be an object of true or false values: {e}")), + } } pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { @@ -532,10 +527,13 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques "ui.pointer" => pointer_events(app, ctx, req), "ui.key" => { let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") }; + let m = match modifiers(p) { + Ok(m) => m, + Err(e) => return err(e), + }; if let Err(e) = reserve_synthetic(app, 2 + usize::from(s("text").is_some())) { return err(e); } - let m = modifiers(p); app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m }); // Typed text comes with the press, so it shares the key's frame and modifiers. if let Some(t) = s("text") { @@ -546,31 +544,39 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques ok(Value::Null) } "ui.move" => { + let pos = match coord(p, "x", 0.0).and_then(|x| Ok(egui::pos2(x, coord(p, "y", 0.0)?))) { + Ok(pos) => pos, + Err(e) => return err(e), + }; if let Err(e) = reserve_synthetic(app, 1) { return err(e); } - let pos = egui::pos2(p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32); app.synthetic.push(egui::Event::PointerMoved(pos)); ctx.request_repaint(); ok(Value::Null) } "ui.click" | "ui.drag" => synthetic_click(app, ctx, req), "ui.wheel" => { + // Mouse wheel notches over screen point (x, y): `dy` up (+) or down, `dx` sideways + // (`unit: "point"` for trackpad-like points), with modifiers as `ui.click` takes them. + let given = + (|| Ok::<_, String>(([coord(p, "dx", 0.0)?, coord(p, "dy", 0.0)?, coord(p, "x", 0.0)?, coord(p, "y", 0.0)?], modifiers(p)?)))(); + let ([dx, dy, x, y], modifiers) = match given { + Ok(given) => given, + Err(e) => return err(e), + }; if let Err(e) = reserve_synthetic(app, 2) { return err(e); } - // Mouse wheel notches over screen point (x, y): `dy` up (+) or down, `dx` sideways - // (`unit: "point"` for trackpad-like points), with modifiers as `ui.click` takes them. - let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32; let unit = if s("unit") == Some("point") { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line }; // Notches, not a flood: a turn stays within what a real wheel sends. - let delta = egui::vec2(f("dx"), f("dy")).clamp(egui::Vec2::splat(-100.0), egui::Vec2::splat(100.0)); - app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x"), f("y")))); + let delta = egui::vec2(dx, dy).clamp(egui::Vec2::splat(-100.0), egui::Vec2::splat(100.0)); + app.synthetic.push(egui::Event::PointerMoved(egui::pos2(x, y))); app.synthetic.push(egui::Event::MouseWheel { unit, delta, phase: egui::TouchPhase::Move, - modifiers: modifiers(p), + modifiers, source: egui::MouseWheelSource::Unknown, }); ctx.request_repaint(); @@ -635,8 +641,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques ok(Value::Null) } "ui.resize" => { - let w = p.get("width").and_then(Value::as_f64).unwrap_or(1440.0) as f32; - let h = p.get("height").and_then(Value::as_f64).unwrap_or(900.0) as f32; + let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) { + Ok(size) => size, + Err(e) => return err(e), + }; ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w, h))); ok(Value::Null) } @@ -649,32 +657,48 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques if let Some(Err(e)) = s("path").map(vectorcraft_engine::file_access::check_write) { return err(e); } - if p.get("focus").and_then(Value::as_bool).unwrap_or(true) { + let flags = crate::menus::opt_bool(p, "focus").and_then(|focus| Ok((focus, crate::menus::opt_bool(p, "data")?))); + let (focus, data) = match flags { + Ok(flags) => flags, + Err(e) => return err(e), + }; + if focus.unwrap_or(true) { ctx.send_viewport_cmd(egui::ViewportCommand::Focus); } ctx.request_repaint(); - Outcome::Screenshot { path: s("path").map(str::to_string), data: p.get("data").and_then(Value::as_bool) == Some(true) } + Outcome::Screenshot { path: s("path").map(str::to_string), data: data == Some(true) } } "ui.render" => { + let given = (|| { + Ok::<_, String>(( + crate::menus::opt_index(p, "artboard")?, + crate::menus::opt_number(p, "scale")?, + crate::menus::opt_bool(p, "traceViews")?, + crate::menus::opt_bool(p, "data")?, + )) + })(); + let (index, scale, trace_views, data) = match given { + Ok(given) => given, + Err(e) => return err(e), + }; let Some(st) = app.session.active() else { return err("no document") }; let doc = st.doc.clone(); // The artboard asked for (0-based, as headless), else the first. - let index = p.get("artboard").and_then(Value::as_u64).map_or(Some(0), |i| usize::try_from(i).ok()); - let Some(r) = index.and_then(|i| doc.artboards.get(i)).map(|a| a.rect) else { return err("no such artboard") }; - let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0); + let Some(r) = doc.artboards.get(index.unwrap_or(0)).map(|a| a.rect) else { return err("no such artboard") }; + let scale = scale.unwrap_or(1.0); if let Err(e) = vectorcraft_render::raster_size(r, scale) { return err(e); } // Rendered with the options of a PNG export on white, so its pixels are the exported file's. // `traceViews: true` draws Image Trace objects as their View shows them, as the canvas does. let mut opts = RasterExportOptions { background: Some([255; 3]), ..Default::default() }.render_options(RasterFormat::Png); - opts.trace_views = p.get("traceViews").and_then(Value::as_bool) == Some(true); + opts.trace_views = trace_views == Some(true); let img = app.canvas.renderer.render_region_with(&doc, r, scale, &opts); let png = match img.to_png() { Ok(png) => png, Err(e) => return err(e), }; - let data = p.get("data").and_then(Value::as_bool) == Some(true); + let data = data == Some(true); match s("path") { Some(path) => match app.services.write.as_mut() { Some(w) => wrap( @@ -877,7 +901,7 @@ fn rotate_view_pointer( /// A Rotate View packet accepts only the documented boolean modifier fields. fn validate_rotate_view_mods(value: Option<&Value>) -> Result<(), String> { - let Some(value) = value else { return Ok(()) }; + let Some(value) = value.filter(|value| !value.is_null()) else { return Ok(()) }; let Some(fields) = value.as_object() else { return Err("Rotate View `mods` must be an object of booleans".into()) }; if fields.iter().any(|(key, value)| !matches!(key.as_str(), "shift" | "alt" | "cmd" | "ctrl" | "space") || !value.is_boolean()) { return Err("Rotate View `mods` accepts only boolean shift, alt, cmd, ctrl and space".into()); @@ -926,9 +950,36 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con if rotating && let Err(error) = validate_rotate_view_events(p, events) { return err(error); } - let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); + // Every event is read before any is sent, so a malformed packet sends none of them. + let read = packet_mods(p.get("mods")).and_then(|base| { + let base = base.unwrap_or_default(); + events + .iter() + .map(|e| { + let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") { + "down" => PointerKind::Down, + "drag" => PointerKind::Drag, + "up" => PointerKind::Up, + "move" => PointerKind::Move, + "doubleclick" | "dblclick" => PointerKind::DoubleClick, + other => return Err(format!("unknown pointer kind `{other}`")), + }; + PointerEvent::json_check(e)?; + let at = |k: &str| crate::menus::opt_number(e, k).map(|n| n.unwrap_or(0.0)); + Ok((kind, at("x")?, at("y")?, packet_mods(e.get("mods"))?.unwrap_or(base))) + }) + .collect::, String>>() + }); + let read = match read { + Ok(read) => read, + Err(e) => return err(e), + }; let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); + let screen = |e: &Value| e.get("space").and_then(Value::as_str) == Some("screen"); + if !rotating && xf.is_none() && events.iter().any(screen) { + return err("no canvas yet"); + } let from = app.session.input_count(); let held = PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::, _>>()); @@ -936,19 +987,8 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con 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, - "up" => PointerKind::Up, - "move" => PointerKind::Move, - "doubleclick" | "dblclick" => PointerKind::DoubleClick, - other => return err(format!("unknown pointer kind `{other}`")), - }; - let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0); - let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0); - let screen = e.get("space").and_then(Value::as_str) == Some("screen"); - let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods); + for ((e, backquote), (kind, x, y, mods)) in events.iter().zip(held).zip(read) { + let screen = screen(e); if rotating { if let Err(e) = rotate_view_pointer(app, kind, vectorcraft_geom::Point::new(x, y), screen, mods.shift) { return err(e); @@ -1007,18 +1047,24 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR let Some(events) = count.checked_mul(2).and_then(|n| n.checked_add(steps)).and_then(|n| n.checked_add(1)) else { return err("synthetic input event count is out of range"); }; + // Screen-space (egui points) pointer input through egui itself: reaches every widget. + let drag = req.method == "ui.drag"; + let given = (|| { + let a = egui::pos2(coord(p, "x", 0.0)?, coord(p, "y", 0.0)?); + let end = if drag { egui::pos2(coord(p, "toX", 0.0)?, coord(p, "toY", 0.0)?) } else { a }; + Ok::<_, String>((a, end, modifiers(p)?)) + })(); + let (a, end, modifiers) = match given { + Ok(given) => given, + Err(e) => return err(e), + }; if let Err(e) = reserve_synthetic(app, events) { return err(e); } - // Screen-space (egui points) pointer input through egui itself: reaches every widget. - let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32; let button = match s("button") { Some("right") | Some("secondary") => egui::PointerButton::Secondary, _ => egui::PointerButton::Primary, }; - let modifiers = modifiers(p); - let a = egui::pos2(f("x"), f("y")); - let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a }; app.synthetic.push(egui::Event::PointerMoved(a)); app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers }); if req.method == "ui.drag" { @@ -1040,6 +1086,11 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { let p = &req.params; let s = |k: &str| p.get(k).and_then(Value::as_str); + // A flag of the wrong type is refused before anything is set. + let flags = ["rulers", "outline", "grid", "smartGuides", "boundingBox", "controlBar", "imageTracePreview"]; + if let Some(e) = flags.iter().find_map(|k| crate::menus::opt_bool(p, k).err()) { + return err(e); + } // Outline is a setting of the active document's view: without one, nothing is set. if p.get("outline").is_some_and(Value::is_boolean) && app.session.active().is_none() { return err("no document"); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 0a9c042a1e..1763fd679a 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -314,6 +314,93 @@ fn render_takes_the_artboard_asked_for() { assert_eq!(got, size.map(Some), "{params}: {r}"); } assert!(request("ui.render", json!({"artboard": 2}))["error"].is_string()); + for (params, key) in [ + (json!({"artboard": "1"}), "artboard"), + (json!({"artboard": -1}), "artboard"), + (json!({"scale": "0.5"}), "scale"), + (json!({"traceViews": 1}), "traceViews"), + (json!({"data": "yes"}), "data"), + ] { + let r = request("ui.render", params.clone()); + assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{params}: {r}"); + } + let r = request("ui.render", json!({"artboard": null, "scale": null})); + assert_eq!([&r["result"]["width"], &r["result"]["height"]].map(Value::as_u64), [Some(64), Some(64)], "null keeps the default: {r}"); +} + +/// The control channel's input methods refuse a number or switch of the wrong type before they +/// queue any event; omitting it keeps its default. +#[test] +fn control_input_refuses_params_of_the_wrong_type() { + let move_to = |mods: Value| json!({"events": [{"kind": "move", "x": 5, "y": 5}, {"kind": "move", "x": 6, "y": 6, "mods": mods}]}); + for (method, params, key) in [ + ("ui.move", json!({"x": "10"}), "x"), + ("ui.move", json!({"y": true}), "y"), + ("ui.wheel", json!({"dy": "1"}), "dy"), + ("ui.wheel", json!({"dy": 1, "shift": "yes"}), "shift"), + ("ui.click", json!({"x": [1]}), "x"), + ("ui.click", json!({"cmd": 1}), "cmd"), + ("ui.drag", json!({"toX": "5"}), "toX"), + ("ui.key", json!({"key": "Enter", "alt": "true"}), "alt"), + ("ui.resize", json!({"width": "800"}), "width"), + ("ui.screenshot", json!({"focus": "no"}), "focus"), + ("ui.screenshot", json!({"data": 1}), "data"), + ("ui.set", json!({"rulers": "true"}), "rulers"), + ("ui.set", json!({"grid": true, "controlBar": 0}), "controlBar"), + ("ui.pointer", json!({"events": [{"kind": "move", "x": "5", "y": 0}]}), "x"), + ("ui.pointer", move_to(json!({"shift": "yes"})), "mods"), + ("ui.pointer", move_to(json!([true])), "mods"), + ("ui.pointer", json!({"mods": "shift", "events": [{"kind": "move", "x": 1, "y": 1}]}), "mods"), + ] { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.synthetic.push(egui::Event::Text("pending".into())); + let before = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar); + let r = input_request(&mut app, method, params.clone()); + assert_eq!(r["ok"], false, "{method} {params}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{method} {params}: {r}"); + let after = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar); + assert_eq!(after, before, "{method} {params}: nothing is queued or set"); + } + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + assert_eq!(input_request(&mut app, "ui.move", json!({"x": null, "y": 4}))["ok"], true); + assert!(matches!(app.synthetic.first(), Some(egui::Event::PointerMoved(p)) if *p == egui::pos2(0.0, 4.0))); +} + +/// The app's own commands refuse a param of the wrong type and change nothing; omitting it or +/// giving null keeps its default. +#[test] +fn ui_commands_refuse_params_of_the_wrong_type() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("view.setZoom", json!({"zoom": 300, "center": [5, 5]})).unwrap(); + let view = |app: &VectorcraftApp| app.view().map(|v| (v.zoom, v.center.x, v.center.y)); + let before = (view(&app), app.ui.screen_mode, app.session.documents().len(), app.ui.dialog.is_some(), app.ui.open_panel.clone()); + for (id, params, key) in [ + ("view.setZoom", json!({"zoom": "200"}), "zoom"), + ("view.setZoom", json!({"zoom": 200, "center": [1]}), "center"), + ("view.setZoom", json!({"zoom": 200, "center": "0,0"}), "center"), + ("view.screenMode", json!({"mode": "2"}), "mode"), + ("view.screenMode", json!({"mode": 1.5}), "mode"), + ("window.panel", json!({"panel": "layers", "toggle": "true"}), "toggle"), + ("window.panel", json!({"panel": "layers", "toggle": true, "toggleGroup": 1}), "toggleGroup"), + ("file.revert", json!({"confirmed": "yes"}), "confirmed"), + ("file.close", json!({"index": "0"}), "index"), + ("ui.newSwatch", json!({"spot": "true"}), "spot"), + ("ui.newSwatch", json!({"global": 1}), "global"), + ("ui.symbolOptions", json!({"edit": 1}), "edit"), + ("ui.batchDialog", json!({"set": "1"}), "set"), + ("ui.batchDialog", json!({"action": -1}), "action"), + ("file.exportSelection", json!({"multiple": "true"}), "multiple"), + ] { + let e = app.run(id, params.clone()).unwrap_err(); + assert!(e.contains(&format!("`{key}`")), "{id} {params}: {e}"); + let after = (view(&app), app.ui.screen_mode, app.session.documents().len(), app.ui.dialog.is_some(), app.ui.open_panel.clone()); + assert_eq!(after, before, "{id} {params}: nothing changes"); + } + app.run("view.setZoom", json!({"zoom": null, "center": null})).unwrap(); + assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.session.prefs.display_print_size))); } #[test] @@ -370,6 +457,35 @@ fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() { } } +/// `ui.pointer` refuses an unknown event kind, a pen value or `space` of the wrong type, or a +/// screen-space event with no canvas, before any of the packet's events runs. +#[test] +fn synthetic_pointer_rejects_an_unknown_kind_before_any_event_runs() { + 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 moves = [json!({"kind": "down", "x": 125, "y": 125}), json!({"kind": "drag", "x": 145, "y": 125}), json!({"kind": "up", "x": 145, "y": 125})]; + for (last, error) in [ + (json!({"kind": "wiggle", "x": 145, "y": 125}), "unknown pointer kind `wiggle`"), + (json!({"kind": "move", "x": 145, "y": 125, "space": "screen"}), "no canvas yet"), + (json!({"kind": "move", "x": 145, "y": 125, "pressure": "bad"}), "`pressure` must be a number"), + (json!({"kind": "move", "x": 145, "y": 125, "holdMs": "800"}), "`holdMs` must be a number"), + (json!({"kind": "move", "x": 145, "y": 125, "tiltY": true}), "`tiltY` must be a number"), + (json!({"kind": "move", "x": 145, "y": 125, "rotation": "90"}), "`rotation` must be a number"), + (json!({"kind": "move", "x": 145, "y": 125, "space": "screeen"}), "`space` must be doc or screen"), + (json!({"kind": "move", "x": 145, "y": 125, "space": true}), "`space` must be doc or screen"), + ] { + let events = moves.iter().cloned().chain([last]).collect::>(); + let r = input_request(&mut app, "ui.pointer", json!({"events": events})); + assert_eq!(r["ok"], false, "{error}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains(error)), "{r}"); + assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{error}: the drag does not run"); + } +} + /// `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/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index e5008644b9..2cc23df53f 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1,8 +1,10 @@ //! Window › Toolbars › New Toolbar (#1759): toolbars the user makes and names. New Toolbar asks //! for a name and makes a blank toolbar that floats on its own; the ••• button at its foot opens the //! All Tools drawer beside it, and tools dragged from the drawer fill it (`edit_toolbar`, with the -//! `toolbar` param of its commands). Its title bar moves it, its × hides it and its double arrow -//! shows its tools in one column or two. Each toolbar is listed under Window › Toolbars, where its +//! `toolbar` param of its commands). The + button above it opens Add Tool…, a menu of every tool +//! where a click adds the tool at the end, and whose Remove Tool items take tools out: VectorCraft's +//! own way to fill a toolbar without a drag. Its title bar moves it, its × hides it and its double +//! arrow shows its tools in one column or two. Each toolbar is listed under Window › Toolbars, where its //! item shows or hides it, and is kept with the workspace it was made in (`Workspace::toolbars`). //! Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames, copies and deletes them. //! @@ -553,6 +555,10 @@ enum Action { /// A group's flyout: its tools, its button, and the toolbar's name. Flyout(Vec<&'static str>, egui::Rect, String), EditToolbar(String), + /// A tool picked in Add Tool…'s menu, added at the end of the toolbar named. + AddTool(String, &'static str), + /// A tool picked under Remove Tool in Add Tool…'s menu, taken out of the toolbar named. + RemoveTool(String, &'static str), /// The title bar's ×. Hide(String), /// The title bar's double arrow: two columns (true) or one. @@ -561,8 +567,8 @@ enum Action { /// The toolbars made with New Toolbar that show, each floating where its title bar was dragged: the /// title bar's × hides it and its double arrow lays the tools out in one column or two; then its -/// tool buttons (a group's flyout opens as the Tools panel's do) and the ••• button that opens the -/// All Tools drawer beside it. +/// tool buttons (a group's flyout opens as the Tools panel's do), the + button whose menu adds and +/// removes tools, and the ••• button that opens the All Tools drawer beside it. pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Tab hides them, also when Window › Tools shows the Tools panel again. if app.ui.tab_hid.is_some() || app.ui.custom_toolbars.iter().all(|b| !b.shown) { @@ -660,9 +666,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); } ui.add_space(4.0); + // Add Tool…: a menu of the tools, which adds one to this toolbar or takes one out. + let add = ui.vertical_centered(|ui| widgets::icon_button(ui, "plus", "Add Tool…", false, 26.0)).inner; // Edit Toolbar: the All Tools drawer opens beside this toolbar, by this button. - ui.vertical_centered(|ui| widgets::icon_button(ui, "ellipsis", "Edit Toolbar", edit_this, 26.0)).inner + (add, ui.vertical_centered(|ui| widgets::icon_button(ui, "ellipsis", "Edit Toolbar", edit_this, 26.0)).inner) }); + let (add, edit) = edit; + add_menu(&add, &t, &bar, &mut actions); if edit.clicked() { actions.push(Action::EditToolbar(bar.name.clone())); } @@ -721,6 +731,16 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.status(e); } } + Action::AddTool(name, tool) => { + if let Err(e) = app.run("toolbar.addTool", json!({ "tool": tool, "toolbar": name })) { + app.status(e); + } + } + Action::RemoveTool(name, tool) => { + if let Err(e) = app.run("toolbar.removeTool", json!({ "tool": tool, "toolbar": name })) { + app.status(e); + } + } Action::Hide(name) => { if let Err(e) = app.run("window.toolbar.custom", json!({ "name": name, "show": false })) { app.status(e); @@ -793,6 +813,42 @@ fn slot_button(ui: &mut egui::Ui, t: &Tokens, p: &Press, slot: &[String], action Some(rect) } +/// The area of Add Tool…'s menu on the toolbar named `name`. +pub(crate) fn add_menu_id(name: &str) -> egui::Id { + egui::Id::unique(("custom-toolbar-add", key(name))) +} + +/// Add Tool…'s menu, which the + button on the toolbar `bar` opens: under Remove Tool the tools in +/// the toolbar, where a click takes one out; then every tool under the All Tools drawer's headings, +/// where a click adds one at the end (dimmed: in the toolbar already). It scrolls past the window's +/// bottom bars, as other long menus do ([`widgets::menu_scroll`]). +fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &mut Vec) { + egui::Popup::menu(button).id(add_menu_id(&bar.name)).show(|ui| { + ui.set_min_width(200.0); + widgets::menu_scroll(ui, |ui| { + let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); + let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong)); + if !held.is_empty() { + heading(ui, &format!("{}:", tl!("Remove Tool"))); + for tool in held.iter().filter_map(|id| tool_info(id)) { + if widgets::menu_item(ui, tool.label, true, false) { + actions.push(Action::RemoveTool(bar.name.clone(), tool.id)); + } + } + ui.separator(); + } + for (cat, tools) in crate::edit_toolbar::sections() { + heading(ui, &format!("{}:", tl!(cat))); + for tool in tools { + if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) { + actions.push(Action::AddTool(bar.name.clone(), tool.id)); + } + } + } + }); + }); +} + /// Remember `id` as the tool shown by each slot of a toolbar made with New Toolbar that holds it, /// however it was chosen (`toolbar::remember` calls it). pub(crate) fn remember(ui: &mut UiState, id: &str) { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c13a230a94..c25fa2f7ed 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -8,6 +8,7 @@ mod about; pub mod action_batch; +pub mod action_insert_menu_item; pub mod action_new; pub mod action_playback; pub mod action_set_options; @@ -17,6 +18,7 @@ pub mod blend_options; mod brush_art_options; pub mod brush_delete; pub mod brush_options; +pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; pub mod color_balance; @@ -77,6 +79,7 @@ pub mod new_text_style; pub mod objects_on_path_options; pub mod office_export; pub mod package; +pub mod para_style_options; pub(crate) mod path_ops; pub mod pathfinder_options; pub mod pdf_presets; @@ -320,8 +323,10 @@ registry! { SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC, Confirm: [confirm::KIND] => confirm::SPEC, BrushDelete: [brush_delete::KIND] => brush_delete::SPEC, + BrushReplaceArt: [brush_replace_art::KIND] => brush_replace_art::SPEC, Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC, Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, + ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC, ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, @@ -333,6 +338,7 @@ registry! { ColorPicker: [color_picker::KIND] => color_picker::SPEC, GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC, CharStyleOptions: [char_style_options::KIND] => char_style_options::SPEC, + ParaStyleOptions: [para_style_options::KIND] => para_style_options::SPEC, NewTextStyle: [new_text_style::KIND] => new_text_style::SPEC, EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC, ColorGuideOptions: [color_guide_options::KIND] => color_guide_options::SPEC, @@ -389,6 +395,7 @@ registry! { ActionPlayback: [action_playback::KIND] => action_playback::SPEC, ActionStopRecord: [action_stop::RECORD_KIND] => action_stop::RECORD_SPEC, ActionStopMessage: [action_stop::MESSAGE_KIND] => action_stop::MESSAGE_SPEC, + ActionInsertMenuItem: [action_insert_menu_item::KIND] => action_insert_menu_item::SPEC, SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, @@ -872,6 +879,9 @@ mod tests_eps; #[cfg(test)] mod tests_metafile; +#[cfg(test)] +mod tests_hpgl; + #[cfg(test)] mod tests_tiff_bmp_tga; diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 4e8a3bfae8..61ef75c5e1 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -66,14 +66,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "includeSubdirs", "Include All Subdirectories"); } else { ui.label(egui::RichText::new(tl!("Uses every data set of the open document.")).size(11.5).color(t.text_dim)); - form::choice( - ui, - d, - "datasetFileNaming", - "File Name:", - (LABEL, 200.0), - &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], - ); } ui.add_space(8.0); @@ -86,6 +78,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); } + if names_data_set_files(d) { + form::choice( + ui, + d, + "datasetFileNaming", + "File Name:", + (LABEL, 200.0), + &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], + ); + } ui.add_space(6.0); widgets::subheader(ui, tl!("Overrides")); form::check(ui, d, "overrideOpen", "Override Action \"Open\" Commands"); @@ -160,7 +162,8 @@ fn params(d: &Dialog, action_name: &str, commands: Vec) -> Value { }); if source == "folder" { params["folder"] = json!(d.str("folder")); - } else if source == "datasets" { + } + if names_data_set_files(d) { params["datasetFileNaming"] = json!(d.str("datasetFileNaming")); } if destination == "folder" { @@ -169,14 +172,22 @@ fn params(d: &Dialog, action_name: &str, commands: Vec) -> Value { params } +/// Whether the File Name choice names the batch's output: a Data Sets source with a +/// destination folder. With None or Save and Close the dialog sends no folder, so no file +/// takes the data set's name. +fn names_data_set_files(d: &Dialog) -> bool { + d.str("source") == "datasets" && d.str("destination") == "folder" +} + #[cfg(test)] mod tests { use super::*; use vectorcraft_engine::Session; - fn shown(source: &str) -> Vec { + fn shown(source: &str, destination: &str) -> Vec { let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); d.fields["source"] = json!(source); + d.fields["destination"] = json!(destination); render(&mut d) } @@ -205,11 +216,35 @@ mod tests { labels } + /// The File Name row's caption and its selected choice (the dropdown shows only that one). + const NAMING: [&str; 2] = ["File Name:", "File + Number"]; + #[test] - fn file_name_choice_shows_only_for_data_sets() { - assert!(shown("datasets").iter().any(|label| label == "File Name:")); - assert!(shown("datasets").iter().any(|label| label == "File + Number")); - assert!(!shown("folder").iter().any(|label| label == "File Name:")); + fn file_name_choice_shows_only_for_data_sets_into_a_folder() { + for source in ["folder", "datasets"] { + for destination in ["none", "saveAndClose", "folder"] { + let labels = shown(source, destination); + let expected = source == "datasets" && destination == "folder"; + for text in NAMING { + assert_eq!(labels.iter().any(|label| label == text), expected, "{source} to {destination}, {text}: {labels:?}"); + } + } + } + } + + #[test] + fn file_name_choice_comes_back_after_another_destination() { + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!("datasets"); + d.fields["datasetFileNaming"] = json!("dataSetName"); + for (destination, shown) in [("folder", true), ("none", false), ("saveAndClose", false), ("folder", true)] { + d.fields["destination"] = json!(destination); + let labels = render(&mut d); + assert_eq!(labels.iter().any(|label| label == "File Name:"), shown, "{destination}: {labels:?}"); + assert_eq!(labels.iter().any(|label| label == "Data Set Name"), shown, "{destination}: {labels:?}"); + assert_eq!(d.str("datasetFileNaming"), "dataSetName", "{destination}"); + } + assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], "dataSetName"); } /// Batch plays an action recorded with a key its command no longer reads, as Play does. @@ -240,6 +275,14 @@ mod tests { d.fields["datasetFileNaming"] = json!(choice); assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], choice); } + d.fields["datasetFileNaming"] = json!("dataSetName"); + for destination in ["none", "saveAndClose"] { + d.fields["destination"] = json!(destination); + let p = params(&d, "Test", vec![]); + assert!(p.get("datasetFileNaming").is_none(), "{destination}: {p}"); + assert!(p.get("destinationFolder").is_none(), "{destination}: {p}"); + } + d.fields["destination"] = json!("folder"); d.fields["source"] = json!("folder"); assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); } diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs new file mode 100644 index 0000000000..2cf0ab6127 --- /dev/null +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -0,0 +1,261 @@ +//! Actions panel menu › Insert Menu Item… (`ui.action.insertMenuItem`): the menu items that can be +//! steps of an action, to pick one from the list or find it by name. +//! +//! Its fields: `find` (the words the list is narrowed to), `command` and `params` (the item picked; +//! `command` is empty until one is), `note` (`none` or `several` when Find picked nothing), and +//! `set`, `action` and `step`, the place of the new step (no `set` and `action`: the recording in +//! progress). Picking an item runs nothing. OK inserts it; an invalid place is an error, and the +//! dialog stays open. + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, menus, widgets}; + +/// The dialog kind of Insert Menu Item. +pub const KIND: &str = "actionInsertMenuItem"; + +/// The most rows the list shows at once; Find narrows it. +const MAX_LISTED: usize = 200; + +/// The width of the Menu Item label. +const LABEL_W: f32 = 80.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Insert Menu Item").into(), + body, + confirm, + ok_enabled: Some(|_, d| !d.str("command").is_empty()), + min_width: 460.0, + ..DialogSpec::FORM +}; + +/// Opens Insert Menu Item for action `target` as (set, action), after `step`, else for the recording +/// in progress. +pub fn open(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option) { + let mut fields = json!({"find": "", "command": "", "params": {}, "note": ""}); + if let Some((set, action)) = target { + fields["set"] = json!(set); + fields["action"] = json!(action); + if let Some(step) = step { + fields["step"] = json!(step); + } + } + app.ui.dialog = Some(Dialog::new(KIND, fields)); +} + +/// A row of the list: an item of [`menus::insertable_items`], with what it shows and what Find +/// matches worked out once. +pub(crate) struct Row { + command: &'static str, + params: Value, + /// The menu path and label in the UI language (`Object › Group`). + shown: String, + /// The English path and label, the shown one and the command id, lowercased, one per line. + haystack: String, +} + +/// The rows in `lang`, for menus that name fonts in English when `english_names` is set. +fn build(lang: crate::i18n::Lang, english_names: bool) -> Vec { + menus::insertable_items(english_names) + .into_iter() + .map(|item| { + let parts = || item.path.iter().chain(std::iter::once(&item.label)).copied(); + let english = parts().collect::>().join(" › "); + let shown = parts().map(|s| crate::i18n::tr(lang, s)).collect::>().join(" › "); + let haystack = format!("{}\n{}\n{}", english.to_lowercase(), shown.to_lowercase(), item.command.to_lowercase()); + Row { command: item.command, params: item.params, shown, haystack } + }) + .collect() +} + +/// The rows, built again only when the language, the installed plug-ins, the font name setting or +/// the loaded fonts change, not on every frame. +fn rows(app: &VectorcraftApp, ctx: &egui::Context) -> Arc> { + type Key = (&'static str, u64, bool, u64, bool); + let lang = crate::i18n::current(); + let english_names = app.session.prefs.font_names_in_english; + let db = vectorcraft_text::FontDb::global(); + // Read before building, as the Font menu does: fonts that load meanwhile build the rows again. + let (cataloged, generation) = (db.installed_fonts_ready(), db.generation()); + let key: Key = (lang.code(), menus::plugin_revision(), english_names, generation, cataloged); + let id = egui::Id::unique("action-insert-menu-item-rows"); + if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, Arc>)>(id)) + && k == key + { + return v; + } + let built = Arc::new(build(lang, english_names)); + ctx.data_mut(|d| d.insert_temp::<(Key, Arc>)>(id, (key, built.clone()))); + built +} + +/// The rows that every word of `find` matches, in menu order. +fn matches<'a>(rows: &'a [Row], find: &str) -> impl Iterator { + let words: Vec = find.to_lowercase().split_whitespace().map(str::to_string).collect(); + rows.iter().filter(move |r| words.iter().all(|w| r.haystack.contains(w.as_str()))) +} + +/// Picks `row` in `d`. +fn pick(d: &mut Dialog, row: &Row) { + d.fields.insert("command".into(), json!(row.command)); + d.fields.insert("params".into(), row.params.clone()); + d.fields.insert("note".into(), json!("")); +} + +/// Find: picks the one row that `find` matches; with none or several, picks nothing and notes it. +fn find(rows: &[Row], d: &mut Dialog) { + let found: Vec<&Row> = matches(rows, &d.str("find")).take(2).collect(); + match found[..] { + [row] => pick(d, row), + [] => { + d.fields.insert("note".into(), json!("none")); + } + _ => { + d.fields.insert("note".into(), json!("several")); + } + } +} + +/// Whether `row` is the item picked in `d`. +fn picked(d: &Dialog, row: &Row) -> bool { + d.fields.get("command").and_then(Value::as_str) == Some(row.command) && d.fields.get("params") == Some(&row.params) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let rows = rows(app, ui.ctx()); + let dim = Tokens::get(ui.ctx()).text_dim; + let mut find_now = false; + ui.horizontal(|ui| { + if super::form::text_named(ui, d, "find", tl!("Find"), 300.0) { + d.fields.insert("note".into(), json!("")); + } + find_now = widgets::secondary_button(ui, tl!("Find")).clicked(); + }); + if find_now { + find(&rows, d); + } + match d.str("note").as_str() { + "none" => { + ui.label(egui::RichText::new(tl!("No menu item matches.")).color(dim)); + } + "several" => { + ui.label(egui::RichText::new(tl!("Several menu items match. Choose one from the list.")).color(dim)); + } + _ => {} + } + ui.add_space(4.0); + let mut chosen: Option = None; + let query = d.str("find"); + egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, row) in matches(&rows, &query).enumerate().take(MAX_LISTED) { + if ui.selectable_label(picked(d, row), row.shown.as_str()).clicked() { + chosen = Some(i); + } + } + }); + if let Some(row) = chosen.and_then(|i| matches(&rows, &query).nth(i)) { + pick(d, row); + } + ui.add_space(4.0); + let shown = rows.iter().find(|r| picked(d, r)).map_or_else( + || { + let command = d.str("command"); + if command.is_empty() { tl!("None").to_string() } else { command } + }, + |r| r.shown.clone(), + ); + widgets::label_row(ui, "Menu Item:", LABEL_W, |ui| { + ui.label(shown); + }); + ui.label(egui::RichText::new(tl!("Items that open a dialog, and File, Window and Help menu items, are not listed.")).color(dim)); + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut params = json!({"command": d.str("command"), "params": d.fields.get("params").cloned().unwrap_or_else(|| json!({}))}); + for key in ["set", "action", "step"] { + if let Some(value) = d.fields.get(key) { + params[key] = value.clone(); + } + } + let r = app.run(crate::panels::actions::INSERT_MENU_ITEM, params)?; + app.ui.dialog = None; + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::i18n::Lang; + + #[test] + fn find_picks_the_one_match_and_notes_none_or_several() { + let rows = build(Lang::EN, true); + let mut d = Dialog::new(KIND, json!({"find": "object group", "command": "", "params": {}, "note": ""})); + find(&rows, &mut d); + assert_eq!((d.str("note"), d.str("command")), ("several".to_string(), String::new()), "Group and Ungroup both match"); + d.fields.insert("find".into(), json!("OBJECT.UNGROUP")); + find(&rows, &mut d); + assert_eq!((d.str("command"), d.fields["params"].clone(), d.str("note")), ("object.ungroup".to_string(), json!({}), String::new())); + d.fields.insert("find".into(), json!("no such menu item here")); + find(&rows, &mut d); + assert_eq!((d.str("note"), d.str("command")), ("none".to_string(), "object.ungroup".to_string()), "a failed Find keeps the pick"); + } + + /// The list holds the menu items that run an engine command without asking for values first, + /// outside the application, File, Window and Help menus, and leaves out Undo, Redo, the Pastes, + /// Object › Align, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern and the + /// saved-selection, saved-view and recent-font items. + #[test] + fn the_list_holds_only_menu_items_that_can_be_steps() { + let items = menus::insertable_items(true); + assert!(items.len() > 100, "only {} items", items.len()); + for item in &items { + assert!(vectorcraft_engine::find_command(item.command).is_some(), "{item:?}"); + assert!(!item.label.ends_with('…'), "{item:?}"); + assert!(!["VectorCraft", "File", "Window", "Help"].contains(&item.path[0]), "{item:?}"); + assert!(item.params.is_object(), "{item:?}"); + } + let has = |command: &str| items.iter().any(|i| i.command == command); + for command in ["object.group", "object.ungroup", "object.arrange.bringToFront"] { + assert!(has(command), "{command}"); + } + for command in [ + "edit.undo", + "edit.redo", + "edit.paste", + "edit.pasteInFront", + "object.move", + "object.align", + "imageTrace.make", + "imageTrace.makeAndExpand", + "object.pattern.make", + "object.pattern.edit", + "file.save", + "view.zoomIn", + "select.recall1", + ] { + assert!(!has(command), "{command}"); + } + } + + /// Rows show their menu path in the UI language, and Find matches the English path, the shown + /// one and the command id. + #[test] + fn rows_show_the_translated_path_and_match_english_shown_text_and_ids() { + let de = Lang::from_code("de").unwrap(); + let rows = build(de, true); + let group = rows.iter().find(|r| r.command == "object.group").unwrap(); + assert_eq!(group.shown, format!("{} › {}", crate::i18n::tr(de, "Object"), crate::i18n::tr(de, "Group"))); + for words in ["object group", group.shown.as_str(), "object.group"] { + assert!(matches(&rows, words).any(|r| r.command == "object.group"), "{words}"); + } + let shared = rows.iter().any(|r| rows.iter().any(|o| o.command == r.command && o.params != r.params)); + assert!(shared, "items that share a command are listed apart, by their params"); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs new file mode 100644 index 0000000000..cc1a08b251 --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -0,0 +1,100 @@ +//! The Brushes panel's question when art Alt-dragged (Option-dragged on macOS) onto a brush that +//! strokes use is to replace its art ([`ask`]): Apply to Strokes, Leave Strokes or Cancel. Apply to +//! Strokes runs `brush.replaceArt` and the strokes redraw with the new art; Leave Strokes runs it +//! with `applyToStrokes: false`, which keeps the brush and its strokes as they were and adds a copy +//! of the brush with the new art. +//! +//! Fields: `name` (the brush), `ids` (the art), `apply` (set by the button pressed) and `__doc` (the +//! uid of the document it asks about). + +use serde_json::{Value, json}; + +use super::{DialogAction, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; +use crate::widgets; + +/// The dialog kind of the question. +pub const KIND: &str = "brushReplaceArt"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| { + tl!("Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?") + .to_string() + }, + body_with_actions: Some(body), + confirm, + ok: None, + max_width: Some(540.0), + ..DialogSpec::FORM +}; + +/// The field that holds the uid of the document the question is about. +const DOC: &str = "__doc"; + +/// Replace the art of brush `name` with the objects `ids`: at once when no stroke uses the brush, +/// else after asking whether the strokes take the new art. Art the brush cannot take (art with no +/// width, say) is refused before anything asks, with the reason in the status bar. +pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { + let params = json!({"name": name, "ids": ids}); + if super::brush_delete::used(app, &[name.to_string()]) != Some(true) { + if let Err(e) = app.run("brush.replaceArt", params) { + app.status(e); + } + return; + } + // A preview on a copy of the document checks the art without changing anything. + if !app.session.in_interaction() && app.session.begin_interaction("Replace Brush Art").is_ok() { + let checked = app.session.preview("brush.replaceArt", ¶ms); + // The interaction began above, on the active document: ending it puts that document back + // as it was, and can fail only when no document is open, when there is nothing to put back. + let _ = app.session.cancel_interaction(); + if let Err(e) = checked { + app.status(e.to_string()); + return; + } + } + ask(app, name, ids); +} + +/// Ask whether the strokes that use brush `name` take the art of the objects `ids`. +pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { + let doc = app.session.active().map(|d| d.uid); + app.ui.dialog = Some(Dialog::new(KIND, json!({"name": name, "ids": ids, "apply": true, DOC: doc}))); +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let mut action = DialogAction::None; + ui.horizontal(|ui| { + if widgets::primary_button_enabled(ui, tl!("Apply to Strokes"), true).clicked() { + d.fields.insert("apply".into(), json!(true)); + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("Leave Strokes")).clicked() { + d.fields.insert("apply".into(), json!(false)); + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("Cancel")).clicked() { + action = DialogAction::Cancel; + } + }); + action +} + +/// Closes before running. When another document has become the active one, it closes as Cancel does +/// and changes no brush. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + return Ok(json!({})); + } + let params = json!({ + "name": d.fields.get("name").cloned().unwrap_or(Value::Null), + "ids": d.fields.get("ids").cloned().unwrap_or_else(|| json!([])), + "applyToStrokes": d.bool("apply"), + }); + app.run("brush.replaceArt", params) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs new file mode 100644 index 0000000000..f42b7805c2 --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs @@ -0,0 +1,133 @@ +use egui::{Pos2, Rect, pos2, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, time: f64) -> egui::FullOutput { + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let input = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out +} + +fn press(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { + frame(ctx, app, vec![], time); + let out = frame(ctx, app, vec![], time + 0.1); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("dialog accessibility tree").nodes; + let button = nodes.iter().find(|(_, node)| node.label().map(str::trim) == Some(label)); + let bounds = button.and_then(|(_, node)| node.bounds()).expect("visible button"); + let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], time + 0.2); +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx +} + +fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 { + app.run("shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap() +} + +fn art_height(app: &mut VectorcraftApp, name: &str) -> f64 { + let art: vectorcraft_doc::Node = serde_json::from_value(app.run("brush.get", json!({"name": name})).unwrap()["art"].clone()).unwrap(); + art.geometric_bounds().unwrap().height() +} + +/// An art brush "Bar" (40 × 8 pt) painting a path, and a 40 × 20 pt rectangle: → (path, rectangle). +fn used_brush(app: &mut VectorcraftApp) -> (NodeId, u64) { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let bar = rect(app, 10.0, 10.0, 40.0, 8.0); + app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [bar]})).unwrap(); + let path = NodeId(rect(app, 100.0, 100.0, 80.0, 40.0)); + app.run("brush.apply", json!({"name": "Bar", "ids": [path.0]})).unwrap(); + (path, rect(app, 10.0, 40.0, 40.0, 20.0)) +} + +#[test] +fn an_unused_brush_takes_the_art_without_asking() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let bar = rect(&mut app, 10.0, 10.0, 40.0, 8.0); + app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [bar]})).unwrap(); + let tall = rect(&mut app, 10.0, 40.0, 40.0, 20.0); + replace(&mut app, "Bar", &[tall]); + assert!(app.ui.dialog.is_none()); + assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6); +} + +#[test] +fn apply_to_strokes_gives_the_brush_the_new_art() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (path, tall) = used_brush(&mut app); + replace(&mut app, "Bar", &[tall]); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND), "strokes use Bar: it asks"); + let ctx = context(); + let before = app.session.active().unwrap().history.undo.len(); + press(&ctx, &mut app, "Apply to Strokes", 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), Some("Bar")); +} + +#[test] +fn leave_strokes_adds_a_copy_and_cancel_changes_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (path, tall) = used_brush(&mut app); + let ctx = context(); + let before = app.session.active().unwrap().history.undo.len(); + replace(&mut app, "Bar", &[tall]); + press(&ctx, &mut app, "Cancel", 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); + replace(&mut app, "Bar", &[tall]); + press(&ctx, &mut app, "Leave Strokes", 1.0); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "Bar stays as it was"); + assert!((art_height(&mut app, "Bar copy") - 20.0).abs() < 1e-6); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), Some("Bar")); +} + +/// Art a used brush cannot take is refused before the question: no dialog, the reason in the status +/// bar, and the document and its undo history as they were. +#[test] +fn art_with_no_width_is_refused_before_it_asks() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let _ = used_brush(&mut app); + let flat = app.run("shape.line", json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap(); + let st = app.session.active().unwrap(); + let (doc, steps) = (st.doc.clone(), st.history.undo.len()); + replace(&mut app, "Bar", &[flat]); + assert!(app.ui.dialog.is_none(), "nothing asks"); + assert!(app.ui.status.contains("the selected art has no width"), "{}", app.ui.status); + let st = app.session.active().unwrap(); + assert!(st.interaction.is_none()); + assert_eq!(*st.doc, *doc); + assert_eq!(st.history.undo.len(), steps); +} + +#[test] +fn a_button_changes_no_brush_after_another_document_became_active() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (_, tall) = used_brush(&mut app); + let ctx = context(); + replace(&mut app, "Bar", &[tall]); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + press(&ctx, &mut app, "Apply to Strokes", 0.0); + assert!(app.ui.dialog.is_none()); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); +} diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index d1ca76cc58..54df0ab912 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -26,9 +26,9 @@ const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; /// The on, off or unset checkboxes. const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman"]; /// The attributes of Advanced Character Formats, in the order the section shows them. -const ADVANCED: &[&str] = &["h_scale", "v_scale", "baseline_shift", "rotation", "language"]; +const ADVANCED: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "language"]; /// The number fields of Advanced Character Formats. -const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "rotation"]; +const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation"]; /// The attributes of Character Color. const COLOR: &[&str] = &["fill", "stroke", "stroke_width", "overprint_fill", "overprint_stroke"]; /// The fields of Character Color: the fill and stroke paints, their tints in percent, the stroke @@ -78,6 +78,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "h_scale", "v_scale", "baseline_shift", + "tcyUpDown", + "tcyLeftRight", "rotation", "language", "fill", @@ -250,6 +252,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "h_scale" => tl!("Horizontal Scale"), "v_scale" => tl!("Vertical Scale"), "baseline_shift" => tl!("Baseline Shift"), + "tcyUpDown" => tl!("Tate-chu-yoko Up/Down"), + "tcyLeftRight" => tl!("Tate-chu-yoko Left/Right"), "rotation" => tl!("Character Rotation"), "fill_tint" => tl!("Fill Tint"), "stroke_tint" => tl!("Stroke Tint"), @@ -281,7 +285,7 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { if ["h_scale", "v_scale"].contains(&key) && !(1.0..=10000.0).contains(&n) { return Err(format!("{label} must be a number from 1 to 10000")); } - if key == "baseline_shift" && !(-1296.0..=1296.0).contains(&n) { + if ["baseline_shift", "tcyUpDown", "tcyLeftRight"].contains(&key) && !(-1296.0..=1296.0).contains(&n) { return Err(format!("{label} must be a number from -1296 to 1296")); } // Weight from 0 to the document limit, a tint from 0% to 100%. @@ -564,7 +568,7 @@ pub(crate) fn reset_basic(d: &mut Dialog) { } } -/// Reset Panel in Advanced Character Formats: its five attributes become unset. +/// Reset Panel in Advanced Character Formats: its seven attributes become unset. pub(crate) fn reset_advanced(d: &mut Dialog) { d.fields.insert("__resetAdvanced".into(), json!(true)); for key in ADVANCED_NUMBERS { @@ -718,14 +722,16 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// Advanced Character Formats: Horizontal Scale, Vertical Scale, Baseline Shift, Character Rotation -/// and Language, each empty (unset) or set. +/// Advanced Character Formats: Horizontal Scale, Vertical Scale, Baseline Shift, the Tate-chu-yoko +/// Up/Down and Left/Right, Character Rotation and Language, each empty (unset) or set. pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("character-style-advanced").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { for (key, caption, unit) in [ ("h_scale", tl!("Horizontal Scale"), "%"), ("v_scale", tl!("Vertical Scale"), "%"), ("baseline_shift", tl!("Baseline Shift"), "pt"), + ("tcyUpDown", tl!("Tate-chu-yoko Up/Down"), "pt"), + ("tcyLeftRight", tl!("Tate-chu-yoko Left/Right"), "pt"), ("rotation", tl!("Character Rotation"), "°"), ] { let row = ui.label(caption); @@ -1473,11 +1479,19 @@ mod tests { } #[test] - fn advanced_section_shows_its_five_controls() { + fn advanced_section_shows_its_seven_controls() { let mut d = dialog_for(json!({})); let mut app = app(); let shown = crate::tests_labels::painted_text(&mut app, |_, ui| advanced_body(ui, &mut d)); - for label in ["Horizontal Scale", "Vertical Scale", "Baseline Shift", "Character Rotation", "Language:"] { + for label in [ + "Horizontal Scale", + "Vertical Scale", + "Baseline Shift", + "Tate-chu-yoko Up/Down", + "Tate-chu-yoko Left/Right", + "Character Rotation", + "Language:", + ] { assert!(shown.contains(label), "{label}: {shown}"); } } @@ -1569,6 +1583,85 @@ mod tests { assert!(!def.attrs.contains_key("v_scale")); } + #[test] + fn tate_chu_yoko_offsets_show_set_reset_and_keep_their_limits() { + let d = dialog_for(json!({"tcyUpDown": 2.0, "size": 12.0})); + assert_eq!((d.fields["tcyUpDown"].clone(), d.fields["tcyLeftRight"].clone()), (json!(2.0), json!(""))); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"tcyUpDown": 2.0, "size": 12.0}))); + // A value a style captured from scaled text stays while its field is untouched. + assert_eq!(edited_attrs(&dialog_for(json!({"tcyLeftRight": 3000.0}))).unwrap(), attrs(json!({"tcyLeftRight": 3000.0}))); + + let mut d = dialog_for(json!({"tcyUpDown": 2.0})); + d.fields.insert("tcyUpDown".into(), json!("")); + d.fields.insert("tcyLeftRight".into(), json!("-1296")); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"tcyLeftRight": -1296.0}))); + d.fields.insert("tcyLeftRight".into(), json!("0")); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"tcyLeftRight": 0.0}))); + for (key, value, message) in [ + ("tcyUpDown", "1296.1", "Tate-chu-yoko Up/Down must be a number from -1296 to 1296"), + ("tcyLeftRight", "-1296.1", "Tate-chu-yoko Left/Right must be a number from -1296 to 1296"), + ("tcyUpDown", "high", "Tate-chu-yoko Up/Down must be a number"), + ("tcyLeftRight", "NaN", "Tate-chu-yoko Left/Right must be a number"), + ] { + let mut d = dialog_for(json!({})); + d.fields.insert(key.into(), json!(value)); + assert_eq!(edited_attrs(&d).unwrap_err(), message, "{key} {value}"); + } + + let mut d = dialog_for(json!({"tcyUpDown": 2.0, "tcyLeftRight": -1.0, "size": 12.0})); + d.fields.insert("section".into(), json!("advanced")); + reset_section(&mut d); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"size": 12.0}))); + } + + #[test] + fn tate_chu_yoko_offsets_preview_cancel_and_commit_to_the_style_and_its_text() { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0, "tcyLeftRight": 0.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 2, "end": 4, "tcyLeftRight": 5.0})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("advanced")); + d.fields.insert("tcyUpDown".into(), json!("4")); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs["tcyUpDown"], json!(4.0)); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("tcyUpDown".into(), json!("4")); + d.fields.insert("tcyLeftRight".into(), json!("-3")); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.history.undo.len(), undo + 1); + assert_eq!(state.doc.char_styles[0].attrs, attrs(json!({"size": 24.0, "tcyUpDown": 4.0, "tcyLeftRight": -3.0}))); + let vectorcraft_doc::NodeKind::Text(t) = &state.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs.iter().map(|r| (r.style.tcy_up_down, r.style.tcy_left_right)).collect::>(), [(4.0, -3.0), (4.0, 5.0)]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + + app.run("ui.newCharStyle", json!({})).unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Shifted")); + d.fields.insert("tcyLeftRight".into(), json!("6")); + } + super::super::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let def = doc.char_styles.iter().find(|def| def.name == "Shifted").unwrap(); + assert_eq!(def.attrs["tcyLeftRight"], json!(6.0)); + } + /// The negated tags of the twenty stylistic sets: an explicit empty Stylistic Sets choice. fn no_sets() -> Vec { vectorcraft_text::EXTRA_FEATURES[..20].iter().map(|s| format!("-{s}")).collect() diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 0a722cbcf8..7c9aaf6873 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -64,11 +64,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, and Type Tools › Release Type on a Path -/// works the same way (#5532). (Cancel rolls a preview back whichever dialog started it.) +/// works the same way (#5532), and so does Image Tools › Remove Background. (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" | crate::addons::typetools::RELEASE => true, + "type.pathOptions" | crate::addons::typetools::RELEASE | crate::addons::image::REMOVE_BACKGROUND => true, _ => false, } } @@ -102,9 +103,10 @@ fn lengths(command: &str) -> &'static [&'static str] { "shape.flare" => &["diameter", "pathLength"], "perspective.grid.set" => &["cell", "distance"], "object.repeat.options" => &["radius", "hSpacing", "vSpacing"], - "text.areaOptions" => &["width", "height", "gutter", "rowGutter", "inset", "firstBaselineMin"], + "text.areaOptions" => &["width", "height", "gutter", "rowGutter", "inset", "firstBaselineMin", "lineGap"], "type.pathOptions" => &["spacing"], "object.pathfinder.trap" => &["thickness"], + crate::addons::cutting::BRIDGES => &["width"], _ => &[], } } @@ -117,6 +119,8 @@ fn order(command: &str) -> &'static [&'static str] { "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], crate::addons::typetools::RELEASE => &["mode", "keepOriginal"], + crate::addons::image::REMOVE_BACKGROUND => &["background", "colors", "contiguous", "match", "tolerance", "softness"], + crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], _ => &[], } } @@ -127,6 +131,7 @@ fn choices(command: &str, key: &str) -> Option { ("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), + (crate::addons::cutting::BRIDGES, "direction") => Some(crate::addons::cutting::BRIDGE_DIRECTIONS), ("text.areaOptions", "fit") => Some(AREA_FIT), ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), @@ -136,6 +141,8 @@ fn choices(command: &str, key: &str) -> Option { ("graph.setType", "pieLegend") => Some(PIE_LEGEND), ("graph.setType", "piePosition") => Some(PIE_POSITION), ("graph.setType", "pieSort") => Some(PIE_SORT), + (crate::addons::image::REMOVE_BACKGROUND, "background") => Some(crate::addons::image::BACKGROUNDS), + (crate::addons::image::REMOVE_BACKGROUND, "match") => Some(crate::addons::image::MATCHES), _ => None, } } @@ -156,8 +163,8 @@ const RASTERIZE_CMYK: form::Choices = &[("CMYK", "cmyk"), ("Grayscale", "graysca /// Type on a Path Options › Align to Path. const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")]; -/// Area Type Options › Fit. -const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText")]; +/// Area Type Options › Fit (Block is Dynamic Text's, as `type.dynamicText` sets it). +const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")]; /// Area Type Options › First Baseline. const FIRST_BASELINE: form::Choices = diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 06e96e45fe..6f51be44d9 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -63,6 +63,52 @@ pub(crate) fn ask_replace(app: &mut VectorcraftApp, path: &str, typed: &str) { app.ui.dialog = Some(Dialog::new(REPLACE, fields)); } +/// The dialog kind of the question whether a save or export may replace the files it writes beside +/// the one picked in the save panel ([`ask_replace_files`]). Fields: `message`, `detail`, `files` +/// (their paths), `allowed` (files an earlier OK allowed), `doc` (the document's uid), `__command` +/// and `__params`. +pub const REPLACE_FILES: &str = "replaceFiles"; + +pub(super) const REPLACE_FILES_SPEC: DialogSpec = DialogSpec { confirm: replace_files, ..SPEC }; + +/// Ask whether to replace `files`, files that are there beside the one a save or export of the +/// document `doc` (its uid) writes, which the save panel did not ask about (a file per artboard, a +/// linked image). OK runs `command` with `params` again on that document, now replacing those +/// files and `allowed` (those an earlier OK allowed); Cancel writes nothing. +pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[String], allowed: &[String], command: &str, params: Value) { + let name = files.first().map(|f| vectorcraft_engine::cmd::fileio::file_name(f)).unwrap_or_default(); + let message = crate::i18n::fmt(tl!("“{name}” already exists. Replace it?"), &[("name", &name)]); + // Several: every one of them, by name. + let detail = match files { + [_, _, ..] => files.iter().map(|f| vectorcraft_engine::cmd::fileio::file_name(f)).collect::>().join("\n"), + _ => String::new(), + }; + let fields = + json!({"message": message, "detail": detail, "files": files, "allowed": allowed, "doc": doc, "__command": command, "__params": params}); + let d = Dialog::new(REPLACE_FILES, fields); + // Asked when a Background Save or Export ends: a dialog open then stays, and this waits its turn + // (however many messages wait: the save or export needs the answer). + match app.ui.dialog { + None => app.ui.dialog = Some(d), + Some(_) => app.ui.told.push(d), + } +} + +/// OK on [`ask_replace_files`]: what asked runs again on its document, and the files the question +/// named are replaced; one it writes now that was not named is asked about again. The save or export +/// reads the allowance when it starts, before a background one hands its work to the worker. +fn replace_files(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + if !crate::picks::on_document(app, d.fields.get("doc").and_then(Value::as_u64)) { + return Ok(Value::Null); + } + let paths = |k: &str| d.fields.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string); + app.picks.replace_files_ok = paths("allowed").chain(paths("files")).collect(); + let r = confirm(app, d); + app.picks.replace_files_ok.clear(); + r +} + /// The dialog kind of the question Reset Preferences asks over the Preferences dialog /// ([`ask_reset_prefs`]). Fields: `message`, `detail`. pub const RESET_PREFS: &str = "resetPreferences"; diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index a449156e74..1946cc86b2 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -1,13 +1,19 @@ //! File → Document Setup: General (units, bleed, Edit Artboards, outline images, the substituted //! glyphs highlight), Transparency (grid size and colours, simulated paper, flattener preset, white -//! overprint) and Type (language, quotes, superscript/subscript/small caps, text export) tabs. +//! overprint), Type (language, quotes, superscript/subscript/small caps, text export) and Color +//! (document color mode and assigned profiles) tabs. //! -//! Fields: what `document.setup` reports (and takes back), plus `tab` and `bleedLinked`. OK runs -//! `document.setup` with them: one undo step. On an error the dialog stays open. +//! Fields: what `document.setup` reports (and takes back), plus `tab`, `bleedLinked` and the Color +//! tab's `colorMode`, `convertColors`, `rgbProfile` and `cmykProfile` (null: the working space). +//! OK runs `document.setup` with them: one undo step. When the Color tab changed something, OK runs +//! `document.setup`, `edit.assignProfile` and `file.documentColorMode` in one `command.batch`, +//! and the document's changes are still one undo step. On an error the dialog stays open. -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; +use vectorcraft_color::cms::ProfileKind; use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES}; -use vectorcraft_doc::{GridSize, Quotes, Unit}; +use vectorcraft_doc::{ColorMode, GridSize, Quotes, Unit}; +use vectorcraft_engine::cmd::colormgmt::doc_profiles; use super::{DialogSpec, form}; use crate::state::Dialog; @@ -15,10 +21,13 @@ use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; pub(super) const KIND: &str = "documentSetup"; -const TABS: [&str; 3] = ["General", "Transparency", "Type"]; +const TABS: [&str; 4] = ["General", "Transparency", "Type", "Color"]; /// Dialog-only fields `document.setup` doesn't take. -const UI_ONLY: [&str; 2] = ["tab", "bleedLinked"]; +const UI_ONLY: [&str; 6] = ["tab", "bleedLinked", "colorMode", "convertColors", "rgbProfile", "cmykProfile"]; pub(super) const LABEL: f32 = 130.0; +/// The profile rows' entry for no assigned profile: the document uses the working space. +const WORKING_RGB: &str = "Working RGB (don't tag)"; +const WORKING_CMYK: &str = "Working CMYK (don't tag)"; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Document Setup").into(), body, confirm, min_width: 540.0, max_width: Some(540.0), ..DialogSpec::FORM }; @@ -29,13 +38,76 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let linked = fields["bleed"].as_array().is_some_and(|b| b.windows(2).all(|w| w[0] == w[1])); fields["bleedLinked"] = json!(linked); fields["tab"] = json!(TABS[0]); + if let Some(st) = app.session.active() { + let (rgb, cmyk) = doc_profiles(&st.doc); + fields["colorMode"] = json!(mode_id(st.doc.color_mode)); + fields["rgbProfile"] = json!(rgb); + fields["cmykProfile"] = json!(cmyk); + } + fields["convertColors"] = json!(true); app.ui.dialog = Some(Dialog::new(KIND, fields)); Ok(Value::Null) } +/// The `mode` param of `file.documentColorMode` for `m`. +fn mode_id(m: ColorMode) -> &'static str { + match m { + ColorMode::Rgb => "rgb", + ColorMode::Cmyk => "cmyk", + } +} + +/// The commands the Color tab's changes run, as `command.batch` steps, in the order OK runs them: +/// Edit › Assign Profile first, so that a mode change converts through the profiles it assigns, +/// then File › Document Color Mode. Empty when the tab matches the active document. A field the +/// dialog holds with a value of the wrong kind is an error, and then nothing runs; an omitted +/// field leaves its setting as it is (`convertColors`: converts). +fn color_commands(app: &VectorcraftApp, d: &Dialog) -> Result, String> { + let Some(st) = app.session.active() else { return Ok(vec![]) }; + let mut out = vec![]; + let (rgb, cmyk) = doc_profiles(&st.doc); + let mut assign = Map::new(); + for (key, param, current) in [("rgbProfile", "rgb", rgb), ("cmykProfile", "cmyk", cmyk)] { + let chosen = match d.fields.get(key) { + None => continue, + Some(Value::Null) => None, + Some(Value::String(n)) => Some(n.clone()), + Some(_) => return Err(format!("`{key}` must be a profile name or null")), + }; + if chosen != current { + assign.insert(param.into(), json!(chosen)); + } + } + let mode = match d.fields.get("colorMode") { + None => None, + Some(Value::String(m)) if m.eq_ignore_ascii_case("rgb") => Some(ColorMode::Rgb), + Some(Value::String(m)) if m.eq_ignore_ascii_case("cmyk") => Some(ColorMode::Cmyk), + Some(_) => return Err("`colorMode` must be one of rgb, cmyk".into()), + }; + let key = "convertColors"; + let convert = match d.fields.get(key) { + None => true, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(format!("`{key}` must be true or false")), + }; + if !assign.is_empty() { + out.push(json!({"command": "edit.assignProfile", "params": assign})); + } + if let Some(mode) = mode.filter(|m| *m != st.doc.color_mode) { + out.push(json!({"command": "file.documentColorMode", "params": {"mode": mode_id(mode), "convert": convert}})); + } + Ok(out) +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let params = d.fields.iter().filter(|(k, _)| !UI_ONLY.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); - let r = app.run("document.setup", Value::Object(params)); + let params: Map = d.fields.iter().filter(|(k, _)| !UI_ONLY.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + let color = color_commands(app, d)?; + let r = if color.is_empty() { + app.run("document.setup", Value::Object(params)) + } else { + let commands: Vec = std::iter::once(json!({"command": "document.setup", "params": params})).chain(color).collect(); + app.run("command.batch", json!({"label": "Document Setup", "commands": commands})) + }; if r.is_ok() { app.ui.dialog = None; } @@ -54,7 +126,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { match tab { 0 => close = general(app, ui, d), 1 => transparency(app, ui, d), - _ => typography(ui, d), + 2 => typography(ui, d), + _ => color(app, ui, d), } }); close @@ -208,10 +281,40 @@ fn typography(ui: &mut egui::Ui, d: &mut Dialog) { choice(ui, d, "exportText", tl!("Export:"), &[("editable", tl!("Preserve Text Editability")), ("appearance", tl!("Preserve Text Appearance"))]); } +/// The Color tab: the document color mode, whether a mode change converts the colors (unchecked: +/// they keep their numbers), and the RGB and CMYK profiles assigned to the document. +fn color(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + widgets::subheader(ui, tl!("Document Color Mode")); + choice(ui, d, "colorMode", tl!("Color Mode:"), &[("rgb", "RGB Color"), ("cmyk", "CMYK Color")]); + let mode = d.str("colorMode"); + let changes = app.session.active().is_some_and(|st| mode_id(st.doc.color_mode) != mode); + let label = if mode == "cmyk" { tl!("Convert to CMYK") } else { tl!("Convert to RGB") }; + widgets::label_row(ui, "", LABEL, |ui| { + let on = d.bool("convertColors"); + if widgets::check(ui, label, on, changes) { + d.fields.insert("convertColors".into(), json!(!on)); + } + }); + ui.add_space(14.0); + widgets::subheader(ui, tl!("Assign Profile")); + for (key, label, kind, working) in + [("rgbProfile", tl!("RGB:"), ProfileKind::Rgb, WORKING_RGB), ("cmykProfile", tl!("CMYK:"), ProfileKind::Cmyk, WORKING_CMYK)] + { + let current = d.fields.get(key).and_then(Value::as_str).unwrap_or(working).to_string(); + widgets::label_row(ui, label, LABEL, |ui| { + if let Some(n) = crate::panels::separations::profile_dropdown(ui, key, ¤t, kind, Some(working)) { + d.fields.insert(key.into(), if n == working { Value::Null } else { json!(n) }); + } + }); + } +} + #[cfg(test)] mod tests { use egui::{Event, PointerButton, Pos2, Rect, vec2}; use serde_json::json; + use vectorcraft_color::{Color, Paint, cms}; + use vectorcraft_doc::{ColorMode, NodeId}; use vectorcraft_engine::Session; use crate::VectorcraftApp; @@ -302,7 +405,7 @@ mod tests { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("file.documentSetup", json!({})).unwrap(); - for tab in ["General", "Transparency", "Type"] { + for tab in ["General", "Transparency", "Type", "Color"] { app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!(tab)); frame(&mut app); } @@ -343,4 +446,193 @@ mod tests { crate::dialogs::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); } + + /// A new document with a red square → the app and the square. + fn red_square() -> (VectorcraftApp, NodeId) { + 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": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [id], "color": "#ff0000"})).unwrap(); + (app, NodeId(id)) + } + + fn fill(app: &VectorcraftApp, id: NodeId) -> Paint { + app.session.active().unwrap().doc.node(id).unwrap().appearance.fill().unwrap().paint.clone() + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// Opens Document Setup on the Color tab and sets `fields` in it. + fn color_tab(app: &mut VectorcraftApp, fields: serde_json::Value) { + app.run("file.documentSetup", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("tab".into(), json!("Color")); + for (k, v) in fields.as_object().unwrap() { + d.fields.insert(k.clone(), v.clone()); + } + } + + /// The Color tab opens on the document's color mode and assigned profiles, and shows them. + /// The CMYK profile assigned is the working one, so the process-wide color settings stay as + /// they are for the other tests. + #[test] + fn color_tab_shows_the_color_mode_and_profiles() { + let (mut app, _) = red_square(); + let working = cms::active_settings().cmyk; + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("edit.assignProfile", json!({"cmyk": working})).unwrap(); + let steps = undo_steps(&app); + color_tab(&mut app, json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("colorMode"), d.str("cmykProfile"), d.fields["rgbProfile"].clone()), ("cmyk".into(), working.clone(), json!(null))); + assert!(d.bool("convertColors")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for shown in ["CMYK Color", "Convert to CMYK", "Working RGB (don't tag)", working.as_str()] { + assert!(texts.iter().any(|t| t == shown), "no {shown} in {texts:?}"); + } + // Picking the other mode names the conversion OK makes. + app.ui.dialog.as_mut().unwrap().fields.insert("colorMode".into(), json!("rgb")); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "Convert to RGB"), "{texts:?}"); + app.ui.dialog.as_mut().unwrap().fields.insert("colorMode".into(), json!("cmyk")); + // OK with nothing changed records nothing. + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_steps(&app), steps); + } + + /// OK with a new mode converts the colors as File › Document Color Mode does, together with the + /// dialog's other changes, in one undo step. + #[test] + fn ok_converts_the_color_mode_with_the_other_changes_in_one_undo_step() { + let (mut app, id) = red_square(); + let (mut menu, menu_id) = red_square(); + menu.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let steps = undo_steps(&app); + color_tab(&mut app, json!({"colorMode": "cmyk", "bleed": [9, 9, 9, 9]})); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_mode, st.doc.setup.bleed), (ColorMode::Cmyk, [9.0; 4])); + assert_eq!(fill(&app, id), fill(&menu, menu_id)); + assert!(matches!(fill(&app, id), Paint::Solid { color: Color::Cmyk { .. }, .. }), "{:?}", fill(&app, id)); + assert_eq!(undo_steps(&app), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_mode, st.doc.setup.bleed), (ColorMode::Rgb, [0.0; 4])); + assert_eq!(fill(&app, id), Paint::solid(Color::from_hex("ff0000").unwrap())); + } + + /// With Convert unchecked the mode changes and the colors keep their numbers. + #[test] + fn ok_without_convert_keeps_the_color_numbers() { + let (mut app, id) = red_square(); + let before = fill(&app, id); + let steps = undo_steps(&app); + color_tab(&mut app, json!({"colorMode": "cmyk", "convertColors": false})); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.color_mode, ColorMode::Cmyk); + assert_eq!(fill(&app, id), before); + assert_eq!(undo_steps(&app), steps + 1); + } + + /// OK assigns the profiles picked, with the dialog's other changes, in one undo step; the + /// working-space entry assigns none. + #[test] + fn ok_assigns_the_profiles_with_the_other_changes_in_one_undo_step() { + let (mut app, _) = red_square(); + let working = cms::active_settings().cmyk; + let steps = undo_steps(&app); + color_tab(&mut app, json!({"cmykProfile": working, "bleed": [9, 9, 9, 9]})); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_profiles.cmyk.clone(), st.doc.color_profiles.rgb.clone()), (Some(working.clone()), None)); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([9.0; 4], ColorMode::Rgb)); + assert_eq!(undo_steps(&app), steps + 1); + // Back to the working space: no profile assigned. + color_tab(&mut app, json!({"cmykProfile": null})); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.color_profiles.cmyk, None); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_profiles.cmyk.clone(), st.doc.setup.bleed), (None, [0.0; 4])); + } + + /// OK assigns the RGB profile picked, in one undo step. + #[test] + fn ok_assigns_the_rgb_profile() { + let (mut app, _) = red_square(); + let working = cms::active_settings().rgb; + let steps = undo_steps(&app); + color_tab(&mut app, json!({"rgbProfile": working})); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_profiles.rgb.clone(), st.doc.color_profiles.cmyk.clone()), (Some(working), None)); + assert_eq!(undo_steps(&app), steps + 1); + } + + /// A profile and a mode changed in one OK: Assign Profile runs before Document Color Mode, so + /// the conversion goes through the profile picked. + #[test] + fn a_profile_and_a_mode_change_assign_the_profile_first() { + let (mut app, _) = red_square(); + color_tab(&mut app, json!({"colorMode": "cmyk", "cmykProfile": cms::DEVICE_CMYK})); + let commands = super::color_commands(&app, app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!( + commands, + vec![ + json!({"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}), + json!({"command": "file.documentColorMode", "params": {"mode": "cmyk", "convert": true}}), + ] + ); + } + + /// A Color tab field with a value of the wrong kind is an error: the dialog stays open and + /// nothing changes, the profile picked with it included. + #[test] + fn a_bad_color_field_is_an_error_and_changes_nothing() { + let bad = [ + ("colorMode", json!("lab")), + ("colorMode", json!(null)), + ("rgbProfile", json!(5)), + ("cmykProfile", json!(true)), + ("convertColors", json!("no")), + ]; + for (key, value) in bad { + let (mut app, id) = red_square(); + let before = fill(&app, id); + let steps = undo_steps(&app); + color_tab(&mut app, json!({"colorMode": "cmyk", "cmykProfile": cms::active_settings().cmyk})); + app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), value.clone()); + assert!(super::color_commands(&app, app.ui.dialog.as_ref().unwrap()).is_err(), "{key}: {value}"); + assert!(crate::dialogs::confirm(&mut app).is_err(), "{key}: {value}"); + assert!(app.ui.dialog.is_some()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_mode, st.doc.color_profiles.cmyk.clone()), (ColorMode::Rgb, None), "{key}: {value}"); + assert_eq!(fill(&app, id), before); + assert_eq!(undo_steps(&app), steps); + } + } + + /// Cancel leaves the color mode, the colors and the history as they were. + #[test] + fn cancel_changes_no_color_setting() { + let (mut app, id) = red_square(); + let before = fill(&app, id); + let steps = undo_steps(&app); + color_tab(&mut app, json!({"colorMode": "cmyk", "cmykProfile": cms::active_settings().cmyk})); + click_dialog_button(&mut app, "Cancel"); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.color_mode, st.doc.color_profiles.cmyk.clone()), (ColorMode::Rgb, None)); + assert_eq!(fill(&app, id), before); + assert_eq!(undo_steps(&app), steps); + } } diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index cc52623931..498d854fe9 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -1,8 +1,8 @@ //! DXF Options (Export As → DXF): a preset (Custom, or CNC / CAM, which sets the options below for //! cutting software and shows Custom again once one is changed), version, scale (1 unit of the -//! art = N drawing units) and lineweights, number of colours, the format of placed images, -//! Preserve Appearance or Maximize Editability, and Export Selected Art Only, Alter Paths for -//! Appearance and Outline Text. +//! art = N drawing units) and lineweights, number of colours, the format of placed images and +//! Include Placed Images, Preserve Appearance or Maximize Editability, and Export Selected Art +//! Only, Alter Paths for Appearance, Outline Text and Include Fill Hatches. //! //! Fields: `document.export` params (`format: dxf`, `path?`, the artboard choice) and the DXF //! options of `document.exportDxf`. OK remembers the options for next time and writes the file @@ -58,6 +58,8 @@ fn preset_fields(preset: DxfPreset) -> Map { ("scaleLineweights", json!(o.scale_lineweights)), ("colors", json!(o.colors.id())), ("rasterFormat", json!(o.raster.id())), + ("includeImages", json!(o.include_images)), + ("includeHatches", json!(o.include_hatches)), ("preserve", json!(o.preserve.id())), ("alterPaths", json!(o.alter_paths)), ("outlineText", json!(o.outline_text)), @@ -140,6 +142,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } let rasters: Vec<(&str, &str)> = RasterFormat::ALL.iter().map(|r| (r.id(), r.label())).collect(); choice(ui, d, "rasterFormat", tl!("Raster File Format:"), &rasters); + ui.horizontal(|ui| { + ui.add_space(LABEL + 8.0); + check(ui, d, "includeImages", tl!("Include Placed Images")); + }); ui.add_space(10.0); widgets::subheader(ui, tl!("Export Option")); let preserve = Preserve::from_id(&d.str("preserve")).unwrap_or_default(); @@ -162,6 +168,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if widgets::check(ui, tl!("Outline Text"), appearance || d.bool("outlineText"), !appearance) { d.fields.insert("outlineText".into(), json!(!d.bool("outlineText"))); } + check(ui, d, "includeHatches", tl!("Include Fill Hatches")); ui.add_space(8.0); super::form::caption( ui, diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index febbc6488a..777c872494 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -382,19 +382,28 @@ fn choices(effect: &str, key: &str) -> Option { /// The parameters whose dialogs list their values in their own bodies, as (label, value), each /// label as that dialog passes it to its dropdown or radio buttons, which translate it into the UI -/// language: Revolve's edge, the bevel of both Extrude & Bevels (Rounded translated in the "3d" -/// context first), Extrude & Bevel (Classic)'s surface and shading color, every Warp style's +/// language: the edge of both Revolves, the bevel of both Extrude & Bevels (Rounded translated in +/// the "3d" context first), the surface and shading color of the classic 3D effects, every Warp style's /// orientation, Rasterize's Color Model (its `document` value labeled /// CMYK when `cmyk`, for a document in CMYK, and RGB otherwise), Background and Anti-aliasing, and /// the channel of Levels and Curves. pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option> { let c3 = |s: &'static str| crate::i18n::tr_ctx(crate::i18n::current(), "3d", s); Some(match (effect, key) { - (vectorcraft_effects::REVOLVE, "edge") => vec![(tl!("Left"), "left"), (tl!("Right"), "right")], - (vectorcraft_effects::CLASSIC_EXTRUDE, "surface") => { + (vectorcraft_effects::REVOLVE | vectorcraft_effects::CLASSIC_REVOLVE, "edge") => vec![(tl!("Left"), "left"), (tl!("Right"), "right")], + ( + vectorcraft_effects::REVOLVE | vectorcraft_effects::EXTRUDE | vectorcraft_effects::INFLATE | vectorcraft_effects::ROTATE, + "shadowPosition", + ) => { + vec![(tl!("Behind Object"), "behind"), (tl!("Below Object"), "below")] + } + (vectorcraft_effects::CLASSIC_EXTRUDE | vectorcraft_effects::CLASSIC_REVOLVE, "surface") => { vec![(tl!("Wireframe"), "wireframe"), (tl!("No Shading"), "none"), (tl!("Diffuse"), "diffuse"), (tl!("Plastic"), "plastic")] } - (vectorcraft_effects::CLASSIC_EXTRUDE, "shadingColor") => vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none")], + (vectorcraft_effects::CLASSIC_ROTATE, "surface") => vec![(tl!("No Shading"), "none"), (tl!("Diffuse"), "diffuse")], + (vectorcraft_effects::CLASSIC_EXTRUDE | vectorcraft_effects::CLASSIC_REVOLVE | vectorcraft_effects::CLASSIC_ROTATE, "shadingColor") => { + vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none")] + } (vectorcraft_effects::EXTRUDE | vectorcraft_effects::CLASSIC_EXTRUDE, "bevel") => vec![ (tl!("None"), "none"), (tl!("Classic"), "classic"), @@ -873,6 +882,13 @@ fn command(d: &Dialog) -> (&'static str, Value) { p["item"] = item.unwrap_or(Value::Null); p["params"] = params; let id = d.str("__effect"); + // Each target keeps the map its own Warp draws with: the dialog's `version` is the first + // target's. + if super::warp_effect::is_warp(&id) + && let Some(Value::Object(m)) = p.get_mut("params") + { + m.remove("version"); + } // The displayed style comes from the first target. Preserve other targets' Warp IDs // unless the user deliberately chooses Style, including after a preview rollback. if super::warp_effect::is_warp(&id) && d.bool("__warp_style_changed") { @@ -959,6 +975,11 @@ mod tests { (vectorcraft_effects::CLASSIC_EXTRUDE, "bevel"), (vectorcraft_effects::CLASSIC_EXTRUDE, "surface"), (vectorcraft_effects::CLASSIC_EXTRUDE, "shadingColor"), + (vectorcraft_effects::CLASSIC_REVOLVE, "edge"), + (vectorcraft_effects::CLASSIC_REVOLVE, "surface"), + (vectorcraft_effects::CLASSIC_REVOLVE, "shadingColor"), + (vectorcraft_effects::CLASSIC_ROTATE, "surface"), + (vectorcraft_effects::CLASSIC_ROTATE, "shadingColor"), ("warp.arc", "orientation"), ("warp.twist", "orientation"), (vectorcraft_effects::RASTERIZE, "background"), diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index f537595ebc..6c9d95b601 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -239,7 +239,7 @@ fn bar_of(app: &VectorcraftApp) -> Option<(bool, Bar)> { let env = st.selection.objects.first().and_then(|id| vectorcraft_doc::live::envelope_of(&st.doc, *id))?; let NodeKind::Envelope { kind, editing, .. } = &env.kind else { return None }; let bar = match &**kind { - EnvelopeKind::Warp { style, bend, h, v, horizontal } => { + EnvelopeKind::Warp { style, bend, h, v, horizontal, .. } => { Bar::Warp { style: style.clone(), bend: *bend, h: *h, v: *v, horizontal: *horizontal } } EnvelopeKind::Mesh { rows, cols, .. } => Bar::Mesh { rows: *rows, cols: *cols }, diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 246aaf23f1..c0ed169e9b 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -103,7 +103,8 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("all".into(), json!(all)); } let mut range = d.str("range"); - if ui.add_enabled(!all, egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0)).changed() { + let field = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0).hint_text("1-3, 5"); + if ui.add_enabled(!all, field).changed() { d.fields.insert("range".into(), json!(range)); } }); diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 88f9d35c80..54c98052bf 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -784,8 +784,7 @@ fn save_preset_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) /// ones → the names added /// (none on the web, where the picked file arrives later and imports through `io::open_bytes`). pub(crate) fn import_presets(app: &mut VectorcraftApp) -> Result, String> { - if let Some(f) = app.services.open_async.as_mut() { - f(); + if crate::picks::open_async(app) { return Ok(vec![]); } let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS)], ..Default::default() }; diff --git a/crates/ui-egui/src/dialogs/find_links.rs b/crates/ui-egui/src/dialogs/find_links.rs index f6b482f190..05f0e85b60 100644 --- a/crates/ui-egui/src/dialogs/find_links.rs +++ b/crates/ui-egui/src/dialogs/find_links.rs @@ -146,10 +146,12 @@ fn start_search(app: &mut VectorcraftApp, d: &mut Dialog, folder: &str) -> Resul Ok(()) } -/// The files a search found for `row` (`{path, ids}`), best first: the answer's `links` row with -/// the same path and ids. +/// The files a search found for `row` (`{path?, ids}`), best first: the answer's `links` row with +/// the same ids and, when both have one, the same path. A row has no `path` when its file is outside +/// an automation client's read roots. fn files_for<'a>(found: &'a [Value], row: &Value) -> &'a [Value] { - found.iter().find(|r| r["path"] == row["path"] && r["ids"] == row["ids"]).and_then(|r| r["files"].as_array()).map_or(&[], Vec::as_slice) + let same_path = |r: &Value| r["path"].is_null() || row["path"].is_null() || r["path"] == row["path"]; + found.iter().find(|r| r["ids"] == row["ids"] && same_path(r)).and_then(|r| r["files"].as_array()).map_or(&[], Vec::as_slice) } /// The file chosen at the start among `files`: the only one that is the same file, else the only diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index 36659c53be..4722b8b327 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -339,3 +339,12 @@ fn find_in_folder_asks_for_the_folder_off_the_ui_thread() { searched(&mut app); assert_eq!(pick(app.ui.dialog.as_ref().unwrap(), "here.png"), &json!(here)); } + +/// A row whose path `links.check` left out (its file is outside the read roots) still shows the +/// files the search found for its objects. +#[test] +fn a_row_without_its_path_shows_the_files_found_for_its_objects() { + let found = [json!({"name": "a.png", "path": "/elsewhere/a.png", "ids": [3], "files": [{"path": "/root/a.png"}]})]; + assert_eq!(files_for(&found, &json!({"name": "a.png", "ids": [3]})), [json!({"path": "/root/a.png"})]); + assert!(files_for(&found, &json!({"name": "a.png", "ids": [4]})).is_empty()); +} diff --git a/crates/ui-egui/src/dialogs/flattener_presets.rs b/crates/ui-egui/src/dialogs/flattener_presets.rs index e95d0e683a..a8bcdde6e4 100644 --- a/crates/ui-egui/src/dialogs/flattener_presets.rs +++ b/crates/ui-egui/src/dialogs/flattener_presets.rs @@ -197,8 +197,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> } Action::Import => { // On the web the picked file arrives later and imports through `io::open_bytes`. - if let Some(f) = app.services.open_async.as_mut() { - f(); + if crate::picks::open_async(app) { return Ok(()); } let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Flattener presets", PRESET_EXTS)], ..Default::default() }; diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 8e02009339..76403ff451 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -8,7 +8,7 @@ //! //! Fields: `file.new`'s params (`preset`, `name`, `width`, `height` (pt), `units`, `artboards`, //! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, -//! `previewMode`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and +//! `previewMode`, `alignNewObjectsToPixelGrid`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and //! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing //! any of them afterwards makes the settings custom. @@ -29,7 +29,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { inputs: |_| &["presetName"], .. pub(super) const MORE_SPEC: DialogSpec = SPEC; /// The fields `file.new` takes. -const PARAMS: [&str; 12] = [ +const PARAMS: [&str; 13] = [ "preset", "name", "width", @@ -42,6 +42,7 @@ const PARAMS: [&str; 12] = [ "colorMode", "rasterEffectsPpi", "previewMode", + "alignNewObjectsToPixelGrid", ]; /// The preset the fields were last filled from, as `apply` set them; a Recent or Saved card keeps /// its own units here, which the units chosen in Preset Details don't change. @@ -694,7 +695,8 @@ fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(Value, Strin } } -/// The collapsible Advanced Options: Color Mode, Raster Effects and Preview Mode. +/// The collapsible Advanced Options: Color Mode, Raster Effects, Preview Mode and Align New Objects +/// to Pixel Grid. fn advanced(ui: &mut egui::Ui, d: &mut Dialog, label: f32, field: f32) { let open = d.bool("advanced"); if widgets::section_toggle(ui, tl!("Advanced Options"), open) { @@ -714,6 +716,25 @@ fn advanced(ui: &mut egui::Ui, d: &mut Dialog, label: f32, field: f32) { ] { widgets::label_row(ui, name, label, |ui| choice(ui, d, key, options, field)); } + wrapping_check(ui, d, "alignNewObjectsToPixelGrid", tl!("Align New Objects to Pixel Grid")); +} + +/// A checkbox for the boolean field `key` whose `label` (already translated) wraps within the +/// column; a click on the box or the label toggles the field. +fn wrapping_check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { + let t = Tokens::get(ui.ctx()); + let on = d.bool(key); + let toggled = ui + .horizontal_top(|ui| { + let boxed = widgets::check_box(ui, label, on, true); + let text = egui::RichText::new(label).font(egui::FontId::proportional(12.5)).color(t.text); + let clicked = ui.add(egui::Label::new(text).wrap().sense(egui::Sense::click())).clicked(); + boxed || clicked + }) + .inner; + if toggled { + d.fields.insert(key.into(), json!(!on)); + } } #[cfg(test)] @@ -1433,6 +1454,60 @@ mod tests { assert!(h.state().session.documents().is_empty()); } + /// Advanced Options › Align New Objects to Pixel Grid is checked for a Web preset and unchecked + /// for Letter; the checkbox changes it and makes the settings custom, Save Preset keeps it, and + /// Create makes the document with it. + #[test] + fn align_new_objects_checkbox_follows_the_preset_and_reaches_the_document() { + const KEY: &str = "alignNewObjectsToPixelGrid"; + const LABEL: &str = "Align New Objects to Pixel Grid"; + let mut h = big(); + assert_eq!((field(h.state(), "preset"), field(h.state(), KEY)), (json!("Letter"), json!(false))); + set(h.state_mut(), "category", json!("Web")); + set(h.state_mut(), "preset", json!("Web 1920×1080")); + set(h.state_mut(), "advanced", json!(true)); + h.run_steps(3); + assert_eq!(field(h.state(), KEY), json!(true)); + h.get_by_role_and_label(egui::accesskit::Role::CheckBox, LABEL).click(); + h.run_steps(3); + assert_eq!((field(h.state(), "preset"), field(h.state(), KEY)), (json!(""), json!(false)), "custom settings"); + set(h.state_mut(), "category", json!("Print")); + set(h.state_mut(), "preset", json!("Letter")); + h.run_steps(3); + assert_eq!(field(h.state(), KEY), json!(false)); + h.get_by_role_and_label(egui::accesskit::Role::Label, LABEL).click(); + h.run_steps(3); + assert_eq!(field(h.state(), KEY), json!(true), "a click on the label toggles it too"); + h.get_by_label("Save Preset").click(); + h.run_steps(4); + set(h.state_mut(), "presetName", json!("Pixel Letter")); + h.run_steps(2); + h.get_by_label("Save").click(); + h.run_steps(3); + let saved = h.state().session.prefs.new_doc_presets.iter().find(|p| p.name == "Pixel Letter").expect("saved"); + assert!(saved.align_new_objects_to_pixel_grid); + assert_eq!((field(h.state(), "preset"), field(h.state(), KEY)), (json!("Pixel Letter"), json!(true))); + h.get_by_label("Create").click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none()); + assert!(h.state().session.active().unwrap().doc.setup.align_new_objects_to_pixel_grid); + } + + /// A long translation of Align New Objects to Pixel Grid wraps inside the Preset Details column. + #[test] + fn align_new_objects_label_wraps_inside_the_details_column() { + const LABEL: &str = "Στοίχιση νέων αντικειμένων στο πλέγμα εικονοστοιχείων"; + crate::i18n::set_current(crate::i18n::Lang::from_code("el").unwrap()); + let mut h = big(); + set(h.state_mut(), "advanced", json!(true)); + h.run_steps(3); + let boxed = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, LABEL).rect(); + let text = h.get_by_role_and_label(egui::accesskit::Role::Label, LABEL).rect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(text.right() <= boxed.left() + super::DETAILS + 0.5, "{boxed:?} {text:?}"); + assert!(text.height() > boxed.height(), "the label takes two lines: {text:?}"); + } + /// In a small window the pop-up stays on screen, and its button stays in view under rows that scroll. #[test] fn the_popup_stays_inside_a_small_window() { diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 76b280b017..4978a6a1f6 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -1,5 +1,6 @@ -//! New Character Style and New Paragraph Style: the new style's name. OK makes the style from the -//! text that was selected when the dialog opened (`charStyle.new`, `paraStyle.new`). +//! New Character Style and New Paragraph Style: the new style's name and the sections of Character +//! or Paragraph Style Options, filled in from the text that was selected when the dialog opened. +//! OK makes the style with those attributes (`charStyle.new`, `paraStyle.new`). //! //! Fields: `name`, `__para` (true for a paragraph style) and `__target` (the `id`, `start` and //! `end` of the Type tool's selection, empty for the selected objects, and the `attrs` that text had @@ -32,12 +33,15 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result bool { } return false; } - grid(ui, |ui| { - label(ui, tl!("Style Name:")); - form::text(ui, d, "name", 190.0); - ui.end_row(); + ui.horizontal(|ui| { + super::para_style_options::section_list(ui, d); + ui.separator(); + ui.vertical(|ui| super::para_style_options::section_body(ui, d)); }); + super::para_style_options::reset_button(ui, d); + if let Err(why) = super::para_style_options::edited_attrs(d) { + super::char_style_options::attrs_error(ui, &why); + } false } @@ -98,9 +106,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut params = d.fields.get("__target").filter(|t| t.is_object()).cloned().unwrap_or_else(|| json!({})); params["name"] = json!(d.str("name")); - if !para(d) { - params["attrs"] = Value::Object(super::char_style_options::edited_attrs(d)?); - } + params["attrs"] = Value::Object(if para(d) { super::para_style_options::edited_attrs(d)? } else { super::char_style_options::edited_attrs(d)? }); let r = app.run(if para(d) { "paraStyle.new" } else { "charStyle.new" }, params); if let Ok(v) = &r { app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs new file mode 100644 index 0000000000..1d59bdd679 --- /dev/null +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -0,0 +1,1008 @@ +//! Paragraph Style Options fields shared by editing and creating a paragraph style: General, Basic +//! Paragraph Formats (alignment, indents and spacing), Tabs (the style's tab stops), Composition +//! (composer and Roman Hanging Punctuation), Hyphenation, Justification and East Asian Composition +//! Settings (Korean Line Break Anywhere). +//! +//! Each field is unset (empty, or a checkbox in its unset state) or set, and an unset field leaves +//! its attribute out of the style. Distances are shown and typed in the General unit and kept in +//! points. The Hyphenation and Justification options are one attribute each (`hyphenation`, +//! `justification`): when any of their fields is set, a field left empty takes its default value. +//! The `tabs` field is unset (null) or a list of stops, an empty list included, and is the `tabs` +//! attribute. A field still as it opened keeps the style's stored value as it is. +//! +//! Behavior reference (public documentation): +//! . + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::text::DEFAULT_TAB_INTERVAL; +use vectorcraft_doc::{HyphenationOptions, JustificationOptions, TabAlign, TabStop, Unit}; + +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +pub const KIND: &str = "paraStyleOptions"; + +/// The section ids, in the order the section list shows them. +pub(crate) const SECTIONS: [&str; 7] = ["general", "basic", "tabs", "composition", "hyphenation", "justification", "eastAsian"]; +/// The alignments of a tab stop with the names the `tabs` field gives them, in the Tabs panel's +/// order. +const TAB_ALIGNS: [(TabAlign, &str); 4] = + [(TabAlign::Left, "left"), (TabAlign::Center, "center"), (TabAlign::Right, "right"), (TabAlign::Decimal, "decimal")]; +/// The distance fields of Basic Paragraph Formats, which are also the attributes they set. +const DISTANCES: [&str; 5] = ["left_indent", "right_indent", "first_line_indent", "space_before", "space_after"]; +/// The range of the indents, the space before and after, and the Hyphenation Zone (pt), as +/// `text.setFormat` keeps them. +const MAX_DISTANCE: f64 = 1296.0; +/// The whole-number fields of Hyphenation: (field, `hyphenation` key, range). +const COUNTS: [(&str, &str, (f64, f64)); 4] = [ + ("words_longer_than", "words_longer_than", (1.0, 25.0)), + ("after_first", "after_first", (1.0, 15.0)), + ("before_last", "before_last", (1.0, 15.0)), + ("hyphen_limit", "hyphen_limit", (0.0, 25.0)), +]; +/// The fields of Hyphenation that make up the `hyphenation` attribute. +const HYPHENATION_FIELDS: [&str; 6] = + ["words_longer_than", "after_first", "before_last", "hyphen_limit", "hyphenation_zone", "hyphenate_capitalized"]; +/// The spacing rows of Justification: (field prefix, `justification` key, range). +const ROWS: [(&str, &str, (f64, f64)); 3] = [ + ("word", "word_spacing", JustificationOptions::WORD_SPACING), + ("letter", "letter_spacing", JustificationOptions::LETTER_SPACING), + ("glyph", "glyph_scaling", JustificationOptions::GLYPH_SCALING), +]; +/// The columns of a spacing row: Minimum, Desired and Maximum. +const COLUMNS: [&str; 3] = ["min", "desired", "max"]; +/// The fields of Justification that make up the `justification` attribute. +const JUSTIFICATION_FIELDS: [&str; 11] = [ + "word_min", + "word_desired", + "word_max", + "letter_min", + "letter_desired", + "letter_max", + "glyph_min", + "glyph_desired", + "glyph_max", + "auto_leading", + "single_word", +]; +/// The values of the Alignment field (`justify`), in the Paragraph panel's order after Auto. +const JUSTIFY_VALUES: [&str; 8] = ["Auto", "Left", "Center", "Right", "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyAll"]; +/// The values of the Single Word Justification field. +const SINGLE_WORD_VALUES: [&str; 4] = ["fullJustify", "alignLeft", "alignCenter", "alignRight"]; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Paragraph Style Options").into(), + body, + confirm, + preview: true, + inputs: |_| { + &[ + "name", + "justify", + "left_indent", + "right_indent", + "first_line_indent", + "space_before", + "space_after", + "composer", + "roman_hanging", + "hyphenate", + "words_longer_than", + "after_first", + "before_last", + "hyphen_limit", + "hyphenation_zone", + "hyphenate_capitalized", + "word_min", + "word_desired", + "word_max", + "letter_min", + "letter_desired", + "letter_max", + "glyph_min", + "glyph_desired", + "glyph_max", + "auto_leading", + "single_word", + "korean_line_break_anywhere", + "tabs", + "section", + ] + }, + min_width: 720.0, + max_width: Some(720.0), + ..DialogSpec::FORM +}; + +pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { + crate::panels::character::end_typing(app); + let unit = app.session.general_unit(); + let doc = &app.session.active().ok_or("no document open")?.doc; + let def = doc.para_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no style `{name}`"))?; + let mut fields = form_fields(&def.attrs, unit); + fields.insert("__vertical".into(), json!(vertical_text(app))); + fields.insert("name".into(), json!(name)); + fields.insert("__style".into(), json!(name)); + fields.insert("section".into(), json!("general")); + fields.insert("preview".into(), json!(true)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({"dialog": KIND})) +} + +/// The dialog fields for a style's `attrs` in `unit`, with the attributes and the unit they come +/// from, which [`edited_attrs`] reads back. +pub(crate) fn form_fields(attrs: &Map, unit: Unit) -> Map { + let mut fields = fields_from_attrs(attrs, unit); + fields.insert("__attrs".into(), Value::Object(attrs.clone())); + fields.insert("__unit".into(), json!(unit.key())); + fields +} + +/// Whether the first selected text is vertical type, where the Tabs section names a stop's +/// position Y and its Left and Right alignments Top and Bottom. +pub(crate) fn vertical_text(app: &VectorcraftApp) -> bool { + crate::panels::character::first_selected_text(app).is_some_and(|t| t.vertical) +} + +/// The `tabs` field for a style's `tabs` attribute: unset (null) when the style leaves it out, +/// otherwise one entry per stop ([`stop_field`]). +fn tabs_field(value: Option<&Value>, unit: Unit) -> Value { + let Some(stops) = value.and_then(Value::as_array) else { return Value::Null }; + Value::Array(stops.iter().filter_map(|s| serde_json::from_value::(s.clone()).ok()).map(|s| stop_field(&s, unit)).collect()) +} + +/// A tab stop's entry in the `tabs` field: its position as text in `unit`, its alignment, leader +/// and Align On character, and the position in points it shows (`__pt`), which a position still as +/// it shows keeps exactly. +fn stop_field(s: &TabStop, unit: Unit) -> Value { + let align = TAB_ALIGNS.iter().find(|(a, _)| *a == s.align).map_or("left", |(_, key)| *key); + json!({"position": unit.format(s.position), "align": align, "leader": s.leader, "alignOn": s.align_on.to_string(), "__pt": s.position}) +} + +/// The position in points of a `tabs` entry: its `__pt` while its text is as that shows in `unit`, +/// else the text read in `unit`; `None` when the text is not a distance. +fn stop_position(row: &Value, unit: Unit) -> Option { + let text = row.get("position").and_then(Value::as_str).map_or("", str::trim); + row.get("__pt").and_then(Value::as_f64).filter(|pt| pt.is_finite() && unit.format(*pt) == text).or_else(|| unit.parse(text)) +} + +/// The tab stop a `tabs` entry sets, or why it sets none: its position must be a distance from 0 to +/// 100000 pt (`label` names the field), its alignment one of [`TAB_ALIGNS`], its leader text of at +/// most eight characters and its Align On character one character. A leader or Align On character +/// left out is none or a period. +fn read_stop(row: &Value, unit: Unit, label: &str) -> Result { + let position = stop_position(row, unit).ok_or_else(|| format!("{label} must be a number"))?; + if !(0.0..=TabStop::MAX_POSITION).contains(&position) { + let (min, max) = (unit.format(0.0), unit.format(TabStop::MAX_POSITION)); + return Err(format!("{label} must be a number from {min} to {max}")); + } + let other = match row.get("align") { + None | Some(Value::Null) => "left", + Some(v) => v.as_str().unwrap_or(""), + }; + let align = TAB_ALIGNS.iter().find(|(_, key)| *key == other).map(|(a, _)| *a).ok_or_else(|| format!("unknown align `{other}`"))?; + let leader = match row.get("leader") { + None | Some(Value::Null) => "", + Some(Value::String(s)) => s.as_str(), + Some(_) => { + let key = "leader"; + return Err(format!("`{key}` must be a string")); + } + }; + let (label, max) = (caption(tl!("Leader:")), TabStop::MAX_LEADER); + if leader.chars().count() > max { + return Err(format!("{label} must be at most {max} characters")); + } + let label = caption(tl!("Align On:")); + let align_on = match row.get("alignOn") { + None | Some(Value::Null) => '.', + Some(Value::String(s)) => { + let mut chars = s.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => c, + _ => return Err(format!("{label} must be one character")), + } + } + Some(_) => return Err(format!("{label} must be one character")), + }; + Ok(TabStop { position, align, leader: leader.into(), align_on }) +} + +/// A distance in points as its field shows it in `unit`. +fn distance_field(value: Option<&Value>, unit: Unit) -> Value { + value.and_then(Value::as_f64).map_or_else(|| json!(""), |pt| json!(unit.format(pt))) +} + +/// A number as its field shows it, or empty. +fn number_field(value: Option<&Value>) -> Value { + value.and_then(Value::as_f64).map_or_else(|| json!(""), |n| json!(format_number(n))) +} + +fn format_number(n: f64) -> String { + let s = format!("{n:.3}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +/// The fields for a style's `attrs` in `unit`: an attribute the style does not set is an empty +/// field or an unset checkbox or menu. +pub(crate) fn fields_from_attrs(attrs: &Map, unit: Unit) -> Map { + let mut fields = Map::new(); + fields.insert("justify".into(), attrs.get("justify").filter(|v| v.is_string()).cloned().unwrap_or(Value::Null)); + for key in DISTANCES { + fields.insert(key.into(), distance_field(attrs.get(key), unit)); + } + fields.insert("composer".into(), attrs.get("composer").filter(|v| v.is_string()).cloned().unwrap_or(Value::Null)); + for key in ["roman_hanging", "hyphenate", "korean_line_break_anywhere"] { + fields.insert(key.into(), attrs.get(key).filter(|v| v.is_boolean()).cloned().unwrap_or(Value::Null)); + } + let hyphenation = attrs.get("hyphenation"); + for (field, key, _) in COUNTS { + fields.insert(field.into(), number_field(hyphenation.and_then(|h| h.get(key)))); + } + fields.insert("hyphenation_zone".into(), distance_field(hyphenation.and_then(|h| h.get("zone")), unit)); + fields.insert( + "hyphenate_capitalized".into(), + hyphenation.and_then(|h| h.get("capitalized")).filter(|v| v.is_boolean()).cloned().unwrap_or(Value::Null), + ); + let justification = attrs.get("justification"); + for (prefix, key, _) in ROWS { + for (i, column) in COLUMNS.iter().enumerate() { + fields.insert(format!("{prefix}_{column}"), number_field(justification.and_then(|j| j.get(key)).and_then(|v| v.get(i)))); + } + } + fields.insert("auto_leading".into(), number_field(justification.and_then(|j| j.get("auto_leading")))); + fields.insert("single_word".into(), justification.and_then(|j| j.get("single_word")).filter(|v| v.is_string()).cloned().unwrap_or(Value::Null)); + fields.insert("tabs".into(), tabs_field(attrs.get("tabs"), unit)); + fields +} + +/// A field's caption without its colon, for messages that name it. +fn caption(label: &str) -> &str { + label.trim_end().trim_end_matches([':', ':']).trim_end() +} + +/// The caption of the number or distance field `key`, as the dialog shows it. +fn label_of(key: &str) -> &'static str { + match key { + "left_indent" => tl!("Left Indent"), + "right_indent" => tl!("Right Indent"), + "first_line_indent" => tl!("First-line Left Indent"), + "space_before" => tl!("Space Before Paragraph"), + "space_after" => tl!("Space After Paragraph"), + "words_longer_than" => tl!("Words Longer Than:"), + "after_first" => tl!("After First:"), + "before_last" => tl!("Before Last:"), + "hyphen_limit" => tl!("Hyphen Limit:"), + "hyphenation_zone" => tl!("Hyphenation Zone:"), + "auto_leading" => tl!("Auto Leading:"), + k if k.starts_with("word") => tl!("Word Spacing:"), + k if k.starts_with("letter") => tl!("Letter Spacing:"), + _ => tl!("Glyph Scaling:"), + } +} + +/// The text of field `key`, trimmed; `None` when it is empty or unset. +fn typed<'a>(d: &'a Dialog, key: &str) -> Option<&'a str> { + d.fields.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) +} + +/// The distance typed in field `key` (in `unit` unless it names its own), in points: `None` when +/// the field is empty, an error when it is not a distance or is outside `lo..=hi` points. +fn distance(d: &Dialog, key: &str, unit: Unit, lo: f64, hi: f64) -> Result, String> { + let Some(s) = typed(d, key) else { return Ok(None) }; + let label = caption(label_of(key)); + let pt = unit.parse(s).ok_or_else(|| format!("{label} must be a number"))?; + if !(lo..=hi).contains(&pt) { + let (min, max) = (unit.format(lo), unit.format(hi)); + return Err(format!("{label} must be a number from {min} to {max}")); + } + Ok(Some(pt)) +} + +/// The number typed in field `key`: `None` when the field is empty, an error when it is not a +/// number or is outside `lo..=hi`. +fn number(d: &Dialog, key: &str, lo: f64, hi: f64) -> Result, String> { + let Some(s) = typed(d, key) else { return Ok(None) }; + let label = caption(label_of(key)); + let n = vectorcraft_doc::parse_number(s.trim_end_matches('%').trim_end()).filter(|n| n.is_finite()); + let n = n.ok_or_else(|| format!("{label} must be a number"))?; + if !(lo..=hi).contains(&n) { + let (min, max) = (format_number(lo), format_number(hi)); + return Err(format!("{label} must be a number from {min} to {max}")); + } + Ok(Some(n)) +} + +/// The whole number typed in field `key`: `None` when it is empty, an error when it is not a whole +/// number from `lo` to `hi`. +fn count(d: &Dialog, key: &str, lo: f64, hi: f64) -> Result, String> { + let Some(n) = number(d, key, lo, hi)? else { return Ok(None) }; + if n.fract() != 0.0 { + let (label, min, max) = (caption(label_of(key)), format_number(lo), format_number(hi)); + return Err(format!("{label} must be a whole number from {min} to {max}")); + } + // A whole number within `lo..=hi` (at most 25) is exact as a `u32`. + Ok(Some(n as u32)) +} + +/// The unit the dialog shows distances in. +fn unit_of(d: &Dialog) -> Unit { + d.fields.get("__unit").and_then(Value::as_str).and_then(Unit::named_east_asian).unwrap_or_default() +} + +/// The style's attributes as the dialog's fields set them. A field still as it opened keeps its +/// stored value without a check, so a style read from a file with a value out of range can still +/// be renamed. +pub(crate) fn edited_attrs(d: &Dialog) -> Result, String> { + let original = d.fields.get("__attrs").and_then(Value::as_object).cloned().unwrap_or_default(); + let unit = unit_of(d); + let original_fields = fields_from_attrs(&original, unit); + let mut attrs = original.clone(); + let unchanged = |key: &str, reset: &str| !d.bool(reset) && d.fields.get(key) == original_fields.get(key); + let keep_or = |attrs: &mut Map, key: &str, unchanged: bool, value: Option| { + attrs.remove(key); + let value = if unchanged { original.get(key).cloned() } else { value }; + if let Some(value) = value { + attrs.insert(key.into(), value); + } + }; + let choice = |key: &str| d.fields.get(key).filter(|v| v.is_string()).cloned(); + let switch = |key: &str| d.fields.get(key).filter(|v| v.is_boolean()).cloned(); + + let same = unchanged("justify", "__resetBasic"); + keep_or(&mut attrs, "justify", same, choice("justify").filter(|v| v.as_str().is_some_and(|v| JUSTIFY_VALUES.contains(&v)))); + for key in DISTANCES { + let same = unchanged(key, "__resetBasic"); + let value = if same { None } else { distance(d, key, unit, -MAX_DISTANCE, MAX_DISTANCE)?.map(Value::from) }; + keep_or(&mut attrs, key, same, value); + } + + let same = unchanged("composer", "__resetComposition"); + keep_or(&mut attrs, "composer", same, choice("composer").filter(|v| matches!(v.as_str(), Some("singleLine" | "everyLine")))); + let same = unchanged("roman_hanging", "__resetComposition"); + keep_or(&mut attrs, "roman_hanging", same, switch("roman_hanging")); + + let same = unchanged("hyphenate", "__resetHyphenation"); + keep_or(&mut attrs, "hyphenate", same, switch("hyphenate")); + let same = HYPHENATION_FIELDS.iter().all(|key| unchanged(key, "__resetHyphenation")); + let value = if same { None } else { hyphenation(d, &original, &original_fields, unit)? }; + keep_or(&mut attrs, "hyphenation", same, value); + + let same = JUSTIFICATION_FIELDS.iter().all(|key| unchanged(key, "__resetJustification")); + let value = if same { None } else { justification(d, &original, &original_fields)? }; + keep_or(&mut attrs, "justification", same, value); + + let same = unchanged("tabs", "__resetTabs"); + let value = if same { None } else { tab_stops(d, &original, unit)? }; + keep_or(&mut attrs, "tabs", same, value); + + let same = unchanged("korean_line_break_anywhere", "__resetEastAsian"); + keep_or(&mut attrs, "korean_line_break_anywhere", same, switch("korean_line_break_anywhere")); + Ok(attrs) +} + +/// The `tabs` attribute the Tabs section sets: none while the list is unset; otherwise its stops +/// sorted by position. Of stops within 1e-6 pt of each other, the one edited last (`__tabEdited`) +/// is kept, else the first in the list. A stop as the style has it is kept without a check, and any +/// other is read by [`read_stop`]. An error when the list has more than 256 stops and more than the +/// style has. +fn tab_stops(d: &Dialog, original: &Map, unit: Unit) -> Result, String> { + let rows = match d.fields.get("tabs") { + None | Some(Value::Null) => return Ok(None), + Some(Value::Array(rows)) => rows, + Some(_) => { + let key = "tabs"; + return Err(format!("`{key}` must be an array")); + } + }; + let kept: Vec = + original.get("tabs").and_then(Value::as_array).into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect(); + let max = TabStop::MAX_STOPS; + if rows.len() > max.max(kept.len()) { + return Err(format!("at most {max} tab stops")); + } + let label = caption(if d.bool("__vertical") { tl!("Y:") } else { tl!("X:") }); + let kept_rows: Vec = kept.iter().map(|s| stop_field(s, unit)).collect(); + let mut stops = Vec::with_capacity(rows.len()); + for row in rows { + match kept_rows.iter().position(|k| k == row) { + Some(i) => stops.push(kept[i].clone()), + None => stops.push(read_stop(row, unit, label)?), + } + } + let edited = d.fields.get("__tabEdited").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let mut order: Vec = (0..stops.len()).collect(); + order.sort_by(|&a, &b| stops[a].position.total_cmp(&stops[b].position).then(a.cmp(&b))); + let mut keep: Vec = Vec::with_capacity(order.len()); + for i in order { + match keep.last_mut() { + Some(last) if (stops[*last].position - stops[i].position).abs() < 1e-6 => { + if Some(i) == edited { + *last = i; + } + } + _ => keep.push(i), + } + } + let stops: Vec = keep.into_iter().map(|i| stops[i].clone()).collect(); + Ok(Some(serde_json::to_value(stops).map_err(|e| e.to_string())?)) +} + +/// The `hyphenation` attribute the Hyphenation fields set: none when every field is empty or +/// unset; otherwise the style's options (or the defaults) with each changed field written over +/// them, an empty one at its default. +fn hyphenation(d: &Dialog, original: &Map, original_fields: &Map, unit: Unit) -> Result, String> { + let empty = |key: &str| typed(d, key).is_none() && !d.fields.get(key).is_some_and(Value::is_boolean); + if HYPHENATION_FIELDS.iter().all(|key| empty(key)) { + return Ok(None); + } + let reset = d.bool("__resetHyphenation"); + let mut h: HyphenationOptions = + if reset { None } else { original.get("hyphenation").and_then(|v| serde_json::from_value(v.clone()).ok()) }.unwrap_or_default(); + let defaults = HyphenationOptions::default(); + let changed = |key: &str| reset || d.fields.get(key) != original_fields.get(key); + for (field, key, (lo, hi)) in COUNTS { + if !changed(field) { + continue; + } + let given = count(d, field, lo, hi)?; + let value = match key { + "words_longer_than" => &mut h.words_longer_than, + "after_first" => &mut h.after_first, + "before_last" => &mut h.before_last, + _ => &mut h.hyphen_limit, + }; + let default = match key { + "words_longer_than" => defaults.words_longer_than, + "after_first" => defaults.after_first, + "before_last" => defaults.before_last, + _ => defaults.hyphen_limit, + }; + *value = given.unwrap_or(default); + } + if changed("hyphenation_zone") { + h.zone = distance(d, "hyphenation_zone", unit, 0.0, MAX_DISTANCE)?.unwrap_or(defaults.zone); + } + if changed("hyphenate_capitalized") { + h.capitalized = d.fields.get("hyphenate_capitalized").and_then(Value::as_bool).unwrap_or(defaults.capitalized); + } + Ok(Some(serde_json::to_value(h).map_err(|e| e.to_string())?)) +} + +/// The `justification` attribute the Justification fields set, as [`hyphenation`] builds its +/// own; an error when a row with a changed field has a Minimum above its Desired value or a +/// Desired value above its Maximum. A row left as it was keeps the style's values. +fn justification(d: &Dialog, original: &Map, original_fields: &Map) -> Result, String> { + if JUSTIFICATION_FIELDS.iter().all(|key| typed(d, key).is_none()) { + return Ok(None); + } + let reset = d.bool("__resetJustification"); + let mut j: JustificationOptions = + if reset { None } else { original.get("justification").and_then(|v| serde_json::from_value(v.clone()).ok()) }.unwrap_or_default(); + let defaults = JustificationOptions::default(); + let changed = |key: &str| reset || d.fields.get(key) != original_fields.get(key); + for (prefix, key, (lo, hi)) in ROWS { + let (values, default) = match key { + "word_spacing" => (&mut j.word_spacing, defaults.word_spacing), + "letter_spacing" => (&mut j.letter_spacing, defaults.letter_spacing), + _ => (&mut j.glyph_scaling, defaults.glyph_scaling), + }; + let mut row_changed = false; + for (i, column) in COLUMNS.iter().enumerate() { + let field = format!("{prefix}_{column}"); + if changed(&field) { + values[i] = number(d, &field, lo, hi)?.unwrap_or(default[i]); + row_changed = true; + } + } + if row_changed && !(values[0] <= values[1] && values[1] <= values[2]) { + return Err(tl!("Minimum must not exceed Desired, nor Desired Maximum.").to_string()); + } + } + if changed("auto_leading") { + let (lo, hi) = JustificationOptions::AUTO_LEADING; + j.auto_leading = number(d, "auto_leading", lo, hi)?.unwrap_or(defaults.auto_leading); + } + if changed("single_word") { + let given = d.fields.get("single_word").and_then(Value::as_str).filter(|v| SINGLE_WORD_VALUES.contains(v)); + j.single_word = match given { + Some(v) => serde_json::from_value(json!(v)).map_err(|e| e.to_string())?, + None => defaults.single_word, + }; + } + Ok(Some(serde_json::to_value(j).map_err(|e| e.to_string())?)) +} + +/// Reset Panel in Basic Paragraph Formats: Alignment and the five indent and spacing fields become +/// unset. +fn reset_basic(d: &mut Dialog) { + d.fields.insert("__resetBasic".into(), json!(true)); + d.fields.insert("justify".into(), Value::Null); + for key in DISTANCES { + d.fields.insert(key.into(), json!("")); + } +} + +/// Reset Panel in Composition: the composer and Roman Hanging Punctuation become unset. +fn reset_composition(d: &mut Dialog) { + d.fields.insert("__resetComposition".into(), json!(true)); + d.fields.insert("composer".into(), Value::Null); + d.fields.insert("roman_hanging".into(), Value::Null); +} + +/// Reset Panel in Hyphenation: Hyphenation and its options become unset. +fn reset_hyphenation(d: &mut Dialog) { + d.fields.insert("__resetHyphenation".into(), json!(true)); + d.fields.insert("hyphenate".into(), Value::Null); + d.fields.insert("hyphenate_capitalized".into(), Value::Null); + for key in HYPHENATION_FIELDS.iter().filter(|k| **k != "hyphenate_capitalized") { + d.fields.insert((*key).into(), json!("")); + } +} + +/// Reset Panel in Justification: the Justification options become unset. +fn reset_justification(d: &mut Dialog) { + d.fields.insert("__resetJustification".into(), json!(true)); + d.fields.insert("single_word".into(), Value::Null); + for key in JUSTIFICATION_FIELDS.iter().filter(|k| **k != "single_word") { + d.fields.insert((*key).into(), json!("")); + } +} + +/// Reset Panel in Tabs: the tab stops become unset, which leaves `tabs` out of the style. +fn reset_tabs(d: &mut Dialog) { + d.fields.insert("__resetTabs".into(), json!(true)); + d.fields.insert("tabs".into(), Value::Null); + d.fields.remove("__tabEdited"); + d.fields.insert("__tabSel".into(), json!(0)); +} + +/// Reset Panel in East Asian Composition Settings: Korean Line Break Anywhere becomes unset. +fn reset_east_asian(d: &mut Dialog) { + d.fields.insert("__resetEastAsian".into(), json!(true)); + d.fields.insert("korean_line_break_anywhere".into(), Value::Null); +} + +/// Whether the section `d` shows has a Reset Panel: every section but General. +pub(crate) fn can_reset(d: &Dialog) -> bool { + ["basic", "tabs", "composition", "hyphenation", "justification", "eastAsian"].contains(&d.str("section").as_str()) +} + +/// Reset Panel: clear the settings of the section `d` shows. +pub(crate) fn reset_section(d: &mut Dialog) { + match d.str("section").as_str() { + "basic" => reset_basic(d), + "tabs" => reset_tabs(d), + "composition" => reset_composition(d), + "hyphenation" => reset_hyphenation(d), + "justification" => reset_justification(d), + "eastAsian" => reset_east_asian(d), + _ => {} + } +} + +/// Whether `d` is Paragraph Style Options or New Paragraph Style. +pub(crate) fn is_paragraph_dialog(d: &Dialog) -> bool { + d.kind == KIND || (d.kind == super::new_text_style::KIND && d.bool("__para")) +} + +pub fn reset_panel(app: &mut VectorcraftApp) -> Result { + let d = app.ui.dialog.as_mut().ok_or("no dialog open")?; + if !is_paragraph_dialog(d) || !can_reset(d) { + return Err("the open dialog has no Reset".into()); + } + reset_section(d); + Ok(json!({"dialog": d.kind})) +} + +/// The section list of Paragraph Style Options and New Paragraph Style. +pub(crate) fn section_list(ui: &mut egui::Ui, d: &mut Dialog) { + ui.vertical(|ui| { + let labels = [ + tl!("General"), + tl!("Basic Paragraph Formats"), + tl!("Tabs"), + tl!("Composition"), + tl!("Hyphenation"), + tl!("Justification"), + tl!("East Asian Composition Settings"), + ]; + for (id, label) in SECTIONS.into_iter().zip(labels) { + if ui.selectable_label(d.str("section") == id, label).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); +} + +/// The Reset Panel button, enabled on every section but General. +pub(crate) fn reset_button(ui: &mut egui::Ui, d: &mut Dialog) { + ui.add_enabled_ui(can_reset(d), |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + reset_section(d); + } + }); +} + +/// A menu whose first entry leaves field `key` unset. +fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)], enabled: bool) { + let selected = d.fields.get(key).and_then(Value::as_str).unwrap_or("").to_string(); + let shown = options.iter().find(|(value, _)| *value == selected).map_or("", |(_, label)| *label); + let labels: Vec<&str> = std::iter::once(" ").chain(options.iter().map(|(_, label)| *label)).collect(); + ui.add_enabled_ui(enabled, |ui| { + if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, 190.0) { + d.fields.insert(key.into(), if i == 0 { Value::Null } else { options.get(i - 1).map_or(Value::Null, |(value, _)| json!(value)) }); + } + }); +} + +/// An on, off or unset checkbox in its own grid row: a click on unset turns it on, on turns it +/// off, and off makes it unset. +fn switch(ui: &mut egui::Ui, d: &mut Dialog, key: &str, caption: &str, enabled: bool) { + ui.label(""); + let value = d.fields.get(key).and_then(Value::as_bool); + if crate::widgets::check3(ui, caption, value, enabled) { + let next = match value { + None => json!(true), + Some(true) => json!(false), + Some(false) => Value::Null, + }; + d.fields.insert(key.into(), next); + } + ui.end_row(); +} + +/// A text field in its own grid row, with what follows the number, enabled or not. +fn field_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, caption: &str, suffix: &str, enabled: bool) { + let row = ui.label(caption); + if d.fields.get(key).is_none_or(Value::is_null) { + d.fields.insert(key.into(), json!("")); + } + ui.add_enabled_ui(enabled, |ui| { + ui.horizontal(|ui| { + ui.label_inputs_by(row.id, |ui| form::text(ui, d, key, 160.0)); + if !suffix.is_empty() { + ui.label(suffix); + } + }); + }); + ui.end_row(); +} + +/// Basic Paragraph Formats: Alignment, the left, right and first-line indents, and the space +/// before and after the paragraph. +pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("paragraph-style-basic").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + let alignments: Vec<(&str, &str)> = std::iter::once(("Auto", tl!("Auto"))) + .chain(JUSTIFY_VALUES[1..].iter().copied().zip(crate::panels::paragraph::ALIGNMENTS.iter().map(|(_, _, label, _)| tl!(*label)))) + .collect(); + let row = ui.label(tl!("Alignment:")); + ui.label_inputs_by(row.id, |ui| choice(ui, d, "justify", &alignments, true)); + ui.end_row(); + for key in DISTANCES { + field_row(ui, d, key, label_of(key), "", true); + } + }); +} + +/// The editing fields of the selected tab stop, with the `tabs` entry key each one shows. +const TAB_EDITORS: [(&str, &str); 3] = [("__tabPosition", "position"), ("__tabLeader", "leader"), ("__tabAlignOn", "alignOn")]; + +/// Tabs: the selected stop's Alignment, X (Y in vertical type), Leader and Align On, which only a +/// decimal stop uses; Add ([`add_tab`]), Delete Tab ([`delete_tab`]) and Clear All Tabs +/// ([`clear_tabs`]); and the list of stops, one row each, a click on which selects its stop, which +/// scrolls when it is taller than 160 points. A change to a field makes its stop the one edited last. +pub(crate) fn tabs_body(ui: &mut egui::Ui, d: &mut Dialog) { + let vertical = d.bool("__vertical"); + let (mut rows, mut sel, _) = tab_rows(d); + let mut changed = false; + let has = sel < rows.len(); + let shown = TAB_EDITORS.map(|(_, key)| rows.get(sel).and_then(|r| r.get(key)).and_then(Value::as_str).unwrap_or("").to_string()); + for ((field, _), text) in TAB_EDITORS.iter().zip(&shown) { + d.fields.insert((*field).into(), json!(text)); + } + let align = rows.get(sel).and_then(|r| r.get("align")).and_then(Value::as_str).unwrap_or("left").to_string(); + egui::Grid::new("paragraph-style-tabs").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + let row = ui.label(tl!("Alignment:")); + let names: Vec<&str> = TAB_ALIGNS.iter().map(|(a, _)| crate::panels::tabs::align_name(*a, vertical)).collect(); + let shown = TAB_ALIGNS.iter().position(|(_, key)| *key == align).and_then(|i| names.get(i).copied()).unwrap_or(""); + ui.add_enabled_ui(has, |ui| { + ui.label_inputs_by(row.id, |ui| { + if let Some(i) = crate::widgets::dropdown(ui, (KIND, "tab_align"), shown, &names, 190.0) + && let (Some(r), Some((_, key))) = (rows.get_mut(sel).and_then(Value::as_object_mut), TAB_ALIGNS.get(i)) + { + r.insert("align".into(), json!(key)); + changed = true; + } + }); + }); + ui.end_row(); + field_row(ui, d, "__tabPosition", if vertical { tl!("Y:") } else { tl!("X:") }, "", has); + field_row(ui, d, "__tabLeader", tl!("Leader:"), "", has); + field_row(ui, d, "__tabAlignOn", tl!("Align On:"), "", has && align == "decimal"); + }); + for ((field, key), was) in TAB_EDITORS.iter().zip(&shown) { + let typed = d.str(field); + if let Some(r) = rows.get_mut(sel).and_then(Value::as_object_mut) + && typed != *was + { + r.insert((*key).into(), json!(typed)); + changed = true; + } + } + if changed { + d.fields.insert("tabs".into(), Value::Array(rows.clone())); + d.fields.insert("__tabEdited".into(), json!(sel)); + } + ui.add_space(6.0); + let (mut add, mut delete, mut clear) = (false, false, false); + let can_add = new_tab_position(&rows, unit_of(d)).is_some(); + ui.horizontal(|ui| { + add = ui.add_enabled(can_add, egui::Button::new(tl!("Add"))).clicked(); + delete = ui.add_enabled(has, egui::Button::new(tl!("Delete Tab"))).clicked(); + clear = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Clear All Tabs"))).clicked(); + }); + ui.add_space(4.0); + let reveal = d.fields.remove("__tabScroll").is_some(); + egui::ScrollArea::vertical().id_salt("paragraph-style-tab-list").max_height(160.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, r) in rows.iter().enumerate() { + let a = r.get("align").and_then(Value::as_str).and_then(|key| TAB_ALIGNS.iter().find(|(_, k)| *k == key)).map(|(a, _)| *a); + let name = a.map_or("", |a| crate::panels::tabs::align_name(a, vertical)); + let mut text = format!("{} {name}", r.get("position").and_then(Value::as_str).unwrap_or("")); + if let Some(leader) = r.get("leader").and_then(Value::as_str).filter(|l| !l.is_empty()) { + text += &format!(" {leader}"); + } + let row = ui.selectable_label(i == sel, text); + if reveal && i == sel { + ui.scroll_to_rect_animation(row.rect, None, egui::style::ScrollAnimation::none()); + } + if row.clicked() { + sel = i; + } + } + }); + d.fields.insert("__tabSel".into(), json!(sel)); + if add { + add_tab(d); + } else if delete { + delete_tab(d); + } else if clear { + clear_tabs(d); + } +} + +/// The `tabs` entries of `d` (none while unset), the selected one's index (`__tabSel`, at most the +/// last) and the index of the one edited last (`__tabEdited`). +fn tab_rows(d: &Dialog) -> (Vec, usize, Option) { + let rows: Vec = d.fields.get("tabs").and_then(Value::as_array).cloned().unwrap_or_default(); + let index = |key: &str| d.fields.get(key).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let sel = index("__tabSel").unwrap_or(0).min(rows.len().saturating_sub(1)); + (rows, sel, index("__tabEdited")) +} + +/// The position (pt) Add gives a new stop among `rows`: half an inch past the furthest stop that +/// reads, half an inch when none does, and at most 100000 pt. `None` while the list holds 256 stops +/// or when a stop already sits at that position. +fn new_tab_position(rows: &[Value], unit: Unit) -> Option { + if rows.len() >= TabStop::MAX_STOPS { + return None; + } + let positions: Vec = rows.iter().filter_map(|r| stop_position(r, unit)).collect(); + let furthest = positions.iter().copied().filter(|pt| (0.0..=TabStop::MAX_POSITION).contains(pt)).reduce(f64::max); + let position = furthest.map_or(DEFAULT_TAB_INTERVAL, |pt| pt + DEFAULT_TAB_INTERVAL).min(TabStop::MAX_POSITION); + (!positions.iter().any(|pt| (pt - position).abs() < 1e-6)).then_some(position) +} + +/// Add in Tabs: a left stop at [`new_tab_position`], which becomes the selected and last edited +/// stop and is scrolled into view in the list. Nothing when that gives no position. +pub(crate) fn add_tab(d: &mut Dialog) { + let unit = unit_of(d); + let (mut rows, _, _) = tab_rows(d); + let Some(position) = new_tab_position(&rows, unit) else { return }; + rows.push(stop_field(&TabStop { position, align: TabAlign::Left, leader: String::new(), align_on: '.' }, unit)); + let at = rows.len() - 1; + d.fields.insert("tabs".into(), Value::Array(rows)); + d.fields.insert("__tabSel".into(), json!(at)); + d.fields.insert("__tabEdited".into(), json!(at)); + d.fields.insert("__tabScroll".into(), json!(true)); +} + +/// Delete Tab in Tabs: remove the selected stop; the next one (or the last) becomes selected. +pub(crate) fn delete_tab(d: &mut Dialog) { + let (mut rows, sel, edited) = tab_rows(d); + if sel >= rows.len() { + return; + } + rows.remove(sel); + match edited { + Some(e) if e == sel => { + d.fields.remove("__tabEdited"); + } + Some(e) if e > sel => { + d.fields.insert("__tabEdited".into(), json!(e - 1)); + } + _ => {} + } + d.fields.insert("__tabSel".into(), json!(sel.min(rows.len().saturating_sub(1)))); + d.fields.insert("tabs".into(), Value::Array(rows)); + d.fields.insert("__tabScroll".into(), json!(true)); +} + +/// Clear All Tabs in Tabs: an empty list of stops, which the style then sets. +pub(crate) fn clear_tabs(d: &mut Dialog) { + d.fields.insert("tabs".into(), json!([])); + d.fields.insert("__tabSel".into(), json!(0)); + d.fields.remove("__tabEdited"); +} + +/// Composition: the Single-line or Every-line Composer, and Roman Hanging Punctuation. +pub(crate) fn composition_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("paragraph-style-composition").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + let row = ui.label(tl!("Composition")); + let composers = [("singleLine", tl!("Single-line Composer")), ("everyLine", tl!("Every-line Composer"))]; + ui.label_inputs_by(row.id, |ui| choice(ui, d, "composer", &composers, true)); + ui.end_row(); + switch(ui, d, "roman_hanging", tl!("Roman Hanging Punctuation"), true); + }); +} + +/// Hyphenation: the Hyphenation checkbox and its options, which are inactive while it is off or +/// unset; Hyphenation Zone is also inactive with the Every-line Composer, which does not use it. +pub(crate) fn hyphenation_body(ui: &mut egui::Ui, d: &mut Dialog) { + let on = d.fields.get("hyphenate").and_then(Value::as_bool) == Some(true); + let single_line = d.fields.get("composer").and_then(Value::as_str) == Some("singleLine"); + egui::Grid::new("paragraph-style-hyphenation").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + switch(ui, d, "hyphenate", tl!("Hyphenation"), true); + for (key, suffix) in [ + ("words_longer_than", tl!("letters")), + ("after_first", tl!("letters")), + ("before_last", tl!("letters")), + ("hyphen_limit", tl!("hyphens")), + ] { + field_row(ui, d, key, label_of(key), suffix, on); + } + field_row(ui, d, "hyphenation_zone", label_of("hyphenation_zone"), "", on && single_line); + switch(ui, d, "hyphenate_capitalized", tl!("Hyphenate Capitalized Words"), on); + }); +} + +/// Justification: Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired and Maximum), +/// Auto Leading and Single Word Justification. +pub(crate) fn justification_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("paragraph-style-justification").num_columns(4).spacing([10.0, 8.0]).show(ui, |ui| { + ui.label(""); + for heading in [tl!("Minimum"), tl!("Desired"), tl!("Maximum")] { + ui.label(heading); + } + ui.end_row(); + for (prefix, _, _) in ROWS { + let row_label = label_of(prefix); + ui.label(row_label); + for column in COLUMNS { + let key = format!("{prefix}_{column}"); + if d.fields.get(&key).is_none_or(Value::is_null) { + d.fields.insert(key.clone(), json!("")); + } + ui.horizontal(|ui| { + let name = format!("{} {}", caption(row_label), column_name(column)); + form::text_named(ui, d, &key, &name, 60.0); + ui.label("%"); + }); + } + ui.end_row(); + } + }); + ui.add_space(8.0); + egui::Grid::new("paragraph-style-justification-more").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + field_row(ui, d, "auto_leading", label_of("auto_leading"), "%", true); + let row = ui.label(tl!("Single Word Justification:")); + let choices: Vec<(&str, &str)> = + SINGLE_WORD_VALUES.into_iter().zip([tl!("Full Justify"), tl!("Align left"), tl!("Align center"), tl!("Align right")]).collect(); + ui.label_inputs_by(row.id, |ui| choice(ui, d, "single_word", &choices, true)); + ui.end_row(); + }); +} + +/// East Asian Composition Settings: Korean Composition Settings › Korean Line Break Anywhere. +pub(crate) fn east_asian_body(ui: &mut egui::Ui, d: &mut Dialog) { + ui.strong(tl!("Korean Composition Settings")); + egui::Grid::new("paragraph-style-east-asian").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + switch(ui, d, "korean_line_break_anywhere", tl!("Korean Line Break Anywhere"), true); + }); +} + +/// The heading of a spacing column, for the accessible name of its field. +fn column_name(column: &str) -> &'static str { + match column { + "min" => tl!("Minimum"), + "desired" => tl!("Desired"), + _ => tl!("Maximum"), + } +} + +/// The General section: the style's name and every attribute it sets. +pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + let row = ui.label(tl!("Style Name:")); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, "name", 190.0)); + }); + ui.separator(); + if let Ok(attrs) = edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } +} + +/// The content of the section `d` shows. +pub(crate) fn section_body(ui: &mut egui::Ui, d: &mut Dialog) { + match d.str("section").as_str() { + "basic" => basic_body(ui, d), + "tabs" => tabs_body(ui, d), + "composition" => composition_body(ui, d), + "hyphenation" => hyphenation_body(ui, d), + "justification" => justification_body(ui, d), + "eastAsian" => east_asian_body(ui, d), + _ => general_body(ui, d), + } +} + +/// The key under which the dialog keeps the height its section content was drawn at, for the next +/// frame. +fn content_id(ui: &egui::Ui) -> egui::Id { + ui.layer_id().id.with("para-style-content") +} + +/// The dialog's body: the section list beside the selected section's content, and below them +/// Reset Panel, the Preview checkbox and an invalid value's error. The content is at most 420 points +/// tall, and scrolls when it is taller than that or than the screen less the rest of the window +/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether +/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); + let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); + let rest = (window - content).max(0.0); + let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).clamp(0.0, 420.0); + let drawn = ui.horizontal(|ui| { + section_list(ui, d); + ui.separator(); + let section = d.str("section"); + let content_w = ui.available_width(); + egui::ScrollArea::both() + .id_salt(("para-style-sections", section)) + .max_height(room) + .min_scrolled_height(room) + .max_width(content_w) + .auto_shrink([false, true]) + .show(ui, |ui| { + ui.vertical(|ui| section_body(ui, d)); + }) + .inner_rect + .height() + }); + let content_h = drawn.inner; + let was = ui.ctx().data(|m| m.get_temp::(content_id(ui))); + ui.ctx().data_mut(|m| m.insert_temp(content_id(ui), content_h)); + if was.is_none_or(|was| (was - content_h).abs() > 0.5) { + ui.ctx().request_repaint(); + } + reset_button(ui, d); + match edited_attrs(d) { + Ok(attrs) => { + let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); + form::preview(app, ui, d, tl!("Paragraph Style Options"), "paraStyle.edit", params); + } + Err(why) => super::char_style_options::attrs_error(ui, &why), + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let attrs = edited_attrs(d)?; + form::commit_preview(app, "paraStyle.edit", json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs})) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/para_style_options/tests.rs b/crates/ui-egui/src/dialogs/para_style_options/tests.rs new file mode 100644 index 0000000000..467b0dc1ae --- /dev/null +++ b/crates/ui-egui/src/dialogs/para_style_options/tests.rs @@ -0,0 +1,551 @@ +use super::*; +use vectorcraft_engine::Session; +use vectorcraft_engine::doc::{Composer, Justify, NodeId, NodeKind, ParaStyle}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app +} + +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +fn set(app: &mut VectorcraftApp, key: &str, value: Value) { + app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(key.into(), value); +} + +fn def(app: &VectorcraftApp, name: &str) -> Map { + app.session.doc().unwrap().doc.para_styles.iter().find(|d| d.name == name).map(|d| d.attrs.clone()).unwrap_or_default() +} + +fn paras(app: &VectorcraftApp, id: u64) -> Vec { + match &app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.paragraph_styles(), + _ => panic!("not text"), + } +} + +/// A style read from a file or captured from text, with attributes no section shows. +const KEPT: &str = r#"{"justify": "Left", "left_indent": 0.0, "space_before": 7.123456, "tabs": [{"position": 36.0, "align": "right"}], "direction": "rightToLeft", + "mojikumi": "lineEndHalf", "list": {"bullet": "dash"}, "hyphenation": {"words_longer_than": 5, "after_first": 3, "before_last": 3, + "hyphen_limit": 0, "zone": 0.0, "capitalized": true}}"#; + +/// Paragraph Style Options opens on a style's attributes: an attribute the style sets, a default +/// value included, fills its field, one it leaves out is empty or unset. OK with nothing changed +/// keeps every attribute, those no section shows and a distance finer than its field shows +/// included, and records no undo step. +#[test] +fn unchanged_fields_keep_every_attribute_and_set_no_undo_step() { + let mut app = app(); + let kept: Value = serde_json::from_str(KEPT).unwrap(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": kept})).unwrap(); + let stored = def(&app, "Body"); + let undo = app.session.doc().unwrap().history.undo.len(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!(d.str("justify"), "Left"); + assert_eq!(d.str("left_indent"), "0 pt", "an explicit 0 is shown"); + assert_eq!(d.str("right_indent"), "", "an indent the style leaves out is empty"); + assert!(d.fields["composer"].is_null() && d.fields["roman_hanging"].is_null() && d.fields["hyphenate"].is_null()); + assert_eq!((d.str("words_longer_than"), d.str("hyphenation_zone")), ("5".into(), "0 pt".into())); + assert_eq!(d.fields["hyphenate_capitalized"], json!(true)); + assert_eq!((d.str("word_min"), d.str("auto_leading")), (String::new(), String::new())); + assert!(d.fields["single_word"].is_null()); + assert_eq!(edited_attrs(d).unwrap(), stored); + super::super::confirm(&mut app).unwrap(); + assert_eq!(def(&app, "Body"), stored); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(app.run("ui.paraStyleOptions", json!({"name": "Missing"})).is_err()); + assert!(app.run("ui.paraStyleOptions", json!({})).is_err()); +} + +/// Each section's fields set their attributes: Alignment and a distance typed with a unit in Basic, +/// the composer and Roman Hanging Punctuation in Composition, Hyphenation and one option in +/// Hyphenation (the other options at their defaults), and a spacing row and Single Word +/// Justification in Justification. Changing Basic leaves the other attributes as they were. +#[test] +fn each_section_sets_its_attributes_and_keeps_the_others() { + let mut app = app(); + let kept: Value = serde_json::from_str(KEPT).unwrap(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": kept})).unwrap(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "justify", json!("JustifyAll")); + set(&mut app, "space_before", json!("1 in")); + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + let mut want = def(&app, "Body"); + want.insert("justify".into(), json!("JustifyAll")); + want.insert("space_before".into(), json!(72.0)); + assert_eq!(a, want, "Basic changes only its own attributes"); + + set(&mut app, "composer", json!("singleLine")); + set(&mut app, "roman_hanging", json!(false)); + set(&mut app, "hyphenate", json!(true)); + set(&mut app, "after_first", json!("4")); + set(&mut app, "hyphenation_zone", json!("18")); + set(&mut app, "word_desired", json!("90")); + set(&mut app, "single_word", json!("alignCenter")); + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!((&a["composer"], &a["roman_hanging"], &a["hyphenate"]), (&json!("singleLine"), &json!(false), &json!(true))); + assert_eq!( + a["hyphenation"], + json!({"words_longer_than": 5, "after_first": 4, "before_last": 3, "hyphen_limit": 0, "zone": 18.0, "capitalized": true}) + ); + let j = &a["justification"]; + assert_eq!((&j["word_spacing"], &j["auto_leading"], &j["single_word"]), (&json!([80.0, 90.0, 133.0]), &json!(120.0), &json!("alignCenter"))); + for key in ["tabs", "direction", "mojikumi", "list", "left_indent"] { + assert_eq!(a.get(key), want.get(key), "{key} stays as it was"); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(def(&app, "Body"), a); + + // An empty field leaves its attribute out; Justification fields all emptied remove it. + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "space_before", json!("")); + for key in JUSTIFICATION_FIELDS { + set(&mut app, key, if key == "single_word" { Value::Null } else { json!("") }); + } + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert!(!a.contains_key("space_before") && !a.contains_key("justification"), "{a:?}"); +} + +/// A value out of range, one that is not a number and a spacing row out of order are errors that +/// keep the dialog open and the style as it was. +#[test] +fn invalid_values_keep_the_dialog_open() { + let mut app = app(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + for (key, value, why) in [ + ("left_indent", "2000", "Left Indent must be a number from -1296 pt to 1296 pt"), + ("first_line_indent", "wide", "First-line Left Indent must be a number"), + ("words_longer_than", "26", "Words Longer Than must be a number from 1 to 25"), + ("after_first", "1.5", "After First must be a whole number from 1 to 15"), + ("hyphen_limit", "-1", "Hyphen Limit must be a number from 0 to 25"), + ("hyphenation_zone", "-1", "Hyphenation Zone must be a number from 0 pt to 1296 pt"), + ("letter_max", "501", "Letter Spacing must be a number from -100 to 500"), + ("auto_leading", "x", "Auto Leading must be a number"), + ("word_min", "120", "Minimum must not exceed Desired, nor Desired Maximum."), + ] { + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, key, json!(value)); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap_err(), why, "{key} = {value}"); + assert!(super::super::confirm(&mut app).is_err(), "{key} = {value}"); + assert!(app.ui.dialog.is_some(), "{key} = {value}"); + super::super::cancel(&mut app); + assert_eq!(def(&app, "Body"), Map::new()); + } + // A spacing row out of order in a style read from a file does not block a change to another + // option; the definition stores the row as the paragraph applies it. + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let held = json!({"word_spacing": [120.0, 100.0, 133.0], "auto_leading": 120.0}); + doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("justification".into(), held); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "auto_leading", json!("150")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(def(&app, "Body")["justification"]["auto_leading"], json!(150.0)); +} + +/// Reset Panel clears only the section shown, and General has none. +#[test] +fn reset_panel_clears_only_its_section() { + let mut app = app(); + let all = json!({"justify": "Center", "space_after": 6.0, "composer": "singleLine", "roman_hanging": true, "hyphenate": true, + "hyphenation": {"words_longer_than": 8}, "justification": {"auto_leading": 150.0}, "tabs": [{"position": 20.0}], + "korean_line_break_anywhere": true}); + app.run("paraStyle.new", json!({"name": "Body", "attrs": all})).unwrap(); + let stored = def(&app, "Body"); + for (section, cleared) in [ + ("basic", &["justify", "space_after"][..]), + ("tabs", &["tabs"]), + ("composition", &["composer", "roman_hanging"]), + ("hyphenation", &["hyphenate", "hyphenation"]), + ("justification", &["justification"]), + ("eastAsian", &["korean_line_break_anywhere"]), + ] { + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + assert!(app.run("ui.paraStyleOptions.resetPanel", json!({})).is_err(), "General has no Reset Panel"); + set(&mut app, "section", json!(section)); + app.run("ui.paraStyleOptions.resetPanel", json!({})).unwrap(); + let mut want = stored.clone(); + for key in cleared { + want.remove(*key); + } + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(), want, "{section}"); + super::super::cancel(&mut app); + } + assert!(app.run("ui.paraStyleOptions.resetPanel", json!({})).is_err(), "no dialog open"); +} + +/// Preview shows a change on the type that uses the style, and Cancel puts the document and its +/// history back. OK renames the style and changes its paragraphs in one undo step, a paragraph's +/// local override stays, and Undo and Redo restore both. +#[test] +fn preview_cancel_and_ok_update_the_paragraphs_in_one_undo_step() { + let mut app = app(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"left_indent": 6.0}})).unwrap(); + app.run("paraStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 4, "end": 4, "leftIndent": 20.0})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("preview")); + set(&mut app, "left_indent", json!("12")); + set(&mut app, "composer", json!("singleLine")); + frame(&mut app); + assert_eq!(paras(&app, id)[0].left_indent, 12.0, "Preview shows the change"); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "name", json!("Text")); + set(&mut app, "left_indent", json!("12")); + set(&mut app, "composer", json!("singleLine")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + let p = paras(&app, id); + assert_eq!( + p.iter().map(|p| (p.style_name.as_deref(), p.left_indent, p.composer)).collect::>(), + [(Some("Text"), 12.0, Composer::SingleLine), (Some("Text"), 20.0, Composer::SingleLine)] + ); + let changed = app.session.doc().unwrap().doc.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, changed); +} + +/// New Paragraph Style opens with the sections, filled in from the selected paragraph; a changed +/// field goes into the new style, and the others keep the captured values. The style is not +/// applied to the text. +#[test] +fn new_paragraph_style_offers_the_sections() { + let mut app = app(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "One"})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setStyle", json!({"id": id, "justify": "center"})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("ui.newParaStyle", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("section"), d.str("justify")), ("general".into(), "Center".into())); + let captured = d.fields["__attrs"].as_object().cloned().unwrap(); + let mut texts = String::new(); + for section in SECTIONS { + set(&mut app, "section", json!(section)); + texts += &crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + } + for label in [ + "Basic Paragraph Formats", + "Tabs", + "Composition", + "First-line Left Indent", + "Align On:", + "Hyphenate Capitalized Words", + "Single Word Justification:", + ] { + assert!(texts.contains(label), "{label} is drawn: {texts}"); + } + set(&mut app, "section", json!("basic")); + app.run("ui.paraStyleOptions.resetPanel", json!({})).unwrap(); + set(&mut app, "space_after", json!("3")); + set(&mut app, "name", json!("Lead")); + super::super::confirm(&mut app).unwrap(); + let mut want = captured; + for key in ["justify", "left_indent", "right_indent", "first_line_indent", "space_before"] { + want.remove(key); + } + want.insert("space_after".into(), json!(3.0)); + assert_eq!(def(&app, "Lead"), want); + assert_eq!(paras(&app, id)[0].style_name, None, "making the style does not apply it"); + assert_eq!(paras(&app, id)[0].justify, Justify::Center); +} + +/// East Asian Composition Settings › Korean Line Break Anywhere sets the style's attribute, which +/// its paragraphs take; unset, the style leaves it out and the paragraphs keep their own. +#[test] +fn korean_line_break_anywhere_is_set_by_the_east_asian_section() { + let mut app = app(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "가나 다라"})).unwrap()["id"].as_u64().unwrap(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + app.run("paraStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + assert!(!paras(&app, id)[0].korean_line_break_anywhere); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields["korean_line_break_anywhere"].is_null()); + set(&mut app, "section", json!("eastAsian")); + set(&mut app, "korean_line_break_anywhere", json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(def(&app, "Body").get("korean_line_break_anywhere"), Some(&json!(true))); + assert!(paras(&app, id)[0].korean_line_break_anywhere, "the style's paragraphs take it"); +} + +/// The rows of the `tabs` field of the open dialog. +fn tab_rows(app: &VectorcraftApp) -> Vec { + app.ui.dialog.as_ref().unwrap().fields["tabs"].as_array().cloned().unwrap_or_default() +} + +/// Tabs shows a style's stops in the General unit with their alignment, leader and Align On +/// character; a stop left as it was keeps its position exactly, a changed one is read in the unit, +/// and the stops are stored sorted by position. Add puts a left stop half an inch past the furthest +/// stop, Delete Tab removes the selected stop and Clear All Tabs leaves the style an empty list. +#[test] +fn tabs_section_edits_the_style_stops() { + let mut app = app(); + let stops = json!([{"position": 36.0, "align": "right"}, {"position": 72.123456, "align": "decimal", "leader": ".", "alignOn": ","}]); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"left_indent": 3.0, "tabs": stops}})).unwrap(); + let stored = def(&app, "Body"); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let rows = tab_rows(&app); + let shown: Vec<(&str, &str, &str, &str)> = rows + .iter() + .map(|r| (r["position"].as_str().unwrap(), r["align"].as_str().unwrap(), r["leader"].as_str().unwrap(), r["alignOn"].as_str().unwrap())) + .collect(); + assert_eq!(shown, [("36 pt", "right", "", "."), ("72.123 pt", "decimal", ".", ",")]); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(), stored, "nothing changed"); + + // The first stop moves past the second and turns centered; the second keeps its exact position. + let mut rows = rows; + rows[0]["position"] = json!("1.5 in"); + rows[0]["align"] = json!("center"); + set(&mut app, "tabs", Value::from(rows)); + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!( + a["tabs"], + json!([{"position": 72.123456, "align": "decimal", "leader": ".", "alignOn": ","}, {"position": 108.0, "align": "center", "alignOn": "."}]) + ); + assert_eq!(a["left_indent"], json!(3.0), "other attributes stay"); + + let d = app.ui.dialog.as_mut().unwrap(); + add_tab(d); + assert_eq!((tab_rows(&app).len(), app.ui.dialog.as_ref().unwrap().fields["__tabSel"].clone()), (3, json!(2))); + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(a["tabs"][2], json!({"position": 144.0, "align": "left", "alignOn": "."}), "half an inch past the furthest"); + set(&mut app, "__tabSel", json!(0)); + delete_tab(app.ui.dialog.as_mut().unwrap()); + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(a["tabs"].as_array().unwrap().iter().map(|s| s["position"].clone()).collect::>(), [json!(72.123456), json!(144.0)]); + super::super::confirm(&mut app).unwrap(); + assert_eq!(def(&app, "Body")["tabs"].as_array().map(Vec::len), Some(2)); + + // Clear All Tabs leaves an empty list set, which Reset Panel removes; a new stop on a style + // without stops goes at half an inch. + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + clear_tabs(app.ui.dialog.as_mut().unwrap()); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["tabs"], json!([])); + super::super::confirm(&mut app).unwrap(); + assert_eq!(def(&app, "Body")["tabs"], json!([]), "an empty list is stored"); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "section", json!("tabs")); + app.run("ui.paraStyleOptions.resetPanel", json!({})).unwrap(); + let a = edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert!(!a.contains_key("tabs") && a["left_indent"] == json!(3.0), "{a:?}"); + add_tab(app.ui.dialog.as_mut().unwrap()); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["tabs"], json!([{"position": 36.0, "align": "left", "alignOn": "."}])); +} + +/// Of stops typed at one position, the one edited last is kept; with none edited, the first in the +/// list is. +#[test] +fn a_repeated_tab_position_keeps_the_stop_edited_last() { + let mut app = app(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let rows = json!([{"position": "36", "align": "right"}, {"position": "0.5 in", "align": "center"}, {"position": "10", "align": "left"}]); + set(&mut app, "tabs", rows); + let kept = |app: &VectorcraftApp| edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["tabs"].clone(); + assert_eq!(kept(&app), json!([{"position": 10.0, "align": "left", "alignOn": "."}, {"position": 36.0, "align": "right", "alignOn": "."}])); + set(&mut app, "__tabEdited", json!(1)); + assert_eq!(kept(&app)[1]["align"], json!("center")); +} + +/// The list of stops scrolls, so a style with 256 stops keeps the Tabs section short enough for the +/// dialog's buttons to stay on screen. +#[test] +fn a_long_tab_list_scrolls() { + let mut app = app(); + let stops: Vec = (0..256).map(|i| json!({"position": 36.0 * f64::from(i + 1), "align": "left"})).collect(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut height = f32::INFINITY; + let mut out = ctx.run_ui(Default::default(), |ui| { + let top = ui.cursor().top(); + tabs_body(ui, d); + height = ui.cursor().top() - top; + }); + out.textures_delta.clear(); + assert!(height < 400.0, "the Tabs section is {height} points tall"); +} + +/// The stop Add puts at the end of a long list is scrolled into view: its row in the list is drawn +/// inside the list's visible area. +#[test] +fn an_added_tab_stop_is_scrolled_into_view() { + let mut app = app(); + let stops: Vec = (0..100).map(|i| json!({"position": 36.0 * f64::from(i + 1), "align": "left"})).collect(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let draw = |d: &mut Dialog| { + let mut out = ctx.run_ui(Default::default(), |ui| tabs_body(ui, d)); + out.textures_delta.clear(); + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => t.galley.text().starts_with("3636 pt ") && c.clip_rect.intersects(t.visual_bounding_rect()), + _ => false, + }) + }; + draw(d); + add_tab(d); + let shown: Vec = (0..3).map(|_| draw(d)).collect(); + assert_eq!(shown.last(), Some(&true), "{shown:?}"); +} + +/// Add does not put a stop where one already is: with a stop at 100000 pt, the largest position, +/// it adds nothing and the Add button is disabled, so the existing stop keeps its settings. +#[test] +fn add_leaves_a_stop_at_the_largest_position_alone() { + let mut app = app(); + let stops = json!([{"position": 100000.0, "align": "right", "leader": "-"}]); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let before = tab_rows(&app); + add_tab(app.ui.dialog.as_mut().unwrap()); + assert_eq!(tab_rows(&app), before, "no stop is added"); + assert!(new_tab_position(&before, Unit::Points).is_none(), "Add is disabled"); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap(), def(&app, "Body"), "the stop is kept"); +} + +/// A tab position out of range or not a distance, an unknown alignment, a leader of more than eight +/// characters, an Align On entry that is not one character, more than 256 stops, a `tabs` value that +/// is not a list and a stop that is not an object are errors that keep the dialog open and the style +/// as it was. Vertical type names the position Y. +#[test] +fn invalid_tab_stops_keep_the_dialog_open() { + let mut app = app(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + let stop = |key: &str, value: Value| { + let mut stop = json!({"position": "36", "align": "decimal", "leader": "", "alignOn": "."}); + stop[key] = value; + json!([stop]) + }; + let many = Value::from((0..257).map(|i| json!({"position": format!("{i}"), "align": "left"})).collect::>()); + for (tabs, why) in [ + (stop("position", json!("-1")), "X must be a number from 0 pt to 100000 pt"), + (stop("position", json!("100001 pt")), "X must be a number from 0 pt to 100000 pt"), + (stop("position", json!("far")), "X must be a number"), + (stop("align", json!("diagonal")), "unknown align `diagonal`"), + (stop("leader", json!("123456789")), "Leader must be at most 8 characters"), + (stop("alignOn", json!("")), "Align On must be one character"), + (stop("alignOn", json!(",.")), "Align On must be one character"), + (many, "at most 256 tab stops"), + (json!("36"), "`tabs` must be an array"), + (json!({"position": "36"}), "`tabs` must be an array"), + (json!([5]), "X must be a number"), + ] { + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "tabs", tabs.clone()); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap_err(), why, "{tabs}"); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + super::super::cancel(&mut app); + assert_eq!(def(&app, "Body"), Map::new()); + } + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "__vertical", json!(true)); + set(&mut app, "tabs", stop("position", json!("far"))); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap_err(), "Y must be a number"); + // Stops a style read from a file holds out of range stay while another stop is added. + super::super::cancel(&mut app); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let held = json!([{"position": 200000.0, "align": "left", "leader": "123456789", "alignOn": "."}]); + doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), held.clone()); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + add_tab(app.ui.dialog.as_mut().unwrap()); + super::super::confirm(&mut app).unwrap(); + assert_eq!(def(&app, "Body")["tabs"][1], held[0]); +} + +/// Preview shows a style's new stops on the paragraphs that use it, and Cancel puts the document +/// and its history back. OK sets them in one undo step, a paragraph whose stops the Tabs panel set +/// keeps its own, and Undo and Redo restore both. Saving and opening the document keeps the stops. +#[test] +fn tabs_preview_cancel_and_ok_update_the_paragraphs_in_one_undo_step() { + let mut app = app(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "a\tb\nc\td"})).unwrap()["id"].as_u64().unwrap(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": [{"position": 36.0}]}})).unwrap(); + app.run("paraStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + app.run("text.tabs.set", json!({"ids": [id], "start": 4, "end": 4, "stops": [{"position": 50.0}]})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let new_stops = json!([{"position": "20", "align": "right", "leader": "."}, {"position": "80", "align": "decimal", "alignOn": ","}]); + let positions = |app: &VectorcraftApp| paras(app, id).iter().map(|p| p.tabs.iter().map(|t| t.position).collect::>()).collect::>(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "section", json!("tabs")); + set(&mut app, "tabs", new_stops.clone()); + frame(&mut app); + assert_eq!(positions(&app), [vec![20.0, 80.0], vec![50.0]], "Preview shows the change"); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + set(&mut app, "tabs", new_stops); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(positions(&app), [vec![20.0, 80.0], vec![50.0]]); + let p = paras(&app, id); + assert_eq!((p[0].tabs[0].leader.as_str(), p[0].tabs[1].align_on), (".", ',')); + let changed = app.session.doc().unwrap().doc.clone(); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&changed, false)).unwrap(); + let def_of = |d: &vectorcraft_doc::Document| d.para_styles.iter().find(|s| s.name == "Body").map(|s| s.attrs.clone()); + assert_eq!(def_of(&saved), def_of(&changed)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, changed); +} + +/// The section list, Reset Panel and both buttons are drawn in every section, and the Hyphenation +/// options are drawn whether or not Hyphenation is on. +#[test] +fn every_section_draws_its_fields() { + let mut app = app(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + app.run("ui.paraStyleOptions", json!({"name": "Body"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (section, label) in [ + ("general", "Style Name:"), + ("basic", "Space After Paragraph"), + ("tabs", "Clear All Tabs"), + ("composition", "Roman Hanging Punctuation"), + ("hyphenation", "Hyphenation Zone:"), + ("justification", "Glyph Scaling:"), + ("eastAsian", "Korean Line Break Anywhere"), + ] { + set(&mut app, "section", json!(section)); + let mut texts = String::new(); + for _ in 0..5 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + texts = crate::tests_labels::shapes_text(&out); + } + for shown in [label, "General", "Basic Paragraph Formats", "Tabs", "Justification", "Reset Panel", "OK", "Cancel"] { + assert!(texts.contains(shown), "{shown} is drawn in {section}: {texts}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/pdf_presets.rs b/crates/ui-egui/src/dialogs/pdf_presets.rs index 10f7e0e451..f29b25e9e1 100644 --- a/crates/ui-egui/src/dialogs/pdf_presets.rs +++ b/crates/ui-egui/src/dialogs/pdf_presets.rs @@ -173,8 +173,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> } Action::Import => { // On the web the picked file arrives later and imports through `io::open_bytes`. - if let Some(f) = app.services.open_async.as_mut() { - f(); + if crate::picks::open_async(app) { return Ok(()); } let pick = crate::FilePick { diff --git a/crates/ui-egui/src/dialogs/perspective_presets.rs b/crates/ui-egui/src/dialogs/perspective_presets.rs index 7432bd3b2d..4772fa133b 100644 --- a/crates/ui-egui/src/dialogs/perspective_presets.rs +++ b/crates/ui-egui/src/dialogs/perspective_presets.rs @@ -191,8 +191,7 @@ pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current } Action::Import => { // On the web the picked file arrives later and imports through `io::open_bytes`. - if let Some(f) = app.services.open_async.as_mut() { - f(); + if crate::picks::open_async(app) { return Ok(()); } let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Perspective grid presets", PRESET_EXTS)], ..Default::default() }; diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 76f71f3b4e..706188f6da 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -6,7 +6,10 @@ //! declared parameter (fields named after them; `__plugin` is the plug-in id) with a live //! Preview, and OK keeps the run as one undo step (`plugin.run`). A filter without parameters runs //! at once. A heavy filter (its manifest's `budget`) has no Preview, since a run may take minutes: -//! it runs in the background ([`crate::plugin_runs`]). A filter or live effect with commands of +//! it runs in the background ([`crate::plugin_runs`]). A light filter that reports its progress +//! (plug-in API level 2 with the `progress` permission) and calls no commands runs in the +//! background too, with its progress and Cancel, when it runs at once or when OK runs it without a +//! kept preview ([`in_background`]). A filter or live effect with commands of //! its own is a submenu named after it, holding its item and then its commands; a command with //! parameters opens the same dialog for them ([`open_command`]). Exporters are formats of File › Export › //! Export As; one with parameters opens dialog `pluginExport` once the file is picked, and its @@ -16,7 +19,9 @@ //! //! Dialog `pluginInstall` asks a person to approve a plug-in's permissions or heavy budget. What it //! shows and installs is held by the app, not in its fields; a control request or synthetic input -//! can't confirm it. Enter confirms it only when OK has the keyboard focus. +//! can't confirm it. Enter confirms it only when OK has the keyboard focus. OK takes no click, Enter +//! or Space until the question has been on screen in the focused window for [`APPROVAL_DELAY`], and +//! that time starts over for every new question and whenever the window loses the focus. use std::sync::Arc; @@ -200,12 +205,19 @@ fn params(d: &Dialog) -> Value { } } -/// Runs filter `plugin` with `plugin.run`'s params `p`: at once, or in the background when it is -/// heavy. +/// Does filter `m` run in the background ([`crate::plugin_runs`]) rather than on the UI thread? A +/// heavy one does, and so does a light one that reports its progress (the `progress` permission) +/// unless it calls commands, which run only in the session. +fn in_background(m: &Manifest) -> bool { + m.budget == Budget::Heavy || (m.permissions().contains(&permissions::Permission::Progress) && m.command_allowlist.is_empty()) +} + +/// Runs filter `plugin` with `plugin.run`'s params `p`: at once, or in the background +/// ([`in_background`]). fn run(app: &mut VectorcraftApp, plugin: &Plugin, p: Value) -> Result { - match plugin.manifest().budget { - Budget::Light => app.run(CMD, p), - Budget::Heavy => crate::plugin_runs::start(app, p), + match in_background(plugin.manifest()) { + false => app.run(CMD, p), + true => crate::plugin_runs::start(app, p), } } @@ -234,11 +246,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: a filter keeps its previewed run as one undo step; a heavy one, which has no preview, starts -/// in the background ([`run`]) and the dialog closes. +/// OK: a filter keeps its previewed run as one undo step; a heavy one, which has no preview, and a +/// light one that runs in the background ([`in_background`]) with Preview off or a failed preview, +/// start in the background ([`run`]) and the dialog closes. A preview still shown when Preview was +/// just turned off, or a preview that failed, is rolled back first. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let own_run = d.str("__command").is_empty(); + let kept = |plugin: &Plugin| { + plugin.manifest().budget == Budget::Light && d.bool("preview") && app.session.in_interaction() && !d.fields.contains_key(form::REFUSED) + }; match registry::get(&d.str("__plugin")) { - Some(plugin) if plugin.manifest().budget == Budget::Heavy => { + Some(plugin) if own_run && in_background(plugin.manifest()) && !kept(&plugin) => { + if d.fields.contains_key(form::PREVIEWED) && app.session.in_interaction() { + let _ = app.session.cancel_interaction(); + } let r = run(app, &plugin, params(d)); if r.is_ok() { app.ui.dialog = None; @@ -320,6 +341,21 @@ fn import_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result /// The dialog kind of the approval of a plug-in install. pub const INSTALL_KIND: &str = "pluginInstall"; +/// Who asked for a plug-in install, fixed when the request is made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum InstallOrigin { + /// The person at the keyboard: Install Plug-in…, File › Open or a drop. + Person, + /// A control or MCP request, a frame of synthetic input, or a file dialog that one of them + /// opened ([`VectorcraftApp::automation_asked`]): nothing in the dialog installs it, and the + /// person starts Install Plug-in… to install it. + Automation, +} + +/// What [`ask_install`] answers, as `approval`, for a question automation asked: the person has to +/// start Install Plug-in… to install the module. +pub(crate) const PERSON_MUST_START_INSTALL: &str = "personMustStartInstall"; + /// A plug-in install waiting for a person's answer. pub(crate) struct PendingInstall { /// The question and the lines under it, in the UI language. @@ -329,6 +365,83 @@ pub(crate) struct PendingInstall { pub params: Value, /// What OK approves: the module the question is about. pub approval: InstallApproval, + /// Who asked; a question automation asked has no OK that installs. + pub origin: InstallOrigin, + /// How long the question has been on screen; [`ask_install`] starts it over. + pub shown: Shown, +} + +/// How long, in seconds, the approval's question stays on screen in the focused window, on every +/// frame and unchanged, before its OK takes a click, Enter or Space. +pub(crate) const APPROVAL_DELAY: f64 = 0.5; + +/// How long the approval's question has been on screen, from the frames that drew it. +#[derive(Default)] +pub(crate) struct Shown { + /// The time of the first frame of the current showing: drawn, visible, in the focused window, + /// right after a frame that drew it too. `None` while it isn't shown. + since: Option, + /// The pass number and time of the last frame that drew it. + pass: Option, + last: Option, + /// A pointer button, Enter or Space was down on a frame where OK was disabled, and they haven't + /// all been let go of since. + pressed_early: bool, + /// OK takes input: shown for [`APPROVAL_DELAY`], with no press from before that held. + ready: bool, +} + +impl Shown { + /// Notes a frame that draws the question in `ui` → whether OK is enabled on it. The showing + /// starts over when the frame before didn't draw it, when time went back, when the window lost + /// the focus since the frame before, and on any frame that is a measuring pass, is invisible or + /// comes while the window doesn't have the focus. + fn drawn(&mut self, ui: &egui::Ui) -> bool { + let pass = ui.ctx().cumulative_pass_nr(); + let (now, focused, left, pressed) = ui.input(|i| { + let left = i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(false))); + let pressed = i.pointer.any_pressed() || [egui::Key::Enter, egui::Key::Space].into_iter().any(|k| i.key_pressed(k)); + (i.time, i.focused, left, pressed || Self::held(i)) + }); + let seen = focused && ui.is_visible() && !ui.is_sizing_pass() && now.is_finite(); + let follows = self.pass.is_some_and(|p| p.checked_add(1) == Some(pass)) && self.last.is_some_and(|t| t <= now); + if !seen || !follows || left { + self.since = None; + } + if seen && self.since.is_none() { + self.since = Some(now); + } + (self.pass, self.last) = (Some(pass), Some(now)); + let enabled = self.since.is_some_and(|s| now - s >= APPROVAL_DELAY); + if pressed && !enabled { + self.pressed_early = true; + } + self.ready = enabled && !self.pressed_early; + if let Some(s) = self.since.filter(|_| !enabled) { + ui.ctx().request_repaint_after_secs((s + APPROVAL_DELAY - now) as f32); + } + enabled + } + + /// After the frame's OK: a press from before OK took input stops counting once every pointer + /// button, Enter and Space are up. + fn released(&mut self, ui: &egui::Ui) { + if !ui.input(Self::held) { + self.pressed_early = false; + } + } + + /// Whether a pointer button, Enter or Space is down: what can click OK when it is let go of or + /// repeats. + fn held(i: &egui::InputState) -> bool { + i.pointer.any_down() || i.key_down(egui::Key::Enter) || i.key_down(egui::Key::Space) + } + + /// Whether OK takes input: the question was shown for [`APPROVAL_DELAY`] on the last frame + /// that drew it. + pub(crate) fn ready(&self) -> bool { + self.ready + } } /// No OK in the shared footer: the OK in its body is a `Sense::click` button, which Enter clicks @@ -342,25 +455,48 @@ pub(super) const INSTALL_SPEC: DialogSpec = DialogSpec { ..DialogSpec::FORM }; -/// Asks a person whether to install what `pending` describes. → `{pending}`. -pub(crate) fn ask_install(app: &mut VectorcraftApp, pending: PendingInstall) -> Value { +/// Asks a person whether to install what `pending` describes, its question not yet shown, even when +/// it reads as the one it replaces. → `{pending}`, and `approval: "personMustStartInstall"` when +/// automation asked. +pub(crate) fn ask_install(app: &mut VectorcraftApp, mut pending: PendingInstall) -> Value { + pending.shown = Shown::default(); + let automated = pending.origin == InstallOrigin::Automation; app.pending_plugin_install = Some(pending); app.ui.dialog = Some(Dialog::new(INSTALL_KIND, json!({}))); + if automated { + return json!({ "pending": INSTALL_KIND, "approval": PERSON_MUST_START_INSTALL }); + } json!({ "pending": INSTALL_KIND }) } +/// What the approval says when automation asked for the install; the error of its OK +/// ([`install_confirm`]) is the same text. +fn automation_asked_note() -> &'static str { + tl!("Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself.") +} + +/// The question, the lines under it, and OK, which is disabled until the question has been shown +/// for [`APPROVAL_DELAY`] ([`Shown`]), and Cancel, which never waits. When automation asked, a note +/// says so and OK stays disabled. fn install_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> DialogAction { - let Some(pending) = app.pending_plugin_install.as_ref() else { return DialogAction::Cancel }; + let Some(pending) = app.pending_plugin_install.as_mut() else { return DialogAction::Cancel }; + let person = pending.origin == InstallOrigin::Person; + let enabled = pending.shown.drawn(ui) && person; ui.label(egui::RichText::new(&pending.message).strong()); ui.add_space(8.0); ui.label(egui::RichText::new(&pending.detail).color(crate::theme::Tokens::get(ui.ctx()).text_dim)); + if !person { + ui.add_space(8.0); + ui.label(egui::RichText::new(automation_asked_note()).strong()); + } ui.add_space(16.0); let mut action = DialogAction::None; let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { - if widgets::primary_button_enabled(ui, "OK", true).clicked() { + if widgets::primary_button_enabled(ui, "OK", enabled).clicked() && person && pending.shown.ready() { action = DialogAction::Confirm; } + pending.shown.released(ui); ui.add_space(8.0); if widgets::secondary_button(ui, "Cancel").clicked() { action = DialogAction::Cancel; @@ -370,11 +506,18 @@ fn install_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> } /// OK: installs the module the dialog showed, if a person pressed it; automation is refused and the -/// dialog stays open. +/// dialog stays open, and so is any OK of a question automation asked. Before the question has been +/// shown for [`APPROVAL_DELAY`] it installs nothing and the dialog stays open. → `{pending}`. fn install_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + if app.pending_plugin_install.as_ref().is_some_and(|p| p.origin == InstallOrigin::Automation) { + return Err("Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself.".into()); + } if app.automation_is_acting() { return Err("Only the person at the keyboard can approve installing a plug-in".into()); } + if app.pending_plugin_install.as_ref().is_some_and(|p| !p.shown.ready()) { + return Ok(json!({ "pending": INSTALL_KIND })); + } app.ui.dialog = None; let Some(pending) = app.pending_plugin_install.take() else { return Ok(Value::Null) }; app.session.approve_plugin_install(pending.approval); diff --git a/crates/ui-egui/src/dialogs/print_presets.rs b/crates/ui-egui/src/dialogs/print_presets.rs index a8a9f42449..3ad798d998 100644 --- a/crates/ui-egui/src/dialogs/print_presets.rs +++ b/crates/ui-egui/src/dialogs/print_presets.rs @@ -153,8 +153,7 @@ pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current } Action::Import => { // On the web the picked file arrives later and imports through `io::open_bytes`. - if let Some(f) = app.services.open_async.as_mut() { - f(); + if crate::picks::open_async(app) { return Ok(()); } let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Print presets", PRESET_EXTS)], ..Default::default() }; diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 6ca2e57715..c7a306887e 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -1,12 +1,12 @@ //! Compact controls for the 3D and Materials effects: Extrude & Bevel, Revolve, Inflate and Rotate, -//! and Extrude & Bevel (Classic), whose own controls are in `three_d_classic`. The object and the -//! rotation and light gizmos live on the artboard. All document changes run through the effect +//! and Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), whose own controls are in +//! `three_d_classic`. The object and the rotation and light gizmos live on the artboard. All document changes run through the effect //! dialog's existing preview/commit commands. use egui::{Align2, FontId, Id, Pos2, Sense, Stroke, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_effects::{CLASSIC_EXTRUDE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS}; +use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS}; use crate::state::Dialog; use crate::theme::Tokens; @@ -145,11 +145,12 @@ pub(super) fn c3(s: &'static str) -> &'static str { crate::i18n::tr_ctx(crate::i18n::current(), "3d", s) } -/// Extrude & Bevel, Inflate and Extrude & Bevel (Classic): Object, Rotation and Lighting tabs -/// (Rotate has no Object tab). The rotation gizmo shows on the first two, the light gizmo on -/// Lighting. +/// Extrude & Bevel, Inflate, Extrude & Bevel (Classic) and Revolve (Classic): Object, Rotation and +/// Lighting tabs (Rotate and Rotate (Classic) have no Object tab). The rotation gizmo shows on the +/// first two, the light gizmo on Lighting. fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &str) { - let object = id == EXTRUDE || id == INFLATE || id == CLASSIC_EXTRUDE; + let classic = vectorcraft_effects::is_classic_three_d(id); + let object = id == EXTRUDE || id == INFLATE || id == CLASSIC_EXTRUDE || id == CLASSIC_REVOLVE; let mut tabs = vec![]; if object { tabs.push(tl!("Object")); @@ -169,7 +170,7 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: & } ui.add_space(8.0); if super::revolve_gizmo::lighting(d) { - if id == CLASSIC_EXTRUDE { + if classic { super::three_d_classic::surface_controls(ui, d); } else { lighting_controls(ui, d); @@ -178,6 +179,8 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: & let unit = app.session.general_unit(); if id == CLASSIC_EXTRUDE { super::three_d_classic::object_controls(ui, d, unit); + } else if id == CLASSIC_REVOLVE { + super::three_d_classic::revolve_controls(ui, d, unit); } else if id == EXTRUDE { extrude_controls(ui, d, unit); } else { @@ -333,6 +336,27 @@ fn lighting_controls(ui: &mut egui::Ui, d: &mut Dialog) { store_selected(d, &selected); } }); + shadow_controls(ui, d); +} + +/// The Shadows switch, and below it while the switch is on or mixed, the shadow's Position, +/// Distance from Object and Shadow Bounds. The first light casts the shadow, so they are +/// unavailable while Shading is off. +fn shadow_controls(ui: &mut egui::Ui, d: &mut Dialog) { + ui.add_enabled_ui(flag(d, "shade", true) != Some(false), |ui| { + toggle(ui, d, "shadow", tl!("Shadows"), false); + if flag(d, "shadow", false) == Some(false) { + return; + } + let positions: Vec<(Value, &str)> = super::effect::own_choices(&d.str("__effect"), "shadowPosition", false) + .unwrap_or_default() + .into_iter() + .map(|(label, value)| (json!(value), label)) + .collect(); + choice(ui, d, "shadowPosition", tl!("Position"), &positions); + number(ui, d, "shadowDistance", tl!("Distance from Object"), (0.0, 100.0), "%", 1, None); + number(ui, d, "shadowBounds", tl!("Shadow Bounds"), (10.0, 400.0), "%", 1, None); + }); } fn lighting_presets(ui: &mut egui::Ui, d: &mut Dialog) { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 103fbe6ad0..fd802f83f0 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -148,6 +148,24 @@ fn command_driven_fields_preview_and_small_windows_keep_the_buttons_reachable() assert!(!h.app.session.in_interaction()); } +#[test] +fn the_shadows_switch_shows_its_settings_and_turns_the_shadow_on_in_one_undo_step() { + let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", EXTRUDE, vec2(1280.0, 900.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + h.click(h.rect("Lighting").center()); + assert!(!h.texts.iter().any(|(s, _)| s == "Shadow Bounds"), "the settings show only while shadows are on"); + h.click(h.rect("Shadows").center()); + assert_eq!(h.app.ui.dialog.as_ref().unwrap().fields.get("shadow"), Some(&json!(true))); + assert!(h.texts.iter().any(|(s, _)| s == "Distance from Object")); + let state = h.app.session.doc().unwrap(); + let node = state.doc.node(state.selection.objects[0]).unwrap(); + assert_eq!(node.appearance.effects[0].params["shadow"], json!(true), "the preview draws the shadow"); + dialogs::confirm(&mut h.app).unwrap(); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + #[test] fn lighting_tab_shows_light_fields_and_keeps_the_dialog_compact() { let mut h = Harness::new(vec2(1280.0, 900.0)); @@ -158,7 +176,9 @@ fn lighting_tab_shows_light_fields_and_keeps_the_dialog_compact() { assert!(Rect::from_min_size(Pos2::ZERO, h.screen).contains_rect(h.rect(label))); } let panel = h.ctx.memory(|m| m.area_rect(Id::unique(("dialog", "effect")).with("revolve"))).unwrap(); - assert!(panel.width() < 420.0 && panel.height() < 570.0, "compact lighting controls with light management: {panel:?}"); + // The Shadows switch adds one 28-point row to the 570-point bound; its settings show only + // while it is on. + assert!(panel.width() < 420.0 && panel.height() < 600.0, "compact lighting controls with light management: {panel:?}"); h.drag(h.rect("Height").center(), vec2(24.0, 0.0)); assert_ne!(h.value("lightHeight"), 30.0); h.click(h.response(("revolve-reset", "lightHeight")).center()); @@ -359,6 +379,87 @@ fn classic_extrude_bevel_shows_its_options_and_applies_as_one_step() { assert_eq!(h.app.session.doc().unwrap().doc, before); } +/// Revolve (Classic): its angle, cap, offset and axis side on the Object tab, Position on the +/// Rotation tab, and the classic surface on the Lighting tab, without Draw Hidden Faces; OK keeps +/// the edit as one undo step. +#[test] +fn classic_revolve_shows_its_options_and_applies_as_one_step() { + use vectorcraft_effects::CLASSIC_REVOLVE; + let mut h = Harness::with("M100 40 L130 60 L130 140 L100 160", CLASSIC_REVOLVE, vec2(1400.0, 1000.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + for text in ["Angle", "Cap", "Offset", "Axis side", "Left"] { + h.rect(text); + } + assert!(!h.texts.iter().any(|(t, _)| t == "Segments" || t == "Revolve angle" || t == "Depth"), "the other effects' options stay out"); + h.app.ui.dialog.as_mut().unwrap().fields.insert("__tab".into(), json!("rotation")); + h.settle(); + for text in ["Presets", "Rotation X", "Perspective", "Off-Axis Front"] { + h.rect(text); + } + h.click(h.rect("Lighting").center()); + h.settle(); + for text in ["Surface", "Plastic", "Light Intensity", "Ambient Light", "Highlight Size", "Blend Steps", "Shading Color"] { + h.rect(text); + } + assert!(!h.texts.iter().any(|(t, _)| t == "Draw Hidden Faces"), "every face is drawn"); + assert_eq!(dialogs::revolve_gizmo::hint(h.app.ui.dialog.as_ref().unwrap()), "Drag the light, or its rings. Shift snaps to 15°."); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("edge".into(), json!("right")); + d.fields.insert("offset".into(), json!(12.0)); + d.fields.insert("surface".into(), json!("wireframe")); + h.settle(); + assert_eq!(dialogs::revolve_gizmo::hint(h.app.ui.dialog.as_ref().unwrap()), "Drag values or labels. Double-click a value to type."); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let fx = &state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0]; + assert_eq!(fx.id, CLASSIC_REVOLVE); + assert_eq!( + (fx.params["edge"].clone(), fx.params["offset"].as_f64(), fx.params["surface"].clone()), + (json!("right"), Some(12.0), json!("wireframe")) + ); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + +/// Rotate (Classic): Position on the Rotation tab, with no Object tab, and No Shading or Diffuse +/// on the Lighting tab, without the highlight or Draw Hidden Faces; OK keeps the edit as one undo +/// step. +#[test] +fn classic_rotate_shows_its_options_and_applies_as_one_step() { + use vectorcraft_effects::CLASSIC_ROTATE; + let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", CLASSIC_ROTATE, vec2(1400.0, 1000.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + for text in ["Rotation", "Presets", "Rotation X", "Perspective", "Off-Axis Front"] { + h.rect(text); + } + assert!(!h.texts.iter().any(|(t, _)| t == "Object" || t == "Depth" || t == "Angle"), "no Object tab"); + h.click(h.rect("Lighting").center()); + h.settle(); + for text in ["Surface", "Diffuse", "Light Intensity", "Ambient Light", "Blend Steps", "Shading Color"] { + h.rect(text); + } + assert!( + !h.texts.iter().any(|(t, _)| t == "Highlight Intensity" || t == "Highlight Size" || t == "Draw Hidden Faces"), + "no highlight and no hidden faces" + ); + assert_eq!(dialogs::revolve_gizmo::hint(h.app.ui.dialog.as_ref().unwrap()), "Drag the light, or its rings. Shift snaps to 15°."); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("surface".into(), json!("none")); + d.fields.insert("rotationY".into(), json!(40.0)); + h.settle(); + assert_eq!(dialogs::revolve_gizmo::hint(h.app.ui.dialog.as_ref().unwrap()), "Drag values or labels. Double-click a value to type."); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let fx = &state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0]; + assert_eq!(fx.id, CLASSIC_ROTATE); + assert_eq!((fx.params["surface"].clone(), fx.params["rotationY"].as_f64()), (json!("none"), Some(40.0))); + assert!(fx.params.get("highlightSize").is_none() && fx.params.get("drawHiddenFaces").is_none()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + #[test] fn extrude_bevel_options_enable_with_a_bevel_shape() { let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0)); diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 6ef51d38ed..5016eacd06 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -1,9 +1,9 @@ //! Artboard rotation and light controls for the active 3D effect dialog (Extrude & Bevel, Revolve, -//! Inflate, Rotate). Gestures edit fields; +//! Inflate, Rotate and the classic 3D effects). Gestures edit fields; //! the existing effect preview applies commands and owns OK, Cancel and undo. use egui::{Align2, FontId, Id, Pos2, Rect, Sense, Stroke, Vec2, vec2}; use serde_json::json; -use vectorcraft_effects::REVOLVE; +use vectorcraft_effects::{CLASSIC_REVOLVE, REVOLVE}; use vectorcraft_geom::Point; use vectorcraft_three_d::Revolve; @@ -20,14 +20,11 @@ pub(crate) fn lighting(d: &Dialog) -> bool { d.str("__gizmo") == "light" } -/// Does the effect take light: Shading on, or for Extrude & Bevel (Classic) a Diffuse or Plastic +/// Does the effect take light: Shading on, or for the classic 3D effects a Diffuse or Plastic /// surface? fn lit(d: &Dialog) -> bool { - if d.str("__effect") == vectorcraft_effects::CLASSIC_EXTRUDE { - matches!(d.str("surface").as_str(), "diffuse" | "plastic") - } else { - d.bool("shade") - } + let id = d.str("__effect"); + if vectorcraft_effects::is_classic_three_d(&id) { matches!(d.str("surface").as_str(), "diffuse" | "plastic") } else { d.bool("shade") } } pub(crate) fn hint(d: &Dialog) -> &'static str { @@ -97,8 +94,9 @@ impl Geometry { let bounds = node.geometric_bounds()?; let xf = Xf::new(app.canvas_rect?, app.view()?); let options = super::revolve::light_options(d); - // Revolve turns about its axis; the others about the centre of the art's bounds. - let origin = if d.str("__effect") == REVOLVE { options.rotation_origin(bounds) } else { bounds.center() }; + // Both Revolves turn about their axis; the others about the centre of the art's bounds. + let id = d.str("__effect"); + let origin = if id == REVOLVE || id == CLASSIC_REVOLVE { options.rotation_origin(bounds) } else { bounds.center() }; let center = xf.to_screen(origin); if !center.x.is_finite() || !center.y.is_finite() || !xf.rect.contains(center) { return None; diff --git a/crates/ui-egui/src/dialogs/safe_mode.rs b/crates/ui-egui/src/dialogs/safe_mode.rs index 99ea560bb2..b26711c741 100644 --- a/crates/ui-egui/src/dialogs/safe_mode.rs +++ b/crates/ui-egui/src/dialogs/safe_mode.rs @@ -112,11 +112,16 @@ fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result Result { - let items: Vec = safe_mode::disabled() + let disabled = safe_mode::disabled(); + let items: Vec = disabled .iter() - .map(|i| { + .enumerate() + .filter(|(k, i)| i.id.is_none() || !disabled[..*k].iter().any(|e| e.id == i.id)) + .map(|(_, i)| { let mut v = i.to_json(); v["enable"] = json!(false); v diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 924f8c4078..64dc2fae8c 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -133,8 +133,8 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } /// `file.saveForWeb` with settings: write the files (`path`, else a picked file: the page with HTML -/// output, else the image); the web downloads them. The status bar shows the export's first -/// warning. +/// output, else the image); the web downloads them. The status bar shows the export's warnings as +/// [`io::report_saved`] shows a save's notes. pub(crate) fn save(app: &mut VectorcraftApp, mut p: Value) -> Result { // Bad settings never open a save panel. let s = app.session.web_settings(&p)?; @@ -170,7 +170,7 @@ pub(crate) fn save(app: &mut VectorcraftApp, mut p: Value) -> Result bool { r["warnings"].as_array().is_some_and(|w| !w.is_empty()) } @@ -183,8 +183,8 @@ pub(super) fn preview_name(stem: &str) -> &str { } /// `file.saveForWeb.browser`: the HTML page and its images in a new temporary folder, opened in the -/// default browser (desktop). When the export has warnings, the status bar shows the first in -/// place of "Opened …". +/// default browser (desktop). When the export has warnings, the status bar shows them as +/// [`io::report_saved`] shows a save's notes. pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result { if io::is_web(app) { return Err("Preview in Browser needs the desktop app (the web downloads files instead)".into()); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 3d0cb14421..5dfb886044 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -7,8 +7,13 @@ //! editable), `path`, `format`, and one field per option (agents set them with `ui.dialog.set`). //! Native and `.ai` files show their save options (VectorCraft Options after Save As): each //! artboard to a separate file, with `all` (true: every artboard) or `range`, Include Linked Files, -//! Embed ICC Profiles, Create PDF-Compatible File and Use Compression. A native file's Version is a -//! menu of the versions VectorCraft writes (`version`, named by the releases that read each). A +//! Embed ICC Profiles, Create PDF-Compatible File and Use Compression. EPS shows Use Artboards +//! (`useArtboards`, off by default: the bounding box fits the visible art) with the same `all` or +//! `range` under it, then the options Export's EPS Options shows: Preview, Overprints, Flattener +//! preset and PostScript are menus that write the option's value (`previewFormat: "tiffColor"`, +//! `overprints: "preserve"`, `flattenerPreset: "medium"` or a saved preset's name, `level: 3`). +//! A native file's Version is a menu of the versions VectorCraft writes +//! (`version`, named by the releases that read each). A //! `.ai` file's Version comes first: PDF-compatible, or legacy version 7 (`aiVersion: "7"`, a file //! per artboard), which takes only Transparent Images (`transparentImages`), Hidden Objects //! (`hiddenObjects`: a hidden layer, omitted or made visible), Text (`outlineText`: editable or @@ -18,7 +23,9 @@ use std::sync::OnceLock; use serde_json::{Map, Value, json}; +use vectorcraft_engine::cmd::FlattenOptions; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format, FormatOption, SAVE_FORMATS, SaveMode, TEMPLATE_FORMATS}; +use vectorcraft_eps::{Level, Overprint, Preview}; use super::{DialogResult, DialogSpec, form}; use crate::state::Dialog; @@ -76,50 +83,130 @@ fn separates(f: &Format) -> bool { f.options.iter().any(|o| o.name == "separateArtboards") } +/// The checkbox that `f`'s All or Range shows under: Save each artboard to a separate file, or +/// for EPS Use Artboards (off: the visible art's bounds). +fn board_switch(f: &Format) -> Option<&'static str> { + if separates(f) { + Some("separateArtboards") + } else if f.id == "eps" { + Some("useArtboards") + } else { + None + } +} + /// The options the dialog shows: arrays and objects are for agents, as is a native file's /// `precision`, and a page range replaces the single artboard choice; none for a format with its /// own dialog. A `.ait` template has no Version: Save as Template writes it PDF-compatible only. fn shown(f: &Format) -> impl Iterator { let range = f.options.iter().any(|o| o.name == "range"); - let separate = separates(f); + let switched = board_switch(f).is_some(); let options = if own_dialog(f) { &[][..] } else { f.options }; options.iter().filter(move |o| { !(matches!(o.ty, "array" | "object") || o.name == "precision" || (range && o.name == "artboard") - || (separate && o.name == "range") + || (switched && o.name == "range") || (matches!(f.id, "ai" | "ait") && o.name == "useArtboards") - // EPS Save keeps a page and the complete editing document; cropped and - // selected-only output belongs to Export, never this save dialog. - || (f.id == "eps" && matches!(o.name, "useArtboards" | "selectedOnly")) + // EPS Save writes all the artwork: selected-only output belongs to Export. + || (f.id == "eps" && o.name == "selectedOnly") || (f.id == "ait" && o.name == "aiVersion")) }) } -/// An option's label: the save options as the reference app's options dialog names them, the -/// others from their names. +/// An option's label: its written label, or for an option without one, its name split into words. fn label(o: &FormatOption) -> String { - match o.name { + written_label(o).unwrap_or_else(|| form::humanize(o.name)) +} + +/// The written label of option `o`, translated. +fn written_label(o: &FormatOption) -> Option { + Some(match o.name { "separateArtboards" => tl!("Save each artboard to a separate file").into(), - "includeLinked" => tl!("Include Linked Files").into(), + "useArtboards" => tl!("Use Artboards").into(), + "includeLinked" | "includeLinkedFiles" => tl!("Include Linked Files").into(), "embedProfiles" => tl!("Embed ICC Profiles").into(), "pdfCompatible" => tl!("Create PDF-Compatible File").into(), "compress" => tl!("Use Compression").into(), "editingData" => tl!("Include Editing Data for Other Apps").into(), - _ => form::humanize(o.name), - } + "version" | "aiVersion" => tl!("Version:").into(), + "transparentImages" => tl!("Transparent Images:").into(), + "hiddenObjects" => tl!("Hidden Objects:").into(), + "outlineText" => tl!("Text:").into(), + "preview" => tl!("Preview").into(), + "thumbnails" => tl!("Include Document Thumbnails").into(), + "previewFormat" => tl!("Preview:").into(), + "transparentPreview" => tl!("Transparent").into(), + "overprints" => tl!("Overprints:").into(), + "flattenerPreset" => tl!("Flattener preset:").into(), + "embedFonts" => tl!("Embed Fonts (for other applications)").into(), + "cmykPostScript" => tl!("Include CMYK PostScript in RGB Files").into(), + "compatibleGradients" => tl!("Compatible Gradient and Gradient Mesh Printing").into(), + "level" => tl!("PostScript:").into(), + _ => return None, + }) } -/// Every artboard (the All choice under Save each artboard to a separate file): `all` when set, -/// else no range given. +/// The values of an option that takes one of a fixed set, each with the name its menu shows, and +/// `at`, the entry the option's value picks as the save reads it (none when the save would reject +/// the value). The first `builtins` names are VectorCraft's own (translated where they are shown); +/// the others are names the user gave (saved flattener presets), shown as they are. +struct Choices { + values: Vec, + names: Vec, + builtins: usize, + at: Option, +} + +/// The choices of `f`'s option `o`, whose value is `value`, when it takes one of a fixed set of +/// values: EPS's preview format, overprints, PostScript level and flattener preset (the built-in +/// presets by id, then the saved ones by name). +fn choices(app: &VectorcraftApp, f: &Format, o: &FormatOption, value: &Value) -> Option { + if f.id != "eps" { + return None; + } + let text = value.as_str().map_or_else(|| value.to_string(), str::to_string); + let (pairs, builtins, at): (Vec<(Value, String)>, Option, Option) = match o.name { + "previewFormat" => ( + Preview::ALL.iter().map(|p| (json!(p.id()), p.label().to_string())).collect(), + None, + Preview::from_id(&text).and_then(|p| Preview::ALL.iter().position(|q| *q == p)), + ), + "overprints" => ( + Overprint::ALL.iter().map(|p| (json!(p.id()), p.label().to_string())).collect(), + None, + Overprint::from_id(&text).and_then(|p| Overprint::ALL.iter().position(|q| *q == p)), + ), + // The level is a number in the save options. + "level" => ( + Level::ALL.iter().filter_map(|l| Some((json!(l.id().parse::().ok()?), l.label().to_string()))).collect(), + None, + Level::from_id(&text).and_then(|l| Level::ALL.iter().position(|q| *q == l)), + ), + "flattenerPreset" => { + let presets = app.session.flattener_presets(); + let id = |name: &str| FlattenOptions::PRESETS.into_iter().find(|id| FlattenOptions::preset_label(id) == Some(name)); + let pairs = presets.iter().map(|p| (id(&p.name).map_or_else(|| json!(p.name), |id| json!(id)), p.name.clone())).collect(); + let at = app.session.flattener_preset(&text).and_then(|p| presets.iter().position(|q| q.name == p.name)); + (pairs, Some(FlattenOptions::builtin_presets().len()), at) + } + _ => return None, + }; + let builtins = builtins.unwrap_or(pairs.len()); + let (values, names): (Vec, Vec) = pairs.into_iter().unzip(); + Some(Choices { values, names, builtins, at }) +} + +/// Every artboard (the All choice under Save each artboard to a separate file or Use Artboards): +/// `all` when set, else no range given. fn all_artboards(d: &Dialog) -> bool { d.fields.get("all").and_then(Value::as_bool).unwrap_or_else(|| d.str("range").trim().is_empty()) } -/// All or Range, under Save each artboard to a separate file (enabled while it is on). -fn artboard_range(ui: &mut egui::Ui, d: &mut Dialog) { +/// All or Range, under the checkbox `switch` (enabled while it is on). +fn artboard_range(ui: &mut egui::Ui, d: &mut Dialog, switch: &str) { ui.label(""); - ui.add_enabled_ui(d.bool("separateArtboards"), |ui| { + ui.add_enabled_ui(d.bool(switch), |ui| { ui.horizontal(|ui| { ui.add_space(22.0); let mut all = all_artboards(d); @@ -167,9 +254,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { // Version first; the legacy version takes only its own options. let legacy = legacy_ai(d); let mut rows: Vec<&FormatOption> = shown(f).filter(|o| LEGACY_ONLY.contains(&o.name) == legacy || o.name == "aiVersion").collect(); - rows.sort_by_key(|o| o.name != "aiVersion"); + // EPS's PostScript level comes last, as in Export's EPS Options. + rows.sort_by_key(|o| (o.name != "aiVersion", f.id == "eps" && o.name == "level")); for o in rows { - option_row(app, ui, d, o); + option_row(app, ui, d, f, o); } }); if legacy_ai(d) && app.session.active().is_some_and(|st| st.doc.artboards.len() > 1) { @@ -330,8 +418,9 @@ fn artboard_picker(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) } } -/// One option: a checkbox, an artboard menu, a version menu, a number or a text field. -fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &FormatOption) { +/// One option of format `f`: a checkbox, an artboard menu, a version menu, a menu of its +/// [`choices`], a number or a text field. +fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, f: &Format, o: &FormatOption) { let t = Tokens::get(ui.ctx()); let label = label(o); let value = d.fields.get(o.name).cloned().unwrap_or(Value::Null); @@ -383,6 +472,40 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma ui.end_row(); return; } + if let Some(c) = choices(app, f, o, &value) { + ui.label(egui::RichText::new(&label).color(t.text_dim)).on_hover_text(o.description); + // A value none of them names shows as it is. + let current = c.at.and_then(|i| c.names.get(i)).cloned().unwrap_or_else(|| value.as_str().map_or_else(|| value.to_string(), str::to_string)); + let names: Vec<&str> = c.names.iter().map(String::as_str).collect(); + if let Some(i) = super::mixed_dropdown(ui, ("save-option", o.name), ¤t, &names, 254.0, |k| k < c.builtins) { + choose(d, o, &c, i); + } + ui.end_row(); + return; + } + if f.id == "eps" && o.name == "transparentPreview" { + // Only the color preview can keep transparency. + ui.label(""); + let color = Preview::from_id(&d.str("previewFormat")) == Some(Preview::TiffColor); + let transparent = value.as_bool().unwrap_or(true); + ui.horizontal(|ui| { + for (name, on) in [(tl!("Transparent"), true), (tl!("Opaque"), false)] { + if widgets::radio(ui, name, color && transparent == on, color) { + d.fields.insert(o.name.into(), json!(on)); + } + ui.add_space(12.0); + } + }); + ui.end_row(); + return; + } + if f.id == "eps" && o.name == "embedFonts" { + // Type is written as glyph outlines, which need no fonts. + ui.label(""); + widgets::check_tip(ui, &label, true, false, o.description); + ui.end_row(); + return; + } if o.ty == "boolean" { ui.label(""); let on = value.as_bool().unwrap_or(false); @@ -392,8 +515,8 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma d.fields.insert(o.name.into(), json!(!on)); } ui.end_row(); - if o.name == "separateArtboards" { - artboard_range(ui, d); + if matches!(o.name, "separateArtboards" | "useArtboards") { + artboard_range(ui, d, o.name); } return; } @@ -421,6 +544,13 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma ui.end_row(); } +/// Option `o` set to the value of entry `i` of its menu `c`. +fn choose(d: &mut Dialog, o: &FormatOption, c: &Choices, i: usize) { + if let Some(v) = c.values.get(i) { + d.fields.insert(o.name.into(), v.clone()); + } +} + /// The native versions VectorCraft writes, newest first, each with the first release that reads /// it (the format version each release tag writes: 2 in 0.1, 3 from 0.2, 4 from 0.8). const NATIVE_VERSIONS: [(u32, &str); 4] = [(4, "0.8"), (3, "0.2"), (2, "0.1"), (1, "0.1")]; @@ -505,8 +635,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { if !boards.iter().all(|b| *b) { options.insert("range".into(), json!(super::export_for_screens::range_text(&boards))); } - } else if separates(f) { - if !d.bool("separateArtboards") || all_artboards(d) { + } else if let Some(switch) = board_switch(f) { + if switch == "useArtboards" { + // All or Range alone names the artboards: an artboard remembered from an earlier + // save would otherwise turn Use Artboards on, or narrow All to itself. + options.remove("artboard"); + options.remove("artboards"); + options.insert(switch.into(), json!(d.bool(switch))); + } + if !d.bool(switch) || all_artboards(d) { options.remove("range"); } else { // A bad range keeps the dialog open. diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 9590799687..968d79568c 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -346,19 +346,213 @@ fn save_as_pdf_asks_with_the_save_pdf_dialog_and_remembers_its_options() { assert_eq!(dialog(&app).str("__save"), "file.saveCopy"); } +/// The `%%BoundingBox` line of an EPS file. +fn bounding_box(eps: &[u8]) -> String { + let ps = std::str::from_utf8(vectorcraft_eps::sections(eps).unwrap().0).unwrap(); + ps.lines().find(|l| l.starts_with("%%BoundingBox:")).expect("a bounding box").to_string() +} + #[test] -fn eps_save_as_keeps_page_options_and_writes_eps_without_export_only_switches() { +fn eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard() { let (mut app, written, _) = desktop("art.eps"); app.run("file.saveAs", json!({})).unwrap(); let names: Vec<_> = shown(fileio::format("eps").unwrap()).map(|option| option.name).collect(); - assert!(!names.contains(&"useArtboards") && !names.contains(&"selectedOnly")); + assert!(names.contains(&"useArtboards") && !names.contains(&"selectedOnly") && !names.contains(&"range"), "{names:?}"); assert!(names.contains(&"previewFormat")); + // EPS alone gains the row: the other save formats keep their own checkbox or none. + for id in SAVE_FORMATS.iter().chain(TEMPLATE_FORMATS).filter(|id| **id != "eps") { + let f = fileio::format(id).unwrap(); + assert!(!shown(f).any(|o| o.name == "useArtboards") && board_switch(f) != Some("useArtboards"), "{id}"); + } + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(text.contains("Use Artboards") && text.contains("All") && text.contains("Range:"), "{text}"); + assert!(!dialog(&app).bool("useArtboards"), "Use Artboards starts off"); super::super::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); - let saved = written.borrow(); - assert_eq!(saved[0].0, "art.eps"); - assert!(vectorcraft_eps::native(&saved[0].1).is_some()); + { + let saved = written.borrow(); + assert_eq!(saved[0].0, "art.eps"); + assert!(vectorcraft_eps::native(&saved[0].1).is_some()); + // The box Export writes of the visible art, not the artboard. + let exported = app.session.execute("document.export", &json!({"format": "eps"})).unwrap(); + let exported = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap(); + assert_eq!(bounding_box(&saved[0].1), bounding_box(&exported)); + assert_ne!(bounding_box(&saved[0].1), "%%BoundingBox: 0 0 100 80"); + } assert_eq!(app.session.active().unwrap().format, "eps"); + // Checked, the artboard is the page, and an artboard remembered from an earlier save doesn't + // narrow All. + app.run("file.saveAs", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("useArtboards".into(), json!(true)); + d.fields.insert("artboard".into(), json!(3)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + { + let saved = written.borrow(); + assert_eq!(saved.len(), 2, "one artboard: one file"); + assert_eq!(bounding_box(&saved[1].1), "%%BoundingBox: 0 0 100 80"); + } + // A save that named an artboard without Use Artboards (as document.save {artboard} does) had + // it on: the dialog shows it on, on that artboard, and OK writes the artboard again. + let st = app.session.active_mut().unwrap(); + st.save_options.remove("useArtboards"); + st.save_options.insert("artboard".into(), json!(0)); + app.run("file.saveAs", json!({})).unwrap(); + assert!(dialog(&app).bool("useArtboards")); + assert_eq!(dialog(&app).str("range"), "1"); + super::super::confirm(&mut app).unwrap(); + let saved = written.borrow(); + assert_eq!(saved.len(), 3); + assert_eq!(bounding_box(&saved[2].1), "%%BoundingBox: 0 0 100 80"); +} + +/// Save As › EPS shows the options of Export's EPS Options: Preview, Overprints, Flattener preset +/// and PostScript as menus of readable names (not fields holding `tiffColor`, `preserve` and +/// `medium`), the checkboxes under written labels, and the PostScript level last. +#[test] +fn eps_save_options_are_menus_with_readable_names() { + let (mut app, _, _) = desktop("art.eps"); + app.run("file.saveAs", json!({})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + let lines: Vec<&str> = text.lines().collect(); + for shown in [ + "Preview:", + "TIFF (8-bit Color)", + "Transparent", + "Opaque", + "Overprints:", + "Preserve", + "Flattener preset:", + "Medium Resolution", + "Embed Fonts (for other applications)", + "Include Linked Files", + "Include Document Thumbnails", + "Include CMYK PostScript in RGB Files", + "Compatible Gradient and Gradient Mesh Printing", + "PostScript:", + "Language Level 3", + ] { + assert!(lines.contains(&shown), "{shown:?} in {text}"); + } + for id in ["tiffColor", "preserve", "medium", "Cmyk Post Script", "Preview Format:", "Level:", "Thumbnails"] { + assert!(!lines.contains(&id), "{id:?} in {text}"); + } + let at = |s: &str| lines.iter().position(|l| *l == s).unwrap(); + assert!(at("PostScript:") > at("Compatible Gradient and Gradient Mesh Printing"), "{text}"); +} + +/// Every option the save options dialog shows, in every format it serves, has a written label: +/// none is painted as its name split into words. +#[test] +fn save_options_have_written_labels() { + // The web's Save As and Save as Template dialogs show the options of every format they pick. + let formats = SAVE_FORMATS.iter().map(|id| (*id, "file.saveAs")).chain(TEMPLATE_FORMATS.iter().map(|id| (*id, "file.saveAsTemplate"))); + for (id, command) in formats { + let (mut app, _) = web(); + app.run(command, json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + switch_format(&mut app, &mut d, id); + app.ui.dialog = Some(d); + assert_eq!((dialog(&app).kind.as_str(), dialog(&app).str("format").as_str()), (KIND, id)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + let f = fileio::format(id).unwrap(); + for o in shown(f) { + let written = written_label(o); + assert!(written.is_some(), "{id}: {} has no written label", o.name); + let split = form::humanize(o.name); + let split = split.trim_end_matches(':'); + assert!( + written.as_deref().map(|w| w.trim_end_matches(':')) == Some(split) || !text.lines().any(|l| l == split), + "{id}: {split:?} in {text}" + ); + } + } +} + +/// A pick from an EPS menu saves the option's value: the id, the level as a number, a saved +/// flattener preset by its name. The file is written with them. +#[test] +fn picking_eps_menu_items_saves_their_values() { + let (mut app, written, _) = desktop("art.eps"); + app.session.prefs.flattener_presets.push(vectorcraft_engine::cmd::FlattenerPreset { + name: "Mine".into(), + options: vectorcraft_engine::cmd::FlattenOptions::preset("low").unwrap(), + }); + app.run("file.saveAs", json!({})).unwrap(); + let f = fileio::format("eps").unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + for (name, pick, value) in [ + ("previewFormat", "None", json!("none")), + ("overprints", "Discard", json!("discard")), + ("flattenerPreset", "Mine", json!("Mine")), + ("level", "Language Level 2", json!(2)), + ] { + let o = f.options.iter().find(|o| o.name == name).unwrap(); + let c = choices(&app, f, o, &Value::Null).unwrap_or_else(|| panic!("{name} is a menu")); + let i = c.names.iter().position(|n| n == pick).unwrap_or_else(|| panic!("{pick} in {name}: {:?}", c.names)); + choose(&mut d, o, &c, i); + assert_eq!(d.fields[name], value, "{name}"); + assert_eq!(choices(&app, f, o, &value).unwrap().at, Some(i), "{name}: the menu shows the pick"); + } + // The built-in presets come first, by id. A value picks the entry the save reads it as: a + // preset by id or name in any case, a level by its digits, a preview or overprint by id only. + let at = |name: &str, value: Value| { + let o = f.options.iter().find(|o| o.name == name).unwrap(); + choices(&app, f, o, &value).unwrap().at + }; + let o = f.options.iter().find(|o| o.name == "flattenerPreset").unwrap(); + let c = choices(&app, f, o, &Value::Null).unwrap(); + assert_eq!(c.values, [json!("high"), json!("medium"), json!("low"), json!("Mine")]); + assert_eq!((c.builtins, c.at), (3, None)); + assert_eq!( + (at("flattenerPreset", json!("MEDIUM RESOLUTION")), at("flattenerPreset", json!("mine")), at("flattenerPreset", json!("Other"))), + (Some(1), Some(3), None) + ); + assert_eq!((at("level", json!("level2")), at("level", json!(3)), at("level", json!(4))), (Some(0), Some(1), None)); + assert_eq!((at("previewFormat", json!("TIFFBW")), at("previewFormat", json!("TIFF (8-bit Color)"))), (Some(1), None)); + assert_eq!((at("overprints", json!("Discard")), at("overprints", json!("keep"))), (Some(1), None)); + app.ui.dialog = Some(d); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "saved: {}", app.ui.status); + let saved = &app.session.active().unwrap().save_options; + for (name, value) in [("previewFormat", json!("none")), ("overprints", json!("discard")), ("flattenerPreset", json!("Mine")), ("level", json!(2))] + { + assert_eq!(saved[name], value, "{name}"); + } + let bytes = written.borrow()[0].1.clone(); + let (ps, preview) = vectorcraft_eps::sections(&bytes).unwrap(); + assert!(preview.is_none(), "no preview"); + assert!(String::from_utf8_lossy(ps).contains("%%LanguageLevel: 2")); +} + +/// Save As › EPS: Transparent and Opaque apply to the color TIFF preview only, and are disabled +/// with any other preview. Embed Fonts shows checked and disabled. A flattener preset that no +/// entry of the menu names shows as it is. +#[test] +fn eps_save_transparency_follows_the_color_preview() { + use crate::widgets::accessibility_tests::{named, role_and_state, tree}; + use egui::accesskit::Toggled; + let (mut app, _, _) = desktop("art.eps"); + app.run("file.saveAs", json!({})).unwrap(); + let set = |app: &mut VectorcraftApp, k: &str, v: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + }; + set(&mut app, "previewFormat", json!("tiffColor")); + set(&mut app, "transparentPreview", json!(false)); + let t = tree(|ui| super::super::show(&mut app, ui.ctx())); + assert!(!named(&t, "Transparent").is_disabled() && !named(&t, "Opaque").is_disabled()); + assert_eq!((role_and_state(&t, "Transparent").1, role_and_state(&t, "Opaque").1), (Some(Toggled::False), Some(Toggled::True))); + let fonts = named(&t, "Embed Fonts (for other applications)"); + assert_eq!((fonts.is_disabled(), fonts.toggled()), (true, Some(Toggled::True))); + for preview in ["none", "tiffBw"] { + set(&mut app, "previewFormat", json!(preview)); + let t = tree(|ui| super::super::show(&mut app, ui.ctx())); + assert!(named(&t, "Transparent").is_disabled() && named(&t, "Opaque").is_disabled(), "{preview}"); + } + set(&mut app, "flattenerPreset", json!("Gone")); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(text.lines().any(|l| l == "Gone"), "{text}"); } /// #4931: a native file's Version is a menu of the versions VectorCraft writes, the current one diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index ee68105a62..e2f21c80cf 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -478,6 +478,11 @@ fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) { let layers = standard.allows_layers() && choice::(d, "compatibility").unwrap_or_default().has_layers(); flag(ui, d, "createLayers", tl!("Create PDF layers from layers and sublayers"), layers); flag(ui, d, "includeNonPrinting", tl!("Include non-printing layers"), true); + // PDF/X files and PDF 1.3 and 1.4 files always write long pages in points, and PDF/A files + // keep the `UserUnit`. + let compatibility = choice::(d, "compatibility").unwrap_or_default(); + let scales = standard == Standard::None && !matches!(compatibility, Compatibility::Pdf13 | Compatibility::Pdf14); + flag(ui, d, "longPagesInPoints", tl!("Write pages longer than 200 in at full size in points"), scales); if editor { heading(ui, tl!("Description")); if let Some(text) = widgets::text_field_named(ui, "pdf-preset-description", Some(tl!("Description")), Some(&d.str("description")), 460.0, 3) { diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 7bb471a76e..a6f4e9884c 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -323,6 +323,39 @@ fn choosing_a_pdfx_standard_sets_its_version_and_writes_the_standard() { assert_eq!((get(d, "compatibility"), get(d, "createLayers")), (&json!("1.6"), &json!(true))); } +/// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at +/// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and +/// PDF/A files keep the `UserUnit`. +#[test] +fn the_long_pages_in_points_check_box_is_disabled_with_a_standard() { + const LABEL: &str = "Write pages longer than 200 in at full size in points"; + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp| { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + for s in Standard::ALL.iter().copied() { + for c in Compatibility::ALL.iter().copied().filter(|c| s.allows(*c)) { + set_field(&mut app, "standard", json!(s.id())); + set_field(&mut app, "compatibility", json!(c.id())); + frame(&mut app); + let out = frame(&mut app); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().find(|(_, n)| n.label() == Some(LABEL) && n.role() == egui::accesskit::Role::CheckBox); + let disabled = node.unwrap_or_else(|| panic!("no check box named {LABEL:?}")).1.is_disabled(); + let enabled = s == Standard::None && !matches!(c, Compatibility::Pdf13 | Compatibility::Pdf14); + assert_eq!(disabled, !enabled, "{} {}", s.label(), c.label()); + } + } +} + #[test] fn create_layers_writes_pdf_layers() { let (mut app, written, _) = app(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 2ad8bdf213..a7d62b6daf 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -32,7 +32,7 @@ fn open(app: &mut VectorcraftApp, kind: &str, fields: serde_json::Value) { } fn objects(app: &VectorcraftApp) -> usize { - app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum() + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.iter().filter(|c| !c.is_ruler_guide()).count())).sum() } #[test] @@ -570,11 +570,11 @@ fn split_into_grid_opens_at_the_selections_size_and_previews() { ]); frame(&mut app, Default::default()); // The preview: 2 × 3 cells and the guides along their edges, not yet an undo step. - assert_eq!((objects(&app), app.session.doc().unwrap().doc.guides.len()), (6, 10)); + assert_eq!((objects(&app), app.session.doc().unwrap().doc.ruler_guides().len()), (6, 10)); assert!(app.session.in_interaction()); confirm(&mut app).unwrap(); let st = app.session.doc().unwrap(); - assert_eq!((objects(&app), st.doc.guides.len(), st.history.undo.len()), (6, 10, undo + 1)); + assert_eq!((objects(&app), st.doc.ruler_guides().len(), st.history.undo.len()), (6, 10, undo + 1)); assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); // Cancel rolls a preview back. app.run("select.all", json!({})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/tests_dxf.rs b/crates/ui-egui/src/dialogs/tests_dxf.rs index 22429b1649..775562fa8f 100644 --- a/crates/ui-egui/src/dialogs/tests_dxf.rs +++ b/crates/ui-egui/src/dialogs/tests_dxf.rs @@ -50,13 +50,15 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { frame(&mut app); let d = app.ui.dialog.as_ref().unwrap(); let fields = |d: &crate::state::Dialog| { - ["dxfPreset", "version", "unit", "scale", "colors", "preserve", "alterPaths", "outlineText"].map(|k| d.str(k)).join(" ") + ["dxfPreset", "version", "unit", "scale", "colors", "preserve", "alterPaths", "outlineText", "includeImages", "includeHatches"] + .map(|k| d.str(k)) + .join(" ") }; - assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true"); + assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true false false"); // Any change to a field the preset sets shows Custom, and keeps the other fields. set(&mut app, "colors", json!("true")); frame(&mut app); - assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2000 Millimeters 1.0 true editability false true"); + assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2000 Millimeters 1.0 true editability false true false false"); set(&mut app, "colors", json!("256")); frame(&mut app); assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "cnc", "matching every field again"); @@ -70,12 +72,12 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "cnc"); set(&mut app, "dxfPreset", json!("custom")); frame(&mut app); - assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2018 Millimeters 1.0 true appearance false false"); + assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2018 Millimeters 1.0 true appearance false false true true"); // A preset the command gives sets the fields it does not give. app.ui.dialog = None; app.run("ui.dxfOptionsDialog", json!({"dxfPreset": "cnc", "unit": "Inches"})).unwrap(); let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(fields(d), "custom 2000 Inches 1.0 256 editability false true"); + assert_eq!(fields(d), "custom 2000 Inches 1.0 256 editability false true false false"); // A preset set and confirmed without drawing (the control channel) sets its fields too. set(&mut app, "dxfPreset", json!("cnc")); confirm(&mut app).unwrap(); @@ -84,7 +86,7 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { app.run("ui.dxfOptionsDialog", json!({"dxfPreset": "custom"})).unwrap(); let d = app.ui.dialog.as_mut().unwrap(); set_field(d, "dxfPreset".into(), json!("cnc")); - assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true"); + assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true false false"); set_field(d, "unit".into(), json!("Inches")); assert_eq!(d.str("dxfPreset"), "custom"); // Setting the preset again sets its fields again. @@ -94,12 +96,51 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { // Setting Custom while Custom is shown still puts back the defaults. let mut reset = d.clone(); set_field(&mut reset, "dxfPreset".into(), json!("custom")); - assert_eq!(fields(&reset), "custom 2018 Millimeters 1.0 true appearance false false"); + assert_eq!(fields(&reset), "custom 2018 Millimeters 1.0 true appearance false false true true"); confirm(&mut app).unwrap(); let remembered = ["dxfPreset", "version", "unit"].map(|k| app.ui.dxf_options[k].as_str()); assert_eq!(remembered, [Some("custom"), Some("2000"), Some("Inches")]); } +#[test] +fn include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom() { + let (mut app, written) = app(1); + let shown = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().unwrap(); + (d.str("dxfPreset"), d.bool("includeImages"), d.bool("includeHatches")) + }; + app.run("ui.dxfOptionsDialog", json!({"path": "/out/a.dxf"})).unwrap(); + frame(&mut app); + assert_eq!(shown(&app), ("custom".into(), true, true)); + confirm(&mut app).unwrap(); + assert!(text(&written.borrow()[0].1).contains("\nHATCH\n"), "Custom keeps the fill's hatch"); + app.run("ui.dxfOptionsDialog", json!({"path": "/out/b.dxf"})).unwrap(); + set(&mut app, "dxfPreset", json!("cnc")); + frame(&mut app); + assert_eq!(shown(&app), ("cnc".into(), false, false)); + // Either checkbox changed shows Custom; both back as the preset sets them show CNC / CAM. + set(&mut app, "includeHatches", json!(true)); + frame(&mut app); + assert_eq!(shown(&app), ("custom".into(), false, true)); + set(&mut app, "includeHatches", json!(false)); + set(&mut app, "includeImages", json!(true)); + frame(&mut app); + assert_eq!(shown(&app), ("custom".into(), true, false)); + set(&mut app, "includeImages", json!(false)); + frame(&mut app); + assert_eq!(shown(&app).0, "cnc"); + confirm(&mut app).unwrap(); + assert!(!text(&written.borrow()[1].1).contains("\nHATCH\n"), "CNC / CAM writes the fill's outline alone"); + let remembered = ["includeImages", "includeHatches"].map(|k| app.ui.dxf_options[k].as_bool()); + assert_eq!(remembered, [Some(false), Some(false)]); + // The next DXF Options start from them, and Custom turns both back on. + crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({})); + assert_eq!(shown(&app), ("cnc".into(), false, false)); + set(&mut app, "dxfPreset", json!("custom")); + frame(&mut app); + assert_eq!(shown(&app), ("custom".into(), true, true)); +} + #[test] fn bad_dxf_options_keep_the_dialog_open() { let (mut app, written) = app(1); diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 891fb586be..93bb5dec75 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -180,6 +180,15 @@ fn a_bad_range_keeps_export_as_open() { assert!(written.borrow().is_empty()); } +/// An emptied Range field shows an example of the artboard numbers it takes, as Save As's does. +#[test] +fn an_empty_export_as_range_shows_an_example() { + let (mut app, _) = app(2); + app.run("file.exportAs", json!({"useArtboards": true, "range": ""})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.lines().any(|l| l == "1-3, 5"), "{text}"); +} + #[test] fn svg_continues_in_svg_options_and_pdf_art_is_written_directly() { let (mut app, written) = app(2); diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs new file mode 100644 index 0000000000..238a254cfb --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -0,0 +1,28 @@ +//! Export As → HP-GL, drawn headlessly: listed with the other formats, written straight away (no +//! options dialog), one plot per artboard with Use Artboards. + +use serde_json::json; + +use super::tests_export::{app, frame, kind, names, set}; +use super::*; + +#[test] +fn export_as_lists_hpgl_and_writes_plots() { + let (mut app, written) = app(2); + app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); + assert_eq!(kind(&app), Some("exportAs")); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "hpgl"); + frame(&mut app); + let r = confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "no options dialog follows"); + assert_eq!(r["path"], "/out/Untitled-1.plt"); + assert!(written.borrow()[0].1.starts_with(b"IN;")); + assert!(written.borrow()[0].1.ends_with(b"PU;SP0;")); + // One plot per artboard. + app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); + set(&mut app, "useArtboards", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + let n = names(&written); + assert_eq!(&n[1..], ["/out/Untitled-1-Artboard-1.plt", "/out/Untitled-1-Artboard-2.plt"]); +} diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 140623f209..97e2b16ee7 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -508,6 +508,35 @@ fn the_status_bar_says_when_an_image_could_not_be_decoded() { let _ = std::fs::remove_dir_all(dir); } +/// An export into a folder with several notes, from Export for Screens and from the Asset Export +/// panel: the status bar names the first, counts them, and keeps every one of them for its hover. +#[test] +fn an_export_into_a_folder_keeps_every_note_for_the_hover() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let dir = temp_folder("notes"); + let folder = dir.to_string_lossy().replace('\\', "/"); + let rows = json!([{"format": "png", "scale": "1x", "suffix": ""}]); + let (mut app, _) = app(1, false); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({"at": [10, 10]})); + app.run("text.create", json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + let r = app.run("file.exportForScreens", json!({"folder": folder, "formats": rows})).unwrap(); + let notes = crate::io::notes_of(&r); + assert_eq!(notes.len(), 2, "{r}"); + assert!(app.ui.status.starts_with(&format!("Saved {folder} with 2 notes: {}", notes[0])), "{}", app.ui.status); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes))); + app.ui.status_notes = None; + app.run("select.all", json!({})).unwrap(); + app.run("assets.add", json!({"multiple": false})).unwrap(); + let r = crate::io::export_files(&mut app, "assets.export", json!({"folder": folder, "formats": rows})).unwrap(); + let notes = crate::io::notes_of(&r); + assert_eq!(notes.len(), 2, "{r}"); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes)), "assets.export"); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_preset_export_reopens_on_its_rows() { let (mut app, _) = app(1, true); diff --git a/crates/ui-egui/src/dialogs/tests_warp.rs b/crates/ui-egui/src/dialogs/tests_warp.rs index e7cbfcc5b7..21d3e8e1a4 100644 --- a/crates/ui-egui/src/dialogs/tests_warp.rs +++ b/crates/ui-egui/src/dialogs/tests_warp.rs @@ -616,3 +616,33 @@ fn warp_options_style_keyboard_enter_does_not_accept_dialog() { assert_eq!(app.session.doc().unwrap().doc, moved); } } + +/// Warp Options editing the Warps of two objects, one new and one saved without a map version, +/// changes the Bend of both and keeps each one's own `version`. +#[test] +fn warp_options_edit_keeps_each_targets_map_version() { + let (mut app, first) = app(); + app.run("effect.apply", json!({"effect": "warp.arc"})).unwrap(); + let second = NodeId(app.run("shape.rectangle", json!({"x": 230, "y": 60, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap()); + app.run("effect.apply", json!({"effect": "warp.arc"})).unwrap(); + // As a file saved before the version existed gives it. + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + if let Some(Value::Object(p)) = doc.node_mut(second).and_then(|n| n.appearance.effects.first_mut()).map(|e| &mut e.params) { + p.remove("version"); + } + app.run("select.set", json!({"ids": [first.0, second.0]})).unwrap(); + app.run("effect.dialog", json!({"effect": "warp.arc"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, effect::EXISTS); + let ctx = context(); + settle(&mut app, &ctx); + click_text(&mut app, &ctx, "Edit"); + settle(&mut app, &ctx); + make_warp_edit(&mut app, &ctx, "bend"); + click_text(&mut app, &ctx, "OK"); + assert!(app.ui.dialog.is_none()); + let doc = app.session.doc().unwrap().doc.clone(); + let params = |id: NodeId| doc.node(id).unwrap().appearance.effects[0].params.clone(); + assert_eq!((¶ms(first)["bend"], ¶ms(first)["version"]), (&json!(25.0), &json!(vectorcraft_doc::live::WARP_NET))); + assert_eq!(params(second)["bend"], json!(25.0)); + assert!(params(second).get("version").is_none(), "{:?}", params(second)); +} diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 06d034fce4..a3857c914a 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -1,11 +1,12 @@ -//! Extrude & Bevel (Classic)'s own controls in the compact 3D dialog: the extrude and bevel options -//! on the Object tab, and the surface with its lights, highlight, blend steps and shading color on -//! the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D effect -//! shares. +//! The own controls of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) in the +//! compact 3D dialog: the extrude and bevel options, or the revolve options, on the Object tab +//! (Rotate (Classic) has none), and the surface with its lights, highlight, blend steps and shading +//! color on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D +//! effect shares. use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_effects::CLASSIC_EXTRUDE; +use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE}; use super::revolve::{c3, choice, heading, label, light_list, light_record, number, reset_dot, selected_light, store_selected, toggle}; use crate::state::Dialog; @@ -25,10 +26,28 @@ pub(super) fn object_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { }); } +/// Revolve (Classic)'s angle, cap and offset, and the edge of the profile's bounds the axis is at. +pub(super) fn revolve_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { + heading(ui, tl!("Object")); + number(ui, d, "angle", tl!("Angle"), (0.0, 360.0), "°", 1, None); + choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]); + number(ui, d, "offset", tl!("Offset"), (0.0, 1000.0), "", 1, Some(unit)); + let sides: Vec<(Value, &str)> = super::effect::own_choices(CLASSIC_REVOLVE, "edge", false) + .unwrap_or_default() + .into_iter() + .map(|(label, value)| (json!(value), label)) + .collect(); + choice(ui, d, "edge", tl!("Axis side"), &sides); +} + /// The surface, then for Diffuse and Plastic the lights, Ambient Light, the highlight (Plastic -/// only), Blend Steps and Shading Color; Draw Hidden Faces last. +/// only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps and Shading Color; +/// Draw Hidden Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and +/// Rotate (Classic)'s plane is seen from either side). pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) { - choice(ui, d, "surface", tl!("Surface"), &options("surface")); + let id = d.str("__effect"); + let effect = if id == CLASSIC_ROTATE { CLASSIC_ROTATE } else { CLASSIC_EXTRUDE }; + choice(ui, d, "surface", tl!("Surface"), &options_of(effect, "surface")); let surface = d.str("surface"); ui.add_enabled_ui(surface == "diffuse" || surface == "plastic", |ui| { light_list(ui, d); @@ -42,22 +61,31 @@ pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) { store_selected(d, &selected); } number(ui, d, "ambient", tl!("Ambient Light"), (0.0, 100.0), "%", 1, None); - ui.add_enabled_ui(surface == "plastic", |ui| { - number(ui, d, "highlightIntensity", tl!("Highlight Intensity"), (0.0, 100.0), "%", 1, None); - number(ui, d, "highlightSize", tl!("Highlight Size"), (0.0, 100.0), "%", 1, None); - }); + if id != CLASSIC_ROTATE { + ui.add_enabled_ui(surface == "plastic", |ui| { + number(ui, d, "highlightIntensity", tl!("Highlight Intensity"), (0.0, 100.0), "%", 1, None); + number(ui, d, "highlightSize", tl!("Highlight Size"), (0.0, 100.0), "%", 1, None); + }); + } number(ui, d, "blendSteps", tl!("Blend Steps"), (1.0, 256.0), "", 0, None); - choice(ui, d, "shadingColor", tl!("Shading Color"), &options("shadingColor")); + choice(ui, d, "shadingColor", tl!("Shading Color"), &options_of(effect, "shadingColor")); if d.str("shadingColor") == "custom" { shading_custom(ui, d); } }); - toggle(ui, d, "drawHiddenFaces", tl!("Draw Hidden Faces"), false); + if id == CLASSIC_EXTRUDE { + toggle(ui, d, "drawHiddenFaces", tl!("Draw Hidden Faces"), false); + } } /// The values of Extrude & Bevel (Classic)'s `key` as the dropdowns list them, (value, label). fn options(key: &str) -> Vec<(Value, &'static str)> { - super::effect::own_choices(CLASSIC_EXTRUDE, key, false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect() + options_of(CLASSIC_EXTRUDE, key) +} + +/// The values of classic 3D effect `effect`'s `key` as the dropdowns list them, (value, label). +fn options_of(effect: &str, key: &str) -> Vec<(Value, &'static str)> { + super::effect::own_choices(effect, key, false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect() } /// The custom shading color: a color button, its hex value and its reset dot. diff --git a/crates/ui-egui/src/dialogs/warp_effect.rs b/crates/ui-egui/src/dialogs/warp_effect.rs index ff530fbdf2..e8ef2bb6b7 100644 --- a/crates/ui-egui/src/dialogs/warp_effect.rs +++ b/crates/ui-egui/src/dialogs/warp_effect.rs @@ -1,7 +1,7 @@ //! Effect > Warp controls. The style remains an effect ID; Envelope Warp has a different schema. use egui::{Pos2, Rect, Stroke, vec2}; use serde_json::{Map, Value, json}; -use vectorcraft_effects::{WARP_STYLES, WarpStyle, warp_point}; +use vectorcraft_effects::{WARP_STYLES, WarpNet, WarpStyle}; use super::form; use crate::state::Dialog; @@ -38,6 +38,8 @@ fn shown(label: &str) -> String { fn style_preview(ui: &mut egui::Ui, suffix: &str) { let (rect, _) = ui.allocate_exact_size(vec2(30.0, 22.0), egui::Sense::hover()); let Some(style) = WarpStyle::from_id(suffix) else { return }; + // The map new warps take, on a box 0.55 times as high as it is wide. + let net = WarpNet::new(style, 0.45, 0.0, 0.0, 2.0, 1.1, false); let mut lines = vec![]; let mut bounds = Rect::NOTHING; for vertical in [false, true] { @@ -46,8 +48,8 @@ fn style_preview(ui: &mut egui::Ui, suffix: &str) { .map(|i| { let along = -1.0 + f64::from(i) / 8.0; let (x, y) = if vertical { (fixed, along) } else { (along, fixed) }; - let (x, y) = warp_point(style, 0.45, 0.0, 0.0, 0.55, x, y); - let p = Pos2::new(x as f32, y as f32); + let q = net.at((x + 1.0) / 2.0, (y + 1.0) / 2.0); + let p = Pos2::new(q.x as f32, q.y as f32); bounds.extend_with(p); p }) diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index f8b686cca2..4c5b972f12 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -247,6 +247,8 @@ fn new_width_point_profile_and_compound_target() { assert!(d.fields.get("index").is_none_or(Value::is_null)); let actual_t = d.f64("t", -1.0); assert!((actual_t - 0.25).abs() < 1e-6, "compound={compound} pointer={quarter:?} actual_t={actual_t} want=0.25"); + // The two-point profile is linear: at a quarter its sides are 1.25 and 0.75 of + // 1..2 and 0.5..1.5, on a 10pt stroke (5pt half). assert!((d.f64("side1", 0.0) - 6.25).abs() < 1e-6); assert!((d.f64("side2", 0.0) - 3.75).abs() < 1e-6); assert!(!d.bool("linked")); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 2d6fede3bf..6f84623087 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -416,7 +416,7 @@ fn heading(id: &str) -> &'static str { } /// The headings in order, each with its tools in the toolbar's order. -fn sections() -> &'static [(&'static str, Vec<&'static ToolInfo>)] { +pub(crate) fn sections() -> &'static [(&'static str, Vec<&'static ToolInfo>)] { static SECTIONS: OnceLock)>> = OnceLock::new(); SECTIONS.get_or_init(|| { let mut out: Vec<(&'static str, Vec<&'static ToolInfo>)> = crate::toolbar::BASIC.iter().map(|(cat, _)| (*cat, vec![])).collect(); diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index b467f05552..e47561094e 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -381,7 +381,7 @@ fn a_new_toolbar_fills_from_the_drawer_beside_it() { frame(&mut app, &ctx, 0.1, vec![]); let area = || ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine"))).expect("the toolbar is shown"); let bar = area(); - let edit = crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().find(|r| bar.contains(r.center())).expect("its ••• button"); + let edit = crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().rfind(|r| bar.contains(r.center())).expect("its ••• button"); // Open beside the Tools panel's toolbar, the drawer moves to this one on its ••• click. app.run("window.editToolbar", json!({})).unwrap(); frame(&mut app, &ctx, 0.5, vec![]); @@ -439,6 +439,109 @@ fn a_new_toolbar_fills_from_the_drawer_beside_it() { assert!(!ctx.memory(|m| m.areas().visible_last_frame(&egui::LayerId::new(egui::Order::Middle, crate::custom_toolbars::area_id("Mine"))))); } +/// A toolbar made with New Toolbar has an Add Tool… button (+, above the ••• button) that the +/// keyboard reaches and opens with Enter. Its menu lists the tools under the drawer's headings: a +/// tool picked there with a click or with Enter is +/// added at the end of this toolbar alone, without the drawer, and is dimmed in the menu from then +/// on; picked under Remove Tool, it is taken out again. +#[test] +fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { + let mut app = app(); + let ctx = ctx(); + let shipped = slots(&app); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let plus = || { + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine"))).expect("the toolbar is shown"); + let buttons: Vec = + crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().filter(|r| bar.contains(r.center())).collect(); + assert_eq!(buttons.len(), 2, "the + and ••• buttons: {buttons:?}"); + buttons[0] + }; + let button = plus(); + let sense = ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.rect == button).map(|w| w.sense)); + assert!(sense.is_some_and(|s| s.is_focusable()), "Tab stops on the + button: {sense:?}"); + // The menu at `time`, opened with a click on the + button unless it is open. + let open = |app: &mut VectorcraftApp, time: f64| { + let shown = frame(app, &ctx, time, vec![]); + if shown.iter().any(|(s, ..)| s == "Select:") { + return shown; + } + click(app, &ctx, time + 0.2, plus().center()); + // The menu is sized in its first frame and drawn from the second. + frame(app, &ctx, time + 0.5, vec![]); + frame(app, &ctx, time + 0.6, vec![]) + }; + // The items named `name` that the menu shows (it scrolls), top first. + let items = |shown: &[(String, Pos2, Color32)], name: &str| { + let menu = ctx.memory(|m| m.area_rect(crate::custom_toolbars::add_menu_id("Mine"))).expect("the menu is open"); + let mut at: Vec<(Pos2, Color32)> = shown.iter().filter(|(s, p, _)| s.trim() == name && menu.contains(*p)).map(|(_, p, c)| (*p, *c)).collect(); + at.sort_by(|a, b| a.0.y.total_cmp(&b.0.y)); + at + }; + let mine = |app: &VectorcraftApp| crate::custom_toolbars::find(&app.ui, "Mine").unwrap().slots.clone(); + // The keyboard: Enter on the focused + button opens the menu, and Enter on a tool adds it. + let focusable_at = |p: Pos2| { + let id = ctx.viewport(|vp| { + vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.contains(p) && w.sense.is_focusable()).last().map(|w| w.id) + }); + id.unwrap_or_else(|| panic!("nothing focusable at {p:?}")) + }; + let enter = |app: &mut VectorcraftApp, time: f64, at: Pos2| { + let id = focusable_at(at); + ctx.memory_mut(|m| m.request_focus(id)); + frame(app, &ctx, time, vec![]); + for (k, pressed) in [true, false].into_iter().enumerate() { + let key = Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(app, &ctx, time + 0.1 * (k + 1) as f64, vec![key]); + } + frame(app, &ctx, time + 0.5, vec![]); + frame(app, &ctx, time + 0.6, vec![]) + }; + let shown = enter(&mut app, 9.0, plus().center()); + assert!(items(&shown, "Remove Tool:").is_empty(), "nothing to take out of a blank toolbar"); + let lasso = items(&shown, "Lasso Tool"); + assert_eq!(lasso.len(), 1, "listed once, under Select"); + enter(&mut app, 10.0, lasso[0].0); + assert_eq!(mine(&app), [["lasso"]]); + assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched"); + assert!(!app.ui.tools_drawer, "no drawer opened"); + let list = app.run("window.toolbar.list", json!({})).unwrap(); + assert_eq!(list, json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]]}])); + // A second tool goes after the first. + let shown = open(&mut app, 19.0); + click(&mut app, &ctx, 20.0, items(&shown, "Magic Wand Tool")[0].0); + assert_eq!(mine(&app), [["lasso"], ["magicWand"]]); + // A tool in the toolbar is listed under Remove Tool, and dimmed under its heading, where a click + // adds nothing. + let shown = open(&mut app, 29.0); + assert_eq!(items(&shown, "Remove Tool:").len(), 1); + let lasso = items(&shown, "Lasso Tool"); + assert_eq!(lasso.len(), 2, "under Remove Tool, then under Select"); + let enabled = |at: Pos2| { + let layer = egui::LayerId::new(egui::Order::Foreground, crate::custom_toolbars::add_menu_id("Mine")); + ctx.viewport(|vp| { + vp.prev_pass + .widgets + .layers() + .filter(|(l, _)| **l == layer) + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.sense.senses_click() && w.rect.contains(at)) + .last() + .map(|w| w.enabled) + }) + }; + assert_eq!([enabled(lasso[0].0), enabled(lasso[1].0)], [Some(true), Some(false)], "dimmed under Select"); + click(&mut app, &ctx, 30.0, lasso[1].0); + assert_eq!(mine(&app), [["lasso"], ["magicWand"]]); + // Under Remove Tool, a click takes it out. + let shown = open(&mut app, 39.0); + click(&mut app, &ctx, 40.0, items(&shown, "Lasso Tool")[0].0); + assert_eq!(mine(&app), [["magicWand"]]); + assert_eq!(slots(&app), shipped); +} + /// New Toolbar… in the drawer's menu opens the New Toolbar dialog, which asks for a name. #[test] fn new_toolbar_in_the_drawer_menu_asks_for_a_name() { @@ -477,7 +580,7 @@ fn the_drawer_moves_between_new_toolbars() { frame(&mut app, &ctx, 0.1, vec![]); let edit_of = |name: &str| { let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id(name))).unwrap(); - crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().find(|r| bar.contains(r.center())).unwrap() + crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().rfind(|r| bar.contains(r.center())).unwrap() }; let (a, b) = (edit_of("A"), edit_of("B")); for (k, (button, name)) in [(b, "B"), (a, "A"), (b, "B")].into_iter().enumerate() { diff --git a/crates/ui-egui/src/hang_beacon.rs b/crates/ui-egui/src/hang_beacon.rs new file mode 100644 index 0000000000..e47dbfc79c --- /dev/null +++ b/crates/ui-egui/src/hang_beacon.rs @@ -0,0 +1,674 @@ +//! Where the interface thread is in its frame, for the desktop app's hang report (the app's +//! `hang_watch` module). +//! +//! The interface thread marks each stage of a frame (the host's input hook, the app's logic, the +//! interface, and the hand-off to the renderer), a system clipboard call in progress, whether any +//! window's pass had input ([`watch_input`]), and each command it runs. Another thread reads the +//! marks without waiting for the interface thread: the stage and the activity are atomics, and the +//! recent commands and frame times are read with `try_lock`. Marking costs a few atomic stores a +//! frame and one short lock per command and per frame. The web build marks the same way, and +//! nothing reads the marks there. +//! +//! Commands are kept by id only: no parameters, file names or document contents. A command run +//! again moves to the end of the list instead of taking another place, so a panel that runs a +//! query every frame does not push out the commands before it. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, PoisonError}; + +use vectorcraft_engine::cmd::clipboard::Flavour; + +use crate::sysclip::{ClipboardRead, SystemClipboard}; + +/// How many different command ids [`Beacon::recent_commands`] keeps. +pub const RECENT_COMMANDS: usize = 8; +/// How many frames [`Beacon::recent_frames`] keeps. +pub const RECENT_FRAMES: usize = 16; +/// The longest command id [`Beacon::command`] keeps as it is. +pub const MAX_COMMAND_ID: usize = 64; + +/// The marks the desktop app's interface thread writes. +pub static BEACON: Beacon = Beacon::new(); + +/// The part of a frame the interface thread is in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Stage { + /// Outside the app's own frame code: waiting for input or a repaint, or a frame without input + /// handed to the renderer. + Idle = 0, + /// The host's input hook. + Input = 1, + /// The app's logic: background results, timers, the control channel. + Logic = 2, + /// The interface: input handling, commands, panels and dialogs. + Interface = 3, + /// A frame that had input was handed to the renderer. Drawing and presenting it follow, and + /// then the next frame, which input asks for at once. + Drawing = 4, +} + +impl Stage { + fn from_u8(n: u8) -> Stage { + match n { + 1 => Stage::Input, + 2 => Stage::Logic, + 3 => Stage::Interface, + 4 => Stage::Drawing, + _ => Stage::Idle, + } + } + + /// Whether the interface thread is expected to finish this stage soon. + pub fn busy(self) -> bool { + self != Stage::Idle + } + + /// The stage for a report, in English. + pub fn describe(self) -> &'static str { + match self { + Stage::Idle => "between frames", + Stage::Input => "reading the window's input", + Stage::Logic => "running the app's logic (background results, timers, the control channel)", + Stage::Interface => "running the interface (input handling, commands, panels and dialogs)", + Stage::Drawing => { + "after a frame with input went to the renderer: drawing or presenting it, or waiting for the next frame, which the system may hold back while the window is hidden" + } + } + } +} + +/// What the interface thread is waiting on inside a stage, where the app knows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Activity { + None = 0, + /// A read of the system clipboard, or a check of what it holds. + ClipboardRead = 1, + /// A write to the system clipboard. + ClipboardWrite = 2, + /// A system file dialog shown in line, which waits for the user and keeps the window + /// answering the system ([`Sample::busy`]). + Dialog = 3, + /// A menu of the system menu bar is open, which waits for the user ([`Sample::busy`]). The + /// host sets it on the sample it reads; the interface thread does not mark it. + Menu = 4, +} + +impl Activity { + fn from_u8(n: u8) -> Activity { + match n { + 1 => Activity::ClipboardRead, + 2 => Activity::ClipboardWrite, + 3 => Activity::Dialog, + 4 => Activity::Menu, + _ => Activity::None, + } + } + + /// Whether the activity waits for the user, so a long one is not a stall. + pub fn waits_for_user(self) -> bool { + matches!(self, Activity::Dialog | Activity::Menu) + } + + /// The activity for a report, in English; `None` when there is none. + pub fn describe(self) -> Option<&'static str> { + match self { + Activity::None => None, + Activity::ClipboardRead => Some("reading the system clipboard"), + Activity::ClipboardWrite => Some("writing to the system clipboard"), + Activity::Dialog => Some("a system file dialog, waiting for the user"), + Activity::Menu => Some("a menu of the system menu bar, waiting for the user"), + } + } +} + +/// What the interface thread was doing when it was read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Sample { + /// Counts every mark: the same value in two samples means the thread made no mark between them. + pub step: u64, + pub stage: Stage, + pub activity: Activity, +} + +impl Sample { + /// Whether the interface thread is expected to move on soon: inside a stage, and not showing a + /// system dialog or menu that waits for the user. + pub fn busy(&self) -> bool { + self.stage.busy() && !self.activity.waits_for_user() + } +} + +/// One frame's times, in milliseconds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameTime { + /// The app's own work: from the input hook to the end of the interface. + pub work_ms: f32, + /// The renderer's measure of the frame before: the app's work and drawing, without waiting for + /// the display. `None` when the host has none. + pub previous_total_ms: Option, +} + +/// The marks: see the module documentation. +pub struct Beacon { + step: AtomicU64, + stage: AtomicU8, + activity: AtomicU8, + documents: AtomicUsize, + /// A pass of some window had input since [`Beacon::take_input`] last ran. + input: AtomicBool, + /// The windows a pass handed to the system since [`Beacon::take_handed_off`] last ran. Only the + /// interface thread uses it. + handed_off: Mutex>, + commands: Mutex>, + frames: Mutex>, +} + +impl Default for Beacon { + fn default() -> Self { + Self::new() + } +} + +impl Beacon { + pub const fn new() -> Beacon { + Beacon { + step: AtomicU64::new(0), + stage: AtomicU8::new(Stage::Idle as u8), + activity: AtomicU8::new(Activity::None as u8), + documents: AtomicUsize::new(0), + input: AtomicBool::new(false), + handed_off: Mutex::new(Vec::new()), + commands: Mutex::new(VecDeque::new()), + frames: Mutex::new(VecDeque::new()), + } + } + + fn bump(&self) { + self.step.fetch_add(1, Ordering::Release); + } + + /// The interface thread enters `stage`. + pub fn enter(&self, stage: Stage) { + self.stage.store(stage as u8, Ordering::Relaxed); + self.bump(); + } + + /// The interface thread enters `stage` of a frame, timed whatever the activity around it, so a + /// frame the system runs while a file dialog waits for the user is timed too. The activity + /// before it applies again when the guard is dropped. + pub fn enter_timed(&self, stage: Stage) -> ActivityGuard<'_> { + self.enter(stage); + self.activity(Activity::None) + } + + /// The interface thread starts `activity`; it ends when the guard is dropped, and the activity + /// before it applies again. + pub fn activity(&self, activity: Activity) -> ActivityGuard<'_> { + let before = Activity::from_u8(self.activity.swap(activity as u8, Ordering::Relaxed)); + self.bump(); + ActivityGuard { beacon: self, before } + } + + /// The interface thread runs the command `id`. An id that is not a command id's shape (longer + /// than [`MAX_COMMAND_ID`] characters, or with characters other than ASCII letters, digits, `.`, + /// `_` and `-`) is kept as `(other)`: ids can come from saved files and the control channel. An + /// id already in the list moves to its end. + pub fn command(&self, id: &str) { + self.bump(); + let shaped = id.len() <= MAX_COMMAND_ID && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')); + let kept = if shaped { id } else { "(other)" }; + let mut commands = self.commands.lock().unwrap_or_else(PoisonError::into_inner); + if commands.back().is_some_and(|last| last == kept) { + return; + } + let entry = match commands.iter().position(|c| c == kept) { + Some(i) => commands.remove(i).unwrap_or_else(|| kept.to_string()), + None => { + if commands.len() == RECENT_COMMANDS { + commands.pop_front(); + } + kept.to_string() + } + }; + commands.push_back(entry); + } + + /// A pass of some window had input ([`watch_input`]). + pub fn input(&self) { + self.input.store(true, Ordering::Relaxed); + } + + /// Whether a pass of some window had input since the last call. + pub fn take_input(&self) -> bool { + self.input.swap(false, Ordering::Relaxed) + } + + /// A pass of window `id` sent it commands that hand it to the system ([`hands_off`], + /// [`watch_input`]). + pub fn hand_off(&self, id: egui::ViewportId) { + let mut windows = self.handed_off.lock().unwrap_or_else(PoisonError::into_inner); + if !windows.contains(&id) { + windows.push(id); + } + } + + /// The windows a pass handed to the system since the last call. + pub fn take_handed_off(&self) -> Vec { + std::mem::take(&mut *self.handed_off.lock().unwrap_or_else(PoisonError::into_inner)) + } + + /// A frame ended with `time`, with `documents` documents open. + pub fn frame(&self, time: FrameTime, documents: usize) { + self.documents.store(documents, Ordering::Relaxed); + let mut frames = self.frames.lock().unwrap_or_else(PoisonError::into_inner); + if frames.len() == RECENT_FRAMES { + frames.pop_front(); + } + frames.push_back(time); + } + + /// The current marks. + pub fn sample(&self) -> Sample { + let step = self.step.load(Ordering::Acquire); + Sample { step, stage: Stage::from_u8(self.stage.load(Ordering::Relaxed)), activity: Activity::from_u8(self.activity.load(Ordering::Relaxed)) } + } + + /// The ids of the last [`RECENT_COMMANDS`] commands, oldest first; `None` while the interface + /// thread is writing them. + pub fn recent_commands(&self) -> Option> { + let commands = match self.commands.try_lock() { + Ok(c) => c, + Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return None, + }; + Some(commands.iter().cloned().collect()) + } + + /// The last [`RECENT_FRAMES`] frames' times, oldest first; `None` while the interface thread is + /// writing them. + pub fn recent_frames(&self) -> Option> { + let frames = match self.frames.try_lock() { + Ok(f) => f, + Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return None, + }; + Some(frames.iter().copied().collect()) + } + + /// The documents open at the end of the last frame. + pub fn documents(&self) -> usize { + self.documents.load(Ordering::Relaxed) + } +} + +/// Whether a pass's input asks for the next frame at once: events, or files dropped or hovered. +pub fn had_input(raw: &egui::RawInput) -> bool { + !raw.events.is_empty() || !raw.dropped_files.is_empty() || !raw.hovered_files.is_empty() +} + +/// Mark on `beacon` every pass of every window of `ctx` that had input ([`had_input`]): the main +/// window's, after the host's input hook added its own, and those of the windows shown in line +/// (floating panels and documents), whose input does not pass through that hook. Mark as well every +/// pass of a window shown in line that sends its window commands that hand it to the system +/// ([`hands_off`]), before egui passes them on; the main window's are read at the frame's end. +pub fn watch_input(beacon: &'static Beacon, ctx: &egui::Context) { + ctx.on_begin_pass( + "VectorCraft hang report input", + std::sync::Arc::new(move |ui| { + if ui.ctx().input(|i| had_input(&i.raw)) { + beacon.input(); + } + }), + ); + ctx.on_end_pass( + "VectorCraft hang report hand-off", + std::sync::Arc::new(move |ui| { + if ui.ctx().viewport_id() != egui::ViewportId::ROOT && ui.ctx().viewport(|vp| hands_off(&vp.commands)) { + beacon.hand_off(ui.ctx().viewport_id()); + } + }), + ); +} + +/// Whether `commands` minimize or hide their window, or hand it to the system to move or resize: +/// the system may hold back the next frame until the user is done. +pub fn hands_off(commands: &[egui::ViewportCommand]) -> bool { + use egui::ViewportCommand as C; + commands.iter().any(|c| matches!(c, C::Minimized(true) | C::Visible(false) | C::StartDrag | C::BeginResize(_))) +} + +/// The window whose end of frame sets the stage ([`after_frame`]): the main window when it is +/// `main_shown`; otherwise a window shown in line (a floating panel or document) that `viewports` +/// (the main window's input) gives as focused and not minimized; otherwise none. +pub fn shown_window(main_shown: bool, viewports: &egui::ViewportIdMap) -> Option { + if main_shown { + return Some(egui::ViewportId::ROOT); + } + viewports.iter().find(|(id, v)| **id != egui::ViewportId::ROOT && v.focused == Some(true) && v.minimized != Some(true)).map(|(id, _)| *id) +} + +/// The stage at the end of a frame: [`Stage::Drawing`] when a pass had `input` and a window is +/// `shown` (focused, not minimized or hidden: [`shown_window`]), since input asks for the next +/// frame at once; otherwise [`Stage::Idle`]. A frame that sends that window `commands` that +/// minimize or hide it, or hand it to the system to move or resize ([`hands_off`]), also ends idle. +pub fn after_frame(input: bool, shown: bool, commands: &[egui::ViewportCommand]) -> Stage { + if input && shown && !hands_off(commands) { Stage::Drawing } else { Stage::Idle } +} + +/// Ends an [`Activity`] when dropped ([`Beacon::activity`]). +pub struct ActivityGuard<'a> { + beacon: &'a Beacon, + before: Activity, +} + +impl Drop for ActivityGuard<'_> { + fn drop(&mut self) { + self.beacon.activity.store(self.before as u8, Ordering::Relaxed); + self.beacon.bump(); + } +} + +/// A [`SystemClipboard`] whose calls are marked on [`BEACON`] as clipboard activity. The desktop +/// app wraps the clipboard the interface thread uses; the background probe's own clipboard stays +/// unmarked. +pub struct Marked(pub Box); + +impl SystemClipboard for Marked { + fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> { + let _mark = BEACON.activity(Activity::ClipboardWrite); + self.0.write(flavours) + } + + fn holds_ours(&mut self) -> bool { + let _mark = BEACON.activity(Activity::ClipboardRead); + self.0.holds_ours() + } + + fn read(&mut self, mimes: &[&'static str]) -> Option { + let _mark = BEACON.activity(Activity::ClipboardRead); + self.0.read(mimes) + } + + fn has(&mut self, mimes: &[&'static str]) -> bool { + let _mark = BEACON.activity(Activity::ClipboardRead); + self.0.has(mimes) + } + + fn read_deferred(&mut self, mimes: &[&'static str]) -> Option { + let _mark = BEACON.activity(Activity::ClipboardRead); + self.0.read_deferred(mimes) + } + + fn change_count(&mut self) -> Option { + let _mark = BEACON.activity(Activity::ClipboardRead); + self.0.change_count() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_mark_moves_the_step_and_the_stage_reads_back() { + let b = Beacon::new(); + let first = b.sample(); + assert_eq!((first.stage, first.activity), (Stage::Idle, Activity::None)); + b.enter(Stage::Interface); + let s = b.sample(); + assert!(s.step > first.step); + assert_eq!(s.stage, Stage::Interface); + b.command("edit.copy"); + assert!(b.sample().step > s.step); + b.enter(Stage::Idle); + assert!(!b.sample().stage.busy()); + } + + #[test] + fn an_activity_ends_with_its_guard_and_restores_the_one_before() { + let b = Beacon::new(); + { + let _write = b.activity(Activity::ClipboardWrite); + { + let _read = b.activity(Activity::ClipboardRead); + assert_eq!(b.sample().activity, Activity::ClipboardRead); + } + assert_eq!(b.sample().activity, Activity::ClipboardWrite); + } + assert_eq!(b.sample().activity, Activity::None); + } + + #[test] + fn only_the_last_commands_and_frames_are_kept_oldest_first() { + let b = Beacon::new(); + for n in 0..RECENT_COMMANDS + 3 { + b.command(&format!("cmd.{n}")); + } + let commands = b.recent_commands().unwrap_or_default(); + assert_eq!(commands.len(), RECENT_COMMANDS); + assert_eq!(commands.first().map(String::as_str), Some("cmd.3")); + assert_eq!(commands.last().map(String::as_str), Some("cmd.10")); + for n in 0..RECENT_FRAMES + 2 { + b.frame(FrameTime { work_ms: n as f32, previous_total_ms: None }, 2); + } + let frames = b.recent_frames().unwrap_or_default(); + assert_eq!(frames.len(), RECENT_FRAMES); + assert_eq!(frames.first().map(|f| f.work_ms), Some(2.0)); + assert_eq!(b.documents(), 2); + } + + #[test] + fn a_command_run_every_frame_does_not_push_out_the_ones_before() { + let b = Beacon::new(); + for n in 0..RECENT_COMMANDS - 2 { + b.command(&format!("cmd.{n}")); + } + // Two panels that each run a query every frame. + for _ in 0..100 { + b.command("symbol.list"); + b.command("swatch.list"); + } + b.command("cmd.0"); + let commands = b.recent_commands().unwrap_or_default(); + let want: Vec = ["cmd.1", "cmd.2", "cmd.3", "cmd.4", "cmd.5", "symbol.list", "swatch.list", "cmd.0"].map(String::from).to_vec(); + assert_eq!(commands, want); + } + + #[test] + fn a_frame_with_input_ends_drawing_unless_the_window_is_hidden_or_handed_to_the_system() { + use egui::ViewportCommand as C; + assert_eq!(after_frame(true, true, &[]), Stage::Drawing); + assert_eq!(after_frame(true, true, &[C::Focus]), Stage::Drawing); + assert_eq!(after_frame(false, true, &[]), Stage::Idle); + assert_eq!(after_frame(true, false, &[]), Stage::Idle); + for c in [C::Minimized(true), C::Visible(false), C::StartDrag, C::BeginResize(egui::ResizeDirection::East)] { + assert_eq!(after_frame(true, true, std::slice::from_ref(&c)), Stage::Idle, "{c:?}"); + } + } + + #[test] + fn input_is_events_or_files() { + let mut raw = egui::RawInput::default(); + assert!(!had_input(&raw)); + raw.hovered_files.push(egui::HoveredFile::default()); + assert!(had_input(&raw)); + #[derive(Debug)] + struct Dropped; + impl egui::DroppedFile for Dropped { + fn path(&self) -> &std::path::Path { + std::path::Path::new("a.svg") + } + fn bytes(&self) -> Result, String> { + Ok(Vec::new()) + } + } + let mut raw = egui::RawInput::default(); + raw.dropped_files.push(std::sync::Arc::new(Dropped)); + assert!(had_input(&raw)); + let mut raw = egui::RawInput::default(); + raw.events.push(egui::Event::PointerGone); + assert!(had_input(&raw)); + } + + #[test] + fn input_in_a_window_shown_in_line_is_marked() { + static B: Beacon = Beacon::new(); + // The host runs a window shown in line as its own pass, with that window's input. + let child_events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let events = child_events.clone(); + egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| { + let id = viewport.ids.this; + let viewports = std::iter::once((id, egui::ViewportInfo::default())).collect(); + let input = egui::RawInput { viewport_id: id, viewports, events: events.take(), ..Default::default() }; + ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).textures_delta.clear(); + }); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + watch_input(&B, &ctx); + let child = egui::ViewportId::from_hash_of("floating panel"); + let frame = |main: Vec| { + ctx.run_ui(egui::RawInput { events: main, ..Default::default() }, |ui| { + ui.ctx().show_viewport_immediate(child, egui::ViewportBuilder::default(), |_, _| {}); + }) + .textures_delta + .clear(); + }; + frame(Vec::new()); + assert!(!B.take_input(), "no input anywhere"); + child_events.replace(vec![egui::Event::PointerGone]); + frame(Vec::new()); + assert!(B.take_input(), "the floating window's input"); + assert!(!B.take_input(), "taken"); + frame(vec![egui::Event::PointerGone]); + assert!(B.take_input(), "the main window's input"); + } + + #[test] + fn a_frame_run_while_a_dialog_waits_is_timed() { + let b = Beacon::new(); + let _dialog = b.activity(Activity::Dialog); + assert!(!b.sample().busy(), "the dialog waits for the user"); + { + let _timed = b.enter_timed(Stage::Interface); + assert!(b.sample().busy(), "a frame inside the dialog's wait"); + b.enter(Stage::Drawing); + } + assert_eq!(b.sample().activity, Activity::Dialog, "the dialog again"); + assert!(!b.sample().busy()); + } + + #[test] + fn a_window_shown_in_line_handed_to_the_system_is_marked() { + static B: Beacon = Beacon::new(); + egui::Context::set_immediate_viewport_renderer(|ctx, mut viewport| { + let id = viewport.ids.this; + let viewports = std::iter::once((id, egui::ViewportInfo::default())).collect(); + let input = egui::RawInput { viewport_id: id, viewports, ..Default::default() }; + ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).textures_delta.clear(); + }); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + watch_input(&B, &ctx); + let child = egui::ViewportId::from_hash_of("floating panel"); + let frame = |command: Option, main: Option| { + ctx.run_ui(egui::RawInput::default(), |ui| { + ui.ctx().show_viewport_immediate(child, egui::ViewportBuilder::default(), |ui, _| { + if let Some(c) = command.clone() { + ui.ctx().send_viewport_cmd(c); + } + }); + if let Some(c) = main.clone() { + ui.ctx().send_viewport_cmd(c); + } + }) + .textures_delta + .clear(); + }; + frame(None, None); + assert!(B.take_handed_off().is_empty(), "nothing handed off"); + frame(Some(egui::ViewportCommand::StartDrag), None); + assert_eq!(B.take_handed_off(), [child], "the floating window starts a move"); + assert!(B.take_handed_off().is_empty(), "taken"); + frame(Some(egui::ViewportCommand::Focus), None); + assert!(B.take_handed_off().is_empty(), "another command"); + frame(None, Some(egui::ViewportCommand::StartDrag)); + assert!(B.take_handed_off().is_empty(), "the main window's commands are read at the frame's end"); + } + + #[test] + fn a_focused_window_shown_in_line_is_the_shown_window() { + use egui::{ViewportId, ViewportIdMap, ViewportInfo}; + let child = ViewportId::from_hash_of("document window"); + let info = |focused: bool, minimized: bool| ViewportInfo { focused: Some(focused), minimized: Some(minimized), ..Default::default() }; + let map = |root: ViewportInfo, window: ViewportInfo| -> ViewportIdMap { + [(ViewportId::ROOT, root), (child, window)].into_iter().collect() + }; + assert_eq!(shown_window(true, &map(info(true, false), info(false, false))), Some(ViewportId::ROOT)); + assert_eq!(shown_window(false, &map(info(false, false), info(true, false))), Some(child), "the document window has the focus"); + assert_eq!(shown_window(false, &map(info(false, false), info(true, true))), None, "minimized"); + assert_eq!(shown_window(false, &map(info(false, false), info(false, false))), None, "no window has the focus"); + assert_eq!(shown_window(false, &map(info(true, false), info(false, false))), None, "the main window is not shown"); + } + + #[test] + fn the_marked_clipboard_marks_its_calls() { + type Seen = std::sync::Arc>>; + struct Probe(Seen); + impl Probe { + fn see(&self) { + self.0.lock().unwrap().push(BEACON.sample().activity); + } + } + impl SystemClipboard for Probe { + fn write(&mut self, _: &[Flavour]) -> Result<(), String> { + self.see(); + Ok(()) + } + fn holds_ours(&mut self) -> bool { + self.see(); + false + } + fn read(&mut self, _: &[&'static str]) -> Option { + self.see(); + None + } + fn has(&mut self, _: &[&'static str]) -> bool { + self.see(); + false + } + } + let seen = Seen::default(); + let mut m = Marked(Box::new(Probe(seen.clone()))); + let _ = m.write(&[]); + let _ = m.read(&[]); + let _ = m.has(&[]); + let _ = m.holds_ours(); + assert_eq!(BEACON.sample().activity, Activity::None); + assert_eq!(*seen.lock().unwrap(), vec![Activity::ClipboardWrite, Activity::ClipboardRead, Activity::ClipboardRead, Activity::ClipboardRead]); + } + + #[test] + fn ids_that_are_not_command_ids_are_kept_as_other() { + let b = Beacon::new(); + b.command("file.open"); + b.command("/home/someone/private plan.vectorcraft"); + b.command(&"y".repeat(MAX_COMMAND_ID)); + b.command(&"x".repeat(MAX_COMMAND_ID + 1)); + let commands = b.recent_commands().unwrap_or_default(); + // Both are `(other)`, which moves to the end the second time. + assert_eq!(commands, vec!["file.open".to_string(), "y".repeat(MAX_COMMAND_ID), "(other)".into()]); + } + + #[test] + fn a_reader_does_not_wait_while_the_commands_are_being_written() { + let b = Beacon::new(); + b.command("edit.paste"); + let held = b.commands.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(b.recent_commands(), None); + drop(held); + assert_eq!(b.recent_commands(), Some(vec!["edit.paste".to_string()])); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e69dc7b97c..5f0723f4da 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -249,6 +249,7 @@ font-technology Variable Променливи Asset Export Settings Настройки за експортиране на активи Assets Активи Assign Задаване + Assign Profile Задаване на профил Assign Profile… Задаване на профил… Assign: Задаване: Attach to Active Plane Прикрепване към активната равнина @@ -686,6 +687,15 @@ font-technology Variable Променливи Created: Създадено: Crop Изрязване Crop Image Изрязване на изображение + Image Tools Инструменти за изображения + Remove Background… Премахване на фона… + Remove Background Премахване на фона + Background Фон + Edge Color Цвят на ръба + Picked Colors Избрани цветове + Corner Color Цвят на ъглите + Contiguous Съседни + Each Channel Всеки канал Edit Path Редактиране на контура Mask Маска Crop Marks Знаци за изрязване @@ -1109,6 +1119,8 @@ font-technology Variable Променливи Extrude & Bevel… Избутване и фасетка… 3D (Classic) 3D (класически) Extrude & Bevel (Classic)… Избутване и фасетка (класически)… + Revolve (Classic)… Завъртане (класическо)… + Rotate (Classic)… Ротация (класическа)… Surface Повърхност Wireframe Телена рамка No Shading Без засенчване @@ -1389,6 +1401,14 @@ font-technology Variable Променливи Hair Space Тънък интервал Hand Tool Инструмент „Ръка“ Hand-Drawn Ръчно рисувани + Painted and Sketched Рисувани и скицирани + Washed Blue Размито синьо + Bristle Ochre Охра с четка + Pastel Heather Пастелен пирен + Charcoal Shade Сянка с въглен + Ink Contour Мастилен контур + Wet Ink Мокро мастило + Fine Pen Фино перо Handles Дръжки Hard Light Твърда светлина Hard Mix Твърдо смесване @@ -1604,6 +1624,7 @@ font-technology Variable Променливи Include Linked Files Включване на свързаните файлове Include Metadata Включване на метаданни Include non-printing layers Включване на слоеве, които не се печат + Write pages longer than 200 in at full size in points Записване на страници, по-дълги от 200 in, в пълен размер в точки Include SVG Code Включване на SVG код Include Swatches for Tints Включване на образци за тонове Inflate… Издуване… @@ -2262,12 +2283,17 @@ font-technology Variable Променливи Open… Отваряне… Optical Оптично Optical Margin Alignment Подравняване по оптично поле + Dynamic Text Динамичен текст + Dynamic Text Presets Шаблони за динамичен текст + Arch Арка Optimize for fast web view Оптимизиране за бърз уеб преглед Optimized Оптимизирано Options Опции Options for Selection… Опции за селектиране… Options: Опции: Options… Опции… + Organic Fades Органични преливания + Holographic Холографски or more spaces with a tab или повече интервала с табулация Order: Ред: Ordinals Поредни номера @@ -2459,6 +2485,7 @@ font-technology Variable Променливи Presets: Предварителни настройки: Press Натиснете Preview Преглед + Preview: Преглед: Preview All Layers Преглед на всички слоеве Preview in Browser Преглед в браузър Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) @@ -2537,6 +2564,8 @@ digits Malayalam Малаялам Radial Радиален Radial Glows Лъчисти сияния Radial Gradient Лъчист градиент + Conic Gradient Конусен градиент + Diamond Gradient Ромбовиден градиент Radius 1 Радиус 1 Radius 2 Радиус 2 Radius1 Радиус1 @@ -2549,6 +2578,8 @@ digits Malayalam Малаялам Range: Диапазон: Raster Effects Растерен ефект Raster File Format: Растерен файлов формат: + Include Placed Images Включване на поставените изображения + Include Fill Hatches Включване на щриховките на запълванията Raster Sample Size: Растерен размер на пробата: Raster/Vector Balance: Баланс растер/вектор: Rasterize Растеризиране @@ -2729,6 +2760,10 @@ digits Malayalam Малаялам Replace Font Замяна на шрифт Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Заменете го с друг файл или го игнорирайте: неговите изображения ще продължат да показват записания с документа преглед. Replace Spine Замяна на оста + Create Spine Създаване на ос + Create Spine: Създаване на ос: + Always Винаги + Never Никога Replace Symbol Замяна на символ Reset Transformation Нулиране на трансформацията Replace With Font Замяна с шрифт @@ -2807,6 +2842,9 @@ digits Malayalam Малаялам Rise… Издигане… Roman Baseline Латинска основна линия Roman Hanging Punctuation Латинска висяща пунктуация + Korean Line Break Anywhere Пренасяне на корейски текст навсякъде + East Asian Composition Settings Настройки за източноазиатска композиция + Korean Composition Settings Настройки за корейска композиция Rotate Завъртане Rotate 90° CW Завъртане на 90° по часовниковата стрелка Rotate Tool Инструмент „Завъртане“ @@ -3078,6 +3116,15 @@ digits Malayalam Малаялам Stun Pulse Зашеметяване Stealth Fade Скритост Shield Buff Щит + Textures Текстури + Fine Grain Фино зърно + Canvas Weave Тъкано платно + Burlap Sack Зебло + Cracked Glaze Напукана глазура + Mosaic Floor Мозаечен под + Quilted Squares Капитонирани квадрати + Leaded Glass Оловно стъкло + Damp Paper Влажна хартия Shape Фигура Shape Builder Създател на фигури Shape Builder Regions Области на създателя на фигури @@ -3140,6 +3187,7 @@ digits Malayalam Малаялам Show Modified Показване на променените Show Note Показване на бележка Show Options Показване на опциите + Show Recent Colors Показване на скорошните цветове Show Original Path Показване на оригиналния път Open this dialog with these settings next time Отваряне на този прозорец с тези настройки следващия път Auto-Simplify Автоматично опростяване @@ -3443,6 +3491,8 @@ digits Malayalam Малаялам Scale at Center Мащабиране от центъра Up/Down: Нагоре/надолу: Left/Right: Наляво/надясно: + Tate-chu-yoko Up/Down Тате-чу-йоко нагоре/надолу + Tate-chu-yoko Left/Right Тате-чу-йоко наляво/надясно Temperature Температура Temperature/Tint… Температура/Нюанс… Template Шаблон @@ -3512,6 +3562,8 @@ digits Malayalam Малаялам Toolbar: Single/Double Column Лента с инструменти: Една/Две колони Toolbar: Add Tool Лента с инструменти: Добавяне на инструмент Toolbar: Remove Tool Лента с инструменти: Премахване на инструмент + Add Tool… Добавяне на инструмент… + Remove Tool Премахване на инструмент Toolbar: Reset Лента с инструменти: Нулиране Toolbars Ленти с инструменти Tools Инструменти @@ -3582,6 +3634,8 @@ digits Malayalam Малаялам Type on a Path Текст по пътя Type on a Path Options Опции за текст по пътя Type on a Path Options… Опции за текст по път… + Center on Top Центриране горе + Center on Bottom Центриране долу Type on a Path Tool Инструмент „Текст по път“ Type Orientation Ориентация на текста Type stays text, and every stroke is a line with its lineweight and dashes. Текстът остава текст, а всеки щрих е линия с дебелина и чертички. @@ -3775,6 +3829,7 @@ digits Malayalam Малаялам Windows Windows Working CMYK Работен CMYK Working CMYK (don't tag) Работен CMYK (без етикет) + Working RGB (don't tag) Работен RGB (без етикет) Workspace Работно пространство Workspace {i} Работно пространство {i} Wrinkle Tool Инструмент „Набръчкване“ @@ -3953,6 +4008,13 @@ axis Both И двете Dock Panel Закотвен панел Dock to Top Закотвяне горе Dock to Bottom Закотвяне долу + Control Bar Options Опции на контролната лента + Tool Options Опции за инструмент + Object Options Опции за обект + Image Options Опции за изображение + Vertical Alignment Вертикално подравняване + Align and Distribute Подравняване и разпределение + Document Options Опции за документ Dock Control Bar Закотвяне на контролната лента Drag to float the toolbar Плъзнете, за да направите лентата с инструменти плаваща Drag to the window's left or right edge to dock Плъзнете до левия или десния ръб на прозореца за закотвяне @@ -4066,6 +4128,8 @@ axis Both И двете @msg `gradient` must be an object `gradient` трябва да бъде обект @msg `library` is a library id or name (see {list}) `library` е идентификатор или име на библиотека (вижте {list}) @msg `mode` applies to freeform gradients `mode` се прилага към свободни разградки +@msg a negative `aspect` applies to conic gradients отрицателен `aspect` се прилага към конусни градиенти +@msg `focal` applies to radial gradients `focal` се прилага към радиални градиенти @msg `sampleSize` must be 1, 3 or 5 `sampleSize` трябва да бъде 1, 3 или 5 @msg `stops` must be an array `stops` трябва да бъде масив @msg `svg` must be an object of SVG options (see document.formats) `svg` трябва да бъде обект с опции за SVG (вижте document.formats) @@ -4350,6 +4414,8 @@ axis Both И двете @msg not a stored central record не е съхранен централен запис @msg not a valid plug-in module: {0} не е валиден модул за плъгин: {0} @msg not an EMF or WMF file не е EMF или WMF файл +@msg not an HP-GL file не е HP-GL файл +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` трябва да бъде масив от 1 до 255 цвята във формат #rrggbb @msg not found не е открито @msg not in pattern editing mode не е в режим на редактиране на мостра @msg finish editing the pattern first първо завършете редактирането на мострата @@ -4522,7 +4588,7 @@ axis Both И двете @msg unknown format непознат формат @msg unknown format `{f}` (Save writes {_1}) непознат формат `{f}` (Запазването записва {_1}) @msg unknown freeform mode `{m}` (points, lines) непознат режим на свободна форма `{m}` (точки, линии) -@msg unknown gradient kind `{k}` (linear, radial, freeform) непознат вид градиент `{k}` (линеен, радиален, свободна форма) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) непознат вид градиент `{k}` (линеен, радиален, конусен, ромбовиден, свободна форма) @msg unknown highlight `{h}` непознат акцент `{h}` @msg unknown option `{path}.{k}` непозната опция `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) непознати надписи `{o}` (запазване, симулиране или отхвърляне) @@ -4755,6 +4821,8 @@ axis Both И двете @msg invalid object id {value}: expected a non-negative integer невалиден идентификатор на обект {value}: очаква се неотрицателно цяло число @msg `{key}` entry {index} is {value}, not a non-negative integer object id елемент {index} на `{key}` е {value}, а не идентификатор на обект (неотрицателно цяло число) @msg no such object id {value} няма обект с идентификатор {value} +@msg id {value} is a ruler guide, not an object идентификатор {value} е на водач, а не на обект +@msg a ruler guide goes only directly in a layer or sublayer водачът може да е само пряко в слой или подслой @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: outside the read root {root}: {path} пътят за автоматизация е отхвърлен: извън корена за четене {root}: {path} @@ -4771,7 +4839,13 @@ axis Both И двете @msg the PSD file has an unknown colour mode ({m}) PSD файлът има непознат цветови режим ({m}) @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 zipped 32-bit PSD image data with prediction can't be read архивирани (zipped) 32-битови PSD образни данни с предсказване не могат да бъдат прочетени +@msg zipped 1-bit PSD image data with prediction can't be read архивирани (zipped) 1-битови PSD образни данни с предсказване не могат да бъдат прочетени +@msg the PSD file's layer data uses an unknown compression ({m}) данните на слоевете на PSD файла използват непознато компресиране ({m}) +@msg the PSD file's layer records are damaged записите на слоевете на PSD файла са повредени +@msg the PSD file's layer groups are nested too deeply групите слоеве на PSD файла са вложени твърде дълбоко +@msg a layer of the PSD file is too large to read слой на PSD файла е твърде голям за четене +@msg the PSD file's layers take more memory to read than allowed слоевете на PSD файла изискват повече памет за четене от позволеното +@msg the layers can't be read ({e}): the file opened as its merged image слоевете не могат да бъдат прочетени ({e}): файлът е отворен като обединеното си изображение @msg {depth}-bit PSD files in this colour mode can't be read {depth}-битови PSD файлове в този цветови режим не могат да бъдат прочетени @msg the PSD file is cut short PSD файлът е непълен @msg the PSD file's header is damaged заглавната част (header) на PSD файла е повредена @@ -5490,6 +5564,11 @@ theme Appearance Външен вид Softness Мекота Ambient Light Околна светлина Light behind the object Светлина зад обекта + Shadows Сенки + Distance from Object Разстояние от обекта + Shadow Bounds Граници на сянката + Behind Object Зад обекта + Below Object Под обекта 3D Lighting Preset Предварителна настройка за 3D осветление Standard Стандартно Diffuse Дифузно @@ -5613,7 +5692,7 @@ theme Appearance Външен вид @msg span must be "object" or "selection", got {v} span трябва да е "object" или "selection", а не {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 span: "selection" поставя линеен или радиален градиент, а не свободен +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" поставя линеен, радиален, конусен или ромбовиден градиент, а не свободен @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" поставя самия градиент: пропуснете `start` и `end` (те вече го поставят в координатите на документа) Make Image Dynamic Динамично изображение Import Data Sets… Импортиране на набори от данни… @@ -5782,6 +5861,7 @@ theme Appearance Външен вид Ruby Руби Geometric Guides Геометрични водачи Geometric Patterns Геометрични мостри + Grit Textures Зърнести текстури Ease In Плавно начало Ease Out Плавен край Ease In Out Плавно начало и край @@ -5835,6 +5915,7 @@ axis Y Axis Y ос Version: {version} Версия: {version} Install “{name}” in place of the plug-in with the same ID? Да се инсталира ли „{name}“ на мястото на приставката със същия ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Този файл не е приставката, инсталирана преди с този ID. Той получава настройките и кеша, пазени за този ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизация поиска инсталирането на тази приставка. За да я инсталирате, изберете Обект › Приставки › Инсталиране на приставка… сами. File SHA-256: {hash} SHA-256 на файла: {hash} Read the objects it is given Четене на обектите, които получава Change, add and delete objects in the document Промяна, добавяне и изтриване на обекти в документа @@ -5867,6 +5948,16 @@ axis Y Axis Y ос @msg message must be text message трябва да бъде текст @msg allowContinue must be true or false allowContinue трябва да бъде true или false @msg Batch cannot play an action with a stop Пакет не може да изпълни действие със спиране + Insert Menu Item… Вмъкване на елемент от меню… + Insert Menu Item Вмъкване на елемент от меню + Menu Item: Елемент от меню: + No menu item matches. Няма съвпадащ елемент от меню. + Several menu items match. Choose one from the list. Съвпадат няколко елемента от меню. Изберете един от списъка. + Items that open a dialog, and File, Window and Help menu items, are not listed. Елементите, които отварят диалогов прозорец, и елементите от менютата „Файл“, „Прозорец“ и „Помощ“ не са изброени. +@msg command must be text command трябва да бъде текст +@msg no menu item that can be inserted runs this command няма елемент от меню за вмъкване, който изпълнява тази команда +@msg the action already has 10,000 steps действието вече има 10 000 стъпки +@msg the action set would be larger than 8 MiB наборът от действия ще стане по-голям от 8 MiB Playback Options Опции за възпроизвеждане Accelerated Ускорено Step by Step Стъпка по стъпка @@ -5900,6 +5991,12 @@ axis Y Axis Y ос Crosshair Мерник Checkpoint Контролна точка Inventory Icons Икони на инвентара + Skill Icons Икони на умения + Attack Атака + Defend Защита + Heal Лечение + Buff Усилване + Ult Улт Sword Меч Shield Щит Potion Отвара @@ -5958,7 +6055,23 @@ axis Y Axis Y ос Dash Trail Пунктирна следа Speed Line Линия на скорост Game Trails Игрови следи + Energy Beams Енергийни лъчи + Laser Bolt Лазерен болт + Plasma Arc Плазмена дъга + Charge Wave Вълна на заряд + Spark Trail Следа от искри Calligraphic Nibs Калиграфски писци + Bristle Brushes Четки с косъм + Fine Liner Тънък контур + Pointed Flat Заострена плоска + Stubby Round Къса кръгла + Dry Scrub Сухо търкане + Soft Dome Мек купол + Filbert Плоска овална + Angled Round Скосена кръгла + Angled Flat Скосена плоска + Fan Blender Ветрило за смесване + Grass Fan Ветрило за трева Pattern Borders Бордюри с мостри Scatter Shapes Разсеяни фигури Save Brush Library… Запази библиотека с четки… @@ -6303,6 +6416,12 @@ breakText Glyphs Глифи Delete the selected brushes? Да се изтрият избраните четки? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? Remove Strokes Премахване на щрихи + Place Brush Art Поставяне на графика на четка + Replace Brush Art Замяна на графика на четка + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Щрихи използват тази четка. Да се приложи ли новата графика към тези щрихи, или те да останат както са и да се добави копие на четката с новата графика? + Apply to Strokes Прилагане към щрихите + Leave Strokes Оставяне на щрихите +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` няма графика (имат я само разпръснатите и артистичните четки и четките с мостра) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменти за подреждане Arrange in Grid… Подреждане в мрежа… @@ -6485,6 +6604,11 @@ breakText Glyphs Глифи No importer plug-ins installed Няма инсталирани плъгини за импортиране Read files you open in its format and make documents from them Четене на файлове, които отваряте в неговия формат, и създаване на документи от тях +# Copy Troubleshooting Info + Copy Troubleshooting Info Копиране на информация за отстраняване на проблеми +@msg Copied the troubleshooting info Информацията за отстраняване на проблеми е копирана +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Последната сесия на VectorCraft спря да отговаря, преди да се затвори. Помощ › Копиране на информация за отстраняване на проблеми копира подробностите за доклад за грешка + # Safe Mode Safe Mode… Безопасен режим… Safe Mode Безопасен режим @@ -6505,6 +6629,8 @@ breakText Glyphs Глифи # Align to Pixel Grid Align to Pixel Grid Подравняване към пикселната мрежа + Align New Objects to Pixel Grid Подравняване на новите обекти към пикселната мрежа + Not Aligned to Pixel Grid Неподравнени към пикселната мрежа @msg side is left or right, not `{s}` side е left или right, а не `{s}` Edit Custom Dictionary Редактиране на потребителски речник Entry: Запис: @@ -6530,6 +6656,26 @@ breakText Glyphs Глифи @plural {n} earlier line dropped|{n} earlier lines dropped {n} по-ранен ред премахнат|{n} по-ранни реда премахнати @plural {n} line cut|{n} lines cut {n} ред съкратен|{n} реда съкратени +# Learn panel + Learn Обучение + Explore tutorials Разгледайте уроците + For you За вас + Skills Умения + Get started Първи стъпки + Quick skill guide Бързо ръководство за умения + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Кратки практически уроци за основните инструменти, групирани по умения. Изберете умение, за да видите уроците му. + List Tutorials Извеждане на уроци + Show Tutorial Показване на урок +@msg missing `tutorial` (see learn.list) липсва `tutorial` (вижте learn.list) +@msg unknown tutorial `{id}` (see learn.list) непознат урок `{id}` (вижте learn.list) + # Deferred plug-in effects Refresh Deferred Effects Обновяване на отложените ефекти Deferred Effects Отложени ефекти + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Инструменти за рязане + Stencil Bridges… Мостчета на шаблона… + Stencil Bridges Мостчета на шаблона + Shortest Crossing Най-късо пресичане + Direction Посока diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index fc4610e0d0..8caa306eed 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -113,6 +113,7 @@ PDF Presets… PDF predlošci… Perspective Grid Presets… Predlošci mreže perspektive… Color Settings… Postavke boja… + Assign Profile Dodijeli profil Assign Profile… Dodijeli profil… Keyboard Shortcuts… Prečice na tastaturi… Import Shortcut Set Uvezi skup prečica @@ -196,6 +197,15 @@ Expand… Proširi… Expand Appearance Proširi izgled Crop Image Izreži sliku + Image Tools Alati za slike + Remove Background… Ukloni pozadinu… + Remove Background Ukloni pozadinu + Background Pozadina + Edge Color Boja ruba + Picked Colors Odabrane boje + Corner Color Boja uglova + Contiguous Susjedni + Each Channel Svaki kanal Edit Path Uredi putanju Mask Maska Rasterize… Rasteriziraj… @@ -246,6 +256,10 @@ Blend Options… Opcije stapanja… Expand Proširi Replace Spine Zamijeni kičmu + Create Spine Kreiraj kičmu + Create Spine: Kreiraj kičmu: + Always Uvijek + Never Nikad Reverse Spine Obrni kičmu Reverse Front to Back Obrni od naprijed prema nazad Envelope Distort Izobličenje omotnicom @@ -384,6 +398,8 @@ Stair Step Stepenice Gravity Gravitacija Type on a Path Options… Opcije teksta na putanji… + Center on Top Centriraj na vrhu + Center on Bottom Centriraj na dnu Threaded Text Povezani tekst Create Kreiraj Release Selection Oslobodi odabir @@ -399,6 +415,9 @@ Smart Punctuation… Pametna interpunkcija… Create Outlines Kreiraj obrise Optical Margin Alignment Optičko poravnanje margina + Dynamic Text Dinamički tekst + Dynamic Text Presets Predlošci dinamičkog teksta + Arch Svod Fill with Placeholder Text Ispuni tekstom čuvara mjesta Insert Inline Symbol Umetni simbol u redu Show Hidden Characters Prikaži skrivene znakove @@ -470,6 +489,8 @@ Extrude & Bevel… Istiskivanje i zakošenje… 3D (Classic) 3D (klasično) Extrude & Bevel (Classic)… Istiskivanje i zakošenje (klasično)… + Revolve (Classic)… Rotaciono tijelo (klasično)… + Rotate (Classic)… Rotiraj (klasično)… Surface Površina Wireframe Žičani model No Shading Bez sjenčenja @@ -543,6 +564,7 @@ Gaussian Blur… Gaussovo zamućenje… View Prikaz Preview Pregled + Preview: Pregled: Overprint Preview Pregled pretiska Pixel Preview Pregled piksela Trim View Prikaz obrezivanja @@ -783,8 +805,25 @@ Stun Pulse Omamljenost Stealth Fade Nevidljivost Shield Buff Štit + Textures Teksture + Fine Grain Fino zrno + Canvas Weave Tkano platno + Burlap Sack Jutena vreća + Cracked Glaze Ispucala glazura + Mosaic Floor Mozaični pod + Quilted Squares Prošiveni kvadrati + Leaded Glass Olovno staklo + Damp Paper Vlažni papir Outlines and Rules Obrisi i linije Hand-Drawn Ručno crtano + Painted and Sketched Slikano i skicirano + Washed Blue Isprano plavo + Bristle Ochre Oker kistom + Pastel Heather Pastelni vrijesak + Charcoal Shade Sjena ugljenom + Ink Contour Kontura tušem + Wet Ink Mokri tuš + Fine Pen Fino pero Gradient Finishes Gradijentne završnice Shape Effects Efekti oblika Blends and Transparency Stapanja i prozirnost @@ -804,6 +843,8 @@ Spectrum Gradients Gradijenti spektra Sky Gradients Gradijenti neba Neutral Gradients Neutralni gradijenti + Organic Fades Organski prelazi + Holographic Holografski Duotone Gradients Duoton gradijenti Radial Glows Radijalni sjajevi Save Swatch Library… Sačuvaj biblioteku uzoraka boja… @@ -863,6 +904,13 @@ Dock Panel Usidri panel Dock to Top Usidri na vrh Dock to Bottom Usidri na dno + Control Bar Options Opcije kontrolne trake + Tool Options Opcije alata + Object Options Opcije objekta + Image Options Opcije slike + Vertical Alignment Okomito poravnanje + Align and Distribute Poravnanje i raspored + Document Options Opcije dokumenta Dock Control Bar Usidri kontrolnu traku Float Tool Group Odvoji grupu alata Services Usluge @@ -1147,6 +1195,8 @@ lighting Light Svjetlo Toolbar: Single/Double Column Traka s alatima: jedna/dvije kolone Toolbar: Add Tool Traka s alatima: dodaj alat Toolbar: Remove Tool Traka s alatima: ukloni alat + Add Tool… Dodaj alat… + Remove Tool Ukloni alat Toolbar: Reset Traka s alatima: vrati na početno Two Point Perspective Preset 1 Predložak perspektive s dvije tačke 1 Two Point Perspective Preset 2 Predložak perspektive s dvije tačke 2 @@ -1525,6 +1575,7 @@ digits Malayalam Malajalam Roman Baseline Latinična osnovna linija Select a text object to edit its character attributes. Odaberite tekstualni objekat da uredite njegove atribute znakova. Show Options Prikaži opcije + Show Recent Colors Prikaži nedavne boje Color Panel Options Opcije panela boja Small Caps Mala velika slova Small Caps (on the roadmap) Mala velika slova (u planu) @@ -1553,6 +1604,8 @@ digits Malayalam Malajalam Scale at Center Skaliraj od centra Up/Down: Gore/dolje: Left/Right: Lijevo/desno: + Tate-chu-yoko Up/Down Tate-chu-yoko gore/dolje + Tate-chu-yoko Left/Right Tate-chu-yoko lijevo/desno Underline Podvučeno Vertical Scale % Okomita skala % Axis Osa @@ -1655,6 +1708,8 @@ digits Malayalam Malajalam No gradient swatches Nema gradijentnih uzoraka boja Points: clicks add free points Tačke: klikovi dodaju slobodne tačke Radial Gradient Radijalni gradijent + Conic Gradient Konusni gradijent + Diamond Gradient Rombni gradijent Reset to White, Black Vrati na bijelu, crnu Reverse Gradient Obrni gradijent Save to Swatches Sačuvaj u uzorke boja @@ -1937,6 +1992,9 @@ digits Malayalam Malajalam Right Indent Desna uvlaka Right-to-Left Paragraph Direction Smjer pasusa s desna nalijevo Roman Hanging Punctuation Latinična viseća interpunkcija + Korean Line Break Anywhere Prelom korejskog reda bilo gdje + East Asian Composition Settings Postavke istočnoazijske kompozicije + Korean Composition Settings Postavke korejske kompozicije Select a text object to edit its paragraph attributes. Odaberite tekstualni objekat da uredite njegove atribute pasusa. Single-line Composer Slagač jednog reda Toggle Line Composer Uključi/isključi Line Composer @@ -2023,6 +2081,7 @@ digits Malayalam Malajalam Simulate Paper Simuliraj papir Use Black Point Compensation Koristi kompenzaciju crne tačke Working CMYK (don't tag) Radni CMYK (bez oznake) + Working RGB (don't tag) Radni RGB (bez oznake) {name} (spot) {name} (spot) Add to Profiles… Dodaj u profile… Align Stroke to Center Poravnaj potez po sredini @@ -2323,6 +2382,8 @@ digits Malayalam Malajalam Export Selected Art Only Izvezi samo odabrani crtež Number of Colors: Broj boja: Raster File Format: Format rasterske datoteke: + Include Placed Images Uključi postavljene slike + Include Fill Hatches Uključi šrafure ispuna True colour needs version 2004 or later: the nearest of 256 colours is written. Prava boja zahtijeva verziju 2004 ili noviju: zapisuje se najbliža od 256 boja. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Tekst postaje obrisi, a potezi koje CAD linija ne može nacrtati postaju ispunjeni oblici. Type stays text, and every stroke is a line with its lineweight and dashes. Tekst ostaje tekst, a svaki potez je linija sa svojom debljinom i crticama. @@ -2878,6 +2939,7 @@ antiAlias Sharp Oštro General › Thumbnails Općenito › Sličice Grayscale images Slike u nijansama sive Include non-printing layers Uključi slojeve koji se ne štampaju + Write pages longer than 200 in at full size in points Upiši stranice duže od 200 in u punoj veličini, u tačkama Left: Lijevo: Mark as trapped Označi kao zarobljeno Marks and Bleeds Oznake i napusti @@ -4433,6 +4495,8 @@ imageTrace Outline Obris @msg `groupColors` must be an array `groupColors` mora biti niz @msg `library` is a library id or name (see {list}) `library` je ID ili naziv biblioteke (vidi {list}) @msg `mode` applies to freeform gradients `mode` se primjenjuje na gradijente slobodnog oblika +@msg a negative `aspect` applies to conic gradients negativan `aspect` se primjenjuje na konusne gradijente +@msg `focal` applies to radial gradients `focal` se primjenjuje na radijalne gradijente @msg `preserve` must be an object `preserve` mora biti objekat @msg `globalAdjust` must be an object `globalAdjust` mora biti objekat @msg `sampleSize` must be 1, 3 or 5 `sampleSize` mora biti 1, 3 ili 5 @@ -4741,6 +4805,8 @@ imageTrace Outline Obris @msg not a stored central record nije sačuvani centralni zapis @msg not a valid plug-in module: {0} nije važeći modul dodatka: {0} @msg not an EMF or WMF file nije EMF ni WMF datoteka +@msg not an HP-GL file nije HP-GL datoteka +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` mora biti niz od 1 do 255 boja #rrggbb @msg not an export presets file (format `{_1}`) nije datoteka predložaka izvoza (format `{_1}`) @msg not an export presets file: {e} nije datoteka predložaka izvoza: {e} @msg not found nije pronađeno @@ -4921,7 +4987,7 @@ imageTrace Outline Obris @msg unknown format nepoznat format @msg unknown format `{f}` (Save writes {_1}) nepoznat format `{f}` (Sačuvaj zapisuje {_1}) @msg unknown freeform mode `{m}` (points, lines) nepoznat način slobodnog oblika `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) nepoznata vrsta gradijenta `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) nepoznata vrsta gradijenta `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` nepoznato isticanje `{h}` @msg unknown option `{path}.{k}` nepoznata opcija `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) nepoznati pretisci `{o}` (preserve, simulate ili discard) @@ -5110,6 +5176,8 @@ imageTrace Outline Obris @msg invalid object id {value}: expected a non-negative integer nevažeći ID objekta {value}: očekuje se nenegativan cijeli broj @msg `{key}` entry {index} is {value}, not a non-negative integer object id stavka {index} u `{key}` je {value}, a ne ID objekta (nenegativan cijeli broj) @msg no such object id {value} nema objekta s ID-om {value} +@msg id {value} is a ruler guide, not an object ID {value} je vodilica, a ne objekat +@msg a ruler guide goes only directly in a layer or sublayer vodilica može biti samo direktno u sloju ili podsloju @msg id {value} is a layer, not an object id {value} je sloj, a ne objekat @msg id {value} is a layer, not an object; move layers with layer.move id {value} je sloj, a ne objekat; slojeve pomjerajte s layer.move @msg automation filesystem access is not granted: read authority is absent: {path} pristup datotečnom sistemu za automatizaciju nije odobren: nema ovlaštenja za čitanje: {path} @@ -5139,7 +5207,13 @@ imageTrace Outline Obris @msg the HEIC or HEIF file holds a kind of image that can't be read datoteka HEIC ili HEIF sadrži vrstu slike koju nije moguće pročitati @msg HEIC and HEIF images can't be opened in this build HEIC i HEIF slike nije moguće otvoriti u ovoj verziji programa @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD slika je prevelika za čitanje ({_1} × {_2} piksela) -@msg zipped 32-bit PSD image data with prediction can't be read zipovani 32-bitni PSD podaci slike s predviđanjem ne mogu se pročitati +@msg zipped 1-bit PSD image data with prediction can't be read zipovani 1-bitni PSD podaci slike s predviđanjem ne mogu se pročitati +@msg the PSD file's layer data uses an unknown compression ({m}) podaci slojeva PSD datoteke koriste nepoznatu kompresiju ({m}) +@msg the PSD file's layer records are damaged zapisi slojeva PSD datoteke su oštećeni +@msg the PSD file's layer groups are nested too deeply grupe slojeva PSD datoteke su previše duboko ugniježđene +@msg a layer of the PSD file is too large to read sloj PSD datoteke je prevelik za čitanje +@msg the PSD file's layers take more memory to read than allowed slojevi PSD datoteke zahtijevaju više memorije za čitanje nego što je dozvoljeno +@msg the layers can't be read ({e}): the file opened as its merged image slojevi se ne mogu pročitati ({e}): datoteka je otvorena kao spojena slika @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitne PSD datoteke u ovom načinu boja ne mogu se pročitati @msg the PSD file is cut short PSD datoteka je skraćena @msg the PSD file's header is damaged zaglavlje PSD datoteke je oštećeno @@ -5574,6 +5648,11 @@ mark-style Japanese Japanski Softness Mekoća Ambient Light Ambijentalno svjetlo Light behind the object Svjetlo iza objekta + Shadows Sjene + Distance from Object Udaljenost od objekta + Shadow Bounds Granice sjene + Behind Object Iza objekta + Below Object Ispod objekta 3D Lighting Preset Predložak 3D osvjetljenja Standard Standardno Diffuse Difuzno @@ -5634,7 +5713,7 @@ mark-style Japanese Japanski @msg span must be "object" or "selection", got {v} span mora biti "object" ili "selection", dobiveno {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" postavlja `gradient`, a ne uzorak boje @msg span: "selection" places a gradient: give `gradient` span: "selection" postavlja gradijent: navedite `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" postavlja linearni ili radijalni gradijent, a ne gradijent slobodnog oblika +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" postavlja linearni, radijalni, konusni ili rombni gradijent, a ne gradijent slobodnog oblika @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" postavlja sam gradijent: izostavite `start` i `end` (oni ga već postavljaju u koordinatama dokumenta) Make Image Dynamic Učini sliku dinamičkom Import Data Sets… Uvezi skupove podataka… @@ -5799,6 +5878,7 @@ mark-style Japanese Japanski Ruby Ruby Geometric Guides Geometrijske vodilice Geometric Patterns Geometrijski uzorci + Grit Textures Zrnaste teksture Ease In Ublaži ulaz Ease Out Ublaži izlaz Ease In Out Ublaži ulaz i izlaz @@ -5856,6 +5936,8 @@ axis Y Axis Y osa Version: {version} Verzija: {version} Install “{name}” in place of the plug-in with the same ID? Instalirati „{name}” umjesto dodatka s istim ID-om? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ova datoteka nije dodatak ranije instaliran s ovim ID-om. Dobija postavke i predmemoriju sačuvane za taj ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatizacija je zatražila instalaciju ovog dodatka. Da biste ga instalirali, izaberite Objekat › Dodaci › Instaliraj dodatak… sami. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatizacija je zatražila instalaciju ovog dodatka. Da biste ga instalirali, izaberite Objekat › Dodaci › Instaliraj dodatak… sami. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}” je drugi modul od dodatka s ID-om {_1} i dobio bi postavke i predmemoriju sačuvane za njega: instalirajte ga s `replace: true` kada korisnik pristane File SHA-256: {hash} SHA-256 datoteke: {hash} Read the objects it is given Čitati objekte koje dobije @@ -5906,6 +5988,16 @@ axis Y Axis Y osa @msg message must be text message mora biti tekst @msg allowContinue must be true or false allowContinue mora biti true ili false @msg Batch cannot play an action with a stop Paketna obrada ne može reprodukovati akciju sa zaustavljanjem + Insert Menu Item… Umetni stavku menija… + Insert Menu Item Umetni stavku menija + Menu Item: Stavka menija: + No menu item matches. Nijedna stavka menija ne odgovara. + Several menu items match. Choose one from the list. Odgovara više stavki menija. Izaberite jednu sa liste. + Items that open a dialog, and File, Window and Help menu items, are not listed. Stavke koje otvaraju dijalog i stavke menija Datoteka, Prozor i Pomoć nisu navedene. +@msg command must be text command mora biti tekst +@msg no menu item that can be inserted runs this command nijedna stavka menija koja se može umetnuti ne pokreće ovu naredbu +@msg the action already has 10,000 steps akcija već ima 10.000 koraka +@msg the action set would be larger than 8 MiB skup akcija bio bi veći od 8 MiB Playback Options Opcije reprodukcije Accelerated Ubrzano Step by Step Korak po korak @@ -5944,6 +6036,12 @@ axis Y Axis Y osa Crosshair Nišan Checkpoint Kontrolna tačka Inventory Icons Ikone inventara + Skill Icons Ikone vještina + Attack Napad + Defend Odbrana + Heal Iscjeljenje + Buff Pojačanje + Ult Ult Sword Mač Shield Štit Potion Napitak @@ -6008,7 +6106,23 @@ axis Y Axis Y osa Dash Trail Isprekidani trag Speed Line Linija brzine Game Trails Tragovi igre + Energy Beams Energetski snopovi + Laser Bolt Laserski metak + Plasma Arc Plazma luk + Charge Wave Talas naboja + Spark Trail Trag iskri Calligraphic Nibs Kaligrafski vrhovi + Bristle Brushes Četkice s čekinjama + Fine Liner Tanka linija + Pointed Flat Šiljata ravna + Stubby Round Kratka okrugla + Dry Scrub Suho trljanje + Soft Dome Meka kupola + Filbert Ovalna ravna + Angled Round Kosa okrugla + Angled Flat Kosa ravna + Fan Blender Lepeza za stapanje + Grass Fan Lepeza za travu Pattern Borders Ivice od uzoraka Scatter Shapes Raspršeni oblici Save Brush Library… Sačuvaj biblioteku četkica… @@ -6353,6 +6467,12 @@ shape Open Otvoren Delete the selected brushes? Izbrisati odabrane četkice? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? Remove Strokes Ukloni poteze + Place Brush Art Postavi crtež četkice + Replace Brush Art Zamijeni crtež četkice + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Potezi koriste ovu četkicu. Primijeniti novi crtež na te poteze ili ih ostaviti kakvi jesu i dodati kopiju četkice s novim crtežom? + Apply to Strokes Primijeni na poteze + Leave Strokes Ostavi poteze +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` nema crtež (imaju ga samo raspršene i umjetničke četkice i četkice uzorka) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alati za raspoređivanje Arrange in Grid… Rasporedi u mrežu… @@ -6536,6 +6656,11 @@ shape Open Otvoren No importer plug-ins installed Nisu instalirani dodaci za uvoz Read files you open in its format and make documents from them Čitati datoteke koje otvarate u njegovom formatu i od njih praviti dokumente +# Copy Troubleshooting Info + Copy Troubleshooting Info Kopiraj informacije za rješavanje problema +@msg Copied the troubleshooting info Informacije za rješavanje problema kopirane +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Posljednja sesija VectorCrafta prestala je odgovarati prije zatvaranja. Pomoć › Kopiraj informacije za rješavanje problema kopira detalje za prijavu greške + # Safe Mode Safe Mode… Sigurni način rada… Safe Mode Sigurni način rada @@ -6556,6 +6681,8 @@ shape Open Otvoren # Align to Pixel Grid Align to Pixel Grid Poravnaj s mrežom piksela + Align New Objects to Pixel Grid Poravnaj nove objekte s mrežom piksela + Not Aligned to Pixel Grid Nije poravnato s mrežom piksela @msg side is left or right, not `{s}` side je left ili right, a ne `{s}` Edit Custom Dictionary Uredi prilagođeni rječnik Entry: Unos: @@ -6581,6 +6708,26 @@ shape Open Otvoren @plural {n} earlier line dropped|{n} earlier lines dropped {n} raniji red uklonjen|{n} ranija reda uklonjena|{n} ranijih redova uklonjeno @plural {n} line cut|{n} lines cut {n} red skraćen|{n} reda skraćena|{n} redova skraćeno +# Learn panel + Learn Učenje + Explore tutorials Istražite tutorijale + For you Za vas + Skills Vještine + Get started Prvi koraci + Quick skill guide Brzi vodič kroz vještine + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Kratki praktični tutorijali za osnovne alate, grupisani po vještinama. Odaberite vještinu da vidite njene tutorijale. + List Tutorials Izlistaj tutorijale + Show Tutorial Prikaži tutorijal +@msg missing `tutorial` (see learn.list) nedostaje `tutorial` (vidi learn.list) +@msg unknown tutorial `{id}` (see learn.list) nepoznat tutorijal `{id}` (vidi learn.list) + # Deferred plug-in effects Refresh Deferred Effects Osvježi odgođene efekte Deferred Effects Odgođeni efekti + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Alati za rezanje + Stencil Bridges… Mostići šablona… + Stencil Bridges Mostići šablona + Shortest Crossing Najkraći prijelaz + Direction Smjer diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 44562ac0f1..5926045556 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -368,6 +368,11 @@ antiAlias Sharp Nítid Dash Trail Estela discontínua Speed Line Línia de velocitat Game Trails Esteles de joc + Energy Beams Feixos d'energia + Laser Bolt Projectil làser + Plasma Arc Arc de plasma + Charge Wave Ona de càrrega + Spark Trail Estela d'espurnes Art using a deleted global swatch keeps its colour. L’art que utilitza una mostra global suprimida conserva el seu color. Artboard Tauler Artboard Options Opcions del tauler @@ -395,6 +400,7 @@ antiAlias Sharp Nítid Asset Export Settings Configuració d’exportació de recursos Assets Recursos Assign Assigna + Assign Profile Assigna el perfil Assign Profile… Assigna el perfil… Assign: Assigna: Attach Adjunta @@ -456,6 +462,12 @@ antiAlias Sharp Nítid Crosshair Punt de mira Checkpoint Punt de control Inventory Icons Icones d’inventari + Skill Icons Icones d'habilitat + Attack Atac + Defend Defensa + Heal Curació + Buff Potenciació + Ult Ult Sword Espasa Shield Escut Potion Poció @@ -596,6 +608,17 @@ antiAlias Sharp Nítid Calligraphic Brush Pinzell cal·ligràfic Calligraphic Brush Options Opcions del pinzell cal·ligràfic Calligraphic Nibs Plomes cal·ligràfiques + Bristle Brushes Pinzells de cerres + Fine Liner Traç fi + Pointed Flat Pla punxegut + Stubby Round Rodó curt + Dry Scrub Fregat sec + Soft Dome Cúpula suau + Filbert Llengua de gat + Angled Round Rodó bisellat + Angled Flat Pla bisellat + Fan Blender Ventall difuminador + Grass Fan Ventall d'herba Can't export “{name}”. No es pot exportar “{name}”. Can't open “{name}”. No es pot obrir “{name}”. Can't print these settings: see the Summary No es poden imprimir aquests paràmetres: consulta el resum @@ -974,6 +997,15 @@ antiAlias Sharp Nítid CRLF (Windows) CRLF (Windows) Crop Retalla Crop Image Retalla la imatge + Image Tools Eines d’imatge + Remove Background… Elimina el fons… + Remove Background Elimina el fons + Background Fons + Edge Color Color de la vora + Picked Colors Colors triats + Corner Color Color de les cantonades + Contiguous Contigu + Each Channel Cada canal Crop Marks Marques de retall Crop To Retalla fins a Cross Creu @@ -1204,6 +1236,13 @@ antiAlias Sharp Nítid Dock Panel Acobla el panell Dock to Top Acobla a dalt Dock to Bottom Acobla a baix + Control Bar Options Opcions de la barra de control + Tool Options Opcions de l’eina + Object Options Opcions de l’objecte + Image Options Opcions de la imatge + Vertical Alignment Alineació vertical + Align and Distribute Alinea i distribueix + Document Options Opcions del document Dock Control Bar Acobla la barra de control Document Document Document Color Mode Mode de color del document @@ -1545,6 +1584,8 @@ antiAlias Sharp Nítid Extrude & Bevel… Extrudeix i bisella… 3D (Classic) 3D (clàssic) Extrude & Bevel (Classic)… Extrudeix i bisella (clàssic)… + Revolve (Classic)… Revoluciona (clàssic)… + Rotate (Classic)… Gira (clàssic)… Surface Superfície Wireframe Filferro No Shading Sense ombra @@ -1854,6 +1895,7 @@ digits Malayalam Malaiàlam Gridline every Línia de quadrícula cada Gridline every: Línia de quadrícula cada: Grids In Back Quadrícules al darrere + Grit Textures Textures granulades Group Agrupa Group Selection Selecció de grup Group Selection Tool Eina de selecció de grup @@ -1878,6 +1920,14 @@ digits Malayalam Malaiàlam Hand Mà Hand Tool Eina de mà Hand-Drawn Dibuixat a mà + Painted and Sketched Pintat i esbossat + Washed Blue Blau rentat + Bristle Ochre Ocre de cerres + Pastel Heather Bruc pastel + Charcoal Shade Ombra de carbó + Ink Contour Contorn de tinta + Wet Ink Tinta humida + Fine Pen Ploma fina Handles Nanses Hard Dur Hard Light Llum dura @@ -2045,6 +2095,7 @@ digits Malayalam Malaiàlam Include Linked Files Inclou els fitxers enllaçats Include Metadata Inclou les metadades Include non-printing layers Inclou les capes no imprimibles + Write pages longer than 200 in at full size in points Escriu les pàgines de més de 200 in a mida real, en punts Include Objects On Canvas Inclou els objectes del llenç Include SVG Code Inclou codi SVG Include Swatches for Tints Inclou mostres per als tons @@ -2247,6 +2298,11 @@ digits Malayalam Malaiàlam Ligatures are off while the text is tracked. Les lligadures estan desactivades mentre el text té espaiat. Light Clar Light behind the object Llum darrere de l’objecte + Shadows Ombres + Distance from Object Distància de l’objecte + Shadow Bounds Límits de l’ombra + Behind Object Darrere de l’objecte + Below Object Sota l’objecte Light Blue Blau clar Light Red Vermell clar Light Direction Direcció de la llum @@ -2872,12 +2928,23 @@ digits Malayalam Malaiàlam Open… Obre… Optical Òptic Optical Margin Alignment Alineació òptica de marges + Dynamic Text Text dinàmic + Dynamic Text Presets Valors predefinits de text dinàmic + Arch Volta +@msg select point type or type on a path seleccioneu text de punt o text sobre un traçat +@msg type on a path in a thread cannot use Dynamic Text: {frames} el text sobre un traçat d’un text enllaçat no pot fer servir el text dinàmic: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} el text sobre un traçat obert o compost no es pot centrar a dalt o a baix: {open} +@msg type on a path with no length or no height cannot be centered: {flat} el text sobre un traçat sense longitud o sense alçada no es pot centrar: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} el text sobre un traçat d’un text enllaçat no es pot centrar a dalt o a baix: {frames} +@msg select type on a closed path seleccioneu text sobre un traçat tancat Optimize for fast web view Optimitza per a la visualització web ràpida Optimized Optimitzat Options Opcions Options for Selection… Opcions per a la selecció… Options: Opcions: Options… Opcions… + Organic Fades Esvaïments orgànics + Holographic Hologràfics or more spaces with a tab o més espais amb un tabulador Orange Taronja Order: Ordre: @@ -3168,6 +3235,7 @@ digits Malayalam Malaiàlam Press Quality Qualitat d’impressió Pressure Pressió Preview Previsualització + Preview: Previsualització: Preview (1 inch on the page) Previsualització (1 polzada a la pàgina) Preview All Layers Previsualitza totes les capes Preview in Browser Previsualitza al navegador @@ -3251,6 +3319,8 @@ digits Malayalam Malaiàlam Radial Dividers: Divisors radials: Radial Glows Resplendors radials Radial Gradient Degradat radial + Conic Gradient Degradat cònic + Diamond Gradient Degradat de rombe Radial Repeat Repetició radial Radius Radi Radius 1 Radi 1 @@ -3267,6 +3337,8 @@ digits Malayalam Malaiàlam Range: Interval: Raster Effects Efectes de ràster Raster File Format: Format de fitxer de ràster: + Include Placed Images Inclou les imatges col·locades + Include Fill Hatches Inclou les trames dels emplenaments Raster Sample Size: Mida de mostra de ràster: Raster/Vector Balance: Equilibri ràster/vector: Rasterize Rasteritza @@ -3453,6 +3525,10 @@ digits Malayalam Malaiàlam Replace Font Reemplaça el tipus de lletra Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Reemplaça’l per un altre fitxer o ignora’l: les seves imatges continuaran mostrant la previsualització desada amb el document. Replace Spine Reemplaça l’espina + Create Spine Crea l’espina + Create Spine: Crea l’espina: + Always Sempre + Never Mai Replace Symbol Reemplaça el símbol Reset Transformation Restableix la transformació Replace With Font Reemplaça per un tipus de lletra @@ -3572,6 +3648,9 @@ digits Malayalam Malaiàlam Roman Romà Roman Baseline Línia de base romana Roman Hanging Punctuation Puntuació penjant romana + Korean Line Break Anywhere Salt de línia coreà a qualsevol lloc + East Asian Composition Settings Configuració de composició de l’Àsia oriental + Korean Composition Settings Configuració de composició coreana Rotate Gira Rotate 90° CW Gira 90° en sentit horari Rotate Tool Eina de gir @@ -3920,6 +3999,16 @@ digits Malayalam Malaiàlam @msg message must be text message ha de ser text @msg allowContinue must be true or false allowContinue ha de ser true o false @msg Batch cannot play an action with a stop Lot no pot reproduir una acció amb una aturada + Insert Menu Item… Insereix un element de menú… + Insert Menu Item Insereix un element de menú + Menu Item: Element de menú: + No menu item matches. Cap element de menú no coincideix. + Several menu items match. Choose one from the list. Coincideixen diversos elements de menú. Trieu-ne un de la llista. + Items that open a dialog, and File, Window and Help menu items, are not listed. No es mostren els elements que obren un quadre de diàleg ni els elements dels menús Fitxer, Finestra i Ajuda. +@msg command must be text command ha de ser text +@msg no menu item that can be inserted runs this command cap element de menú que es pugui inserir no executa aquesta ordre +@msg the action already has 10,000 steps l’acció ja té 10.000 passos +@msg the action set would be larger than 8 MiB el conjunt d’accions superaria els 8 MiB Playback Options Opcions de reproducció Accelerated Accelerada Step by Step Pas a pas @@ -3962,6 +4051,15 @@ digits Malayalam Malaiàlam Stun Pulse Atordiment Stealth Fade Sigil Shield Buff Escut + Textures Textures + Fine Grain Gra fi + Canvas Weave Teixit de llenç + Burlap Sack Sac de jute + Cracked Glaze Vidrat esquerdat + Mosaic Floor Terra de mosaic + Quilted Squares Quadrats encoixinats + Leaded Glass Vitrall emplomat + Damp Paper Paper humit Shape Forma Shape Builder Constructor de formes Shape Builder Delete Suprimeix del constructor de formes @@ -4042,6 +4140,7 @@ digits Malayalam Malaiàlam Show Modified Mostra els modificats Show Note Mostra la nota Show Options Mostra les opcions + Show Recent Colors Mostra els colors recents Show Original Path Mostra el traçat original Show Package Mostra el paquet Show Panel Mostra el panell @@ -4403,6 +4502,8 @@ digits Malayalam Malaiàlam Scale at Center Escala des del centre Up/Down: Amunt/avall: Left/Right: Esquerra/dreta: + Tate-chu-yoko Up/Down Tate-chu-yoko amunt/avall + Tate-chu-yoko Left/Right Tate-chu-yoko esquerra/dreta Technical Drawing Dibuix tècnic Temperature Temperatura Temperature/Tint… Temperatura/To… @@ -4514,6 +4615,8 @@ digits Malayalam Malaiàlam Toolbar: Add Tool Barra d’eines: afegeix una eina Toolbar: Advanced / Basic Barra d’eines: avançada / bàsica Toolbar: Remove Tool Barra d’eines: suprimeix una eina + Add Tool… Afegeix una eina… + Remove Tool Suprimeix una eina Toolbar: Reset Barra d’eines: restableix Toolbar: Show Controls Barra d’eines: mostra els controls Toolbar: Single/Double Column Barra d’eines: columna simple o doble @@ -4612,6 +4715,8 @@ digits Malayalam Malaiàlam Type on a Path Text sobre un traçat Type on a Path Options Opcions de text sobre un traçat Type on a Path Options… Opcions de text sobre un traçat… + Center on Top Centra a dalt + Center on Bottom Centra a baix Type on a Path Tool Eina de text sobre un traçat Type Optimized Optimitzat per al text Type Orientation Orientació del text @@ -4869,6 +4974,7 @@ digits Malayalam Malaiàlam Words Longer Than: Paraules més llargues de: Working CMYK CMYK de treball Working CMYK (don't tag) CMYK de treball (sense etiquetar) + Working RGB (don't tag) RGB de treball (sense etiquetar) Working RGB RGB de treball Workspace Espai de treball Workspace {i} Espai de treball {i} @@ -4996,6 +5102,8 @@ digits Malayalam Malaiàlam @msg `method` must be classic or perceptual `method` ha de ser classic o perceptual @msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` i `maxAnchors` han de ser nombres enters @msg `mode` applies to freeform gradients `mode` s’aplica als degradats de forma lliure +@msg a negative `aspect` applies to conic gradients un `aspect` negatiu s’aplica als degradats cònics +@msg `focal` applies to radial gradients `focal` s’aplica als degradats radials @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @@ -5005,6 +5113,7 @@ digits Malayalam Malaiàlam @msg `sampleSize` must be 1, 3 or 5 `sampleSize` ha de ser 1, 3 o 5 @msg `select` must be true or false `select` ha de ser true o false @msg `stops` must be an array `stops` ha de ser una matriu +@msg `{key}` must be an array `{key}` ha de ser una matriu @msg `svg` must be an object of SVG options (see document.formats) `svg` ha de ser un objecte d’opcions SVG (vegeu document.formats) @msg `to` must be "corner" or "smooth" `to` ha de ser "corner" o "smooth" @msg `{_1}` has no brushes to apply `{_1}` no té pinzells per aplicar @@ -5025,6 +5134,7 @@ digits Malayalam Malaiàlam @msg `{key}` must be a number not below 0 `{key}` ha de ser un nombre no inferior a 0 @msg `{key}` must be a number, not {v} `{key}` ha de ser un nombre, no {v} @msg `{key}` must be a string `{key}` ha de ser una cadena +@msg `{key}` must be a profile name or null `{key}` ha de ser un nom de perfil o null @msg `{key}` must be a whole number `{key}` ha de ser un nombre enter @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` ha de ser un nombre enter entre {min} i {max} (rebut {x}) @msg `{key}` must be an array of these names: {_1} `{key}` ha de ser una matriu d’aquests noms: {_1} @@ -5326,6 +5436,7 @@ digits Malayalam Malaiàlam @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la pàgina del tauler {n} fa {size}, més que el límit de pàgina del PDF de 14.400 pt (200 in): s’escriu amb un UserUnit de {unit}, de manera que les aplicacions que ignoren UserUnit la mostren tantes vegades més petita @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la pàgina del tauler {n} fa {size}, més que el límit de pàgina del PDF de 14.400 pt (200 in): les pàgines {label} s’escriuen sense UserUnit, en punts, i les aplicacions que respecten el límit retallen la pàgina a 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 el PDF 1.5 no té UserUnit, que una pàgina de més de 14.400 pt (200 in) necessita per mantenir la mida: el fitxer s’escriu com a PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 el PDF 1.4 no té UserUnit, que una pàgina de més de 14.400 pt (200 in) necessita per quedar dins del límit de pàgina de 14.400 unitats del PDF/A-2: el fitxer s’escriu com a PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la pàgina del tauler {n} fa {size}, massa llarga i estreta per als costats de pàgina del PDF de 3 a 14.400 unitats: s'escriu amb una UserUnit de {unit}, que manté el costat curt en 3 unitats o més, i les aplicacions que respecten el límit retallen el costat llarg a 14.400 unitats @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard els fitxers {label} admeten nombres reals fins a {max}, i la pàgina del tauler {n}, de {side} pt, en necessita de més grans: trieu PDF 1.6 o posterior sense estàndard PDF/X, o un tauler més petit @msg Invalid real scale Escala real no vàlida @@ -5518,6 +5629,8 @@ digits Malayalam Malaiàlam @msg no such document no existeix aquest document @msg no such layer or object no existeix aquesta capa o objecte @msg no such object id {value} no existeix l’id d’objecte {value} +@msg id {value} is a ruler guide, not an object l’id {value} és una guia, no un objecte +@msg a ruler guide goes only directly in a layer or sublayer una guia només pot anar directament en una capa o subcapa @msg no such object {0} no existeix l’objecte {0} @msg no such perspective grid preset no existeix aquest preajust de quadrícula de perspectiva @msg no such recent file no existeix aquest fitxer recent @@ -5560,6 +5673,8 @@ digits Malayalam Malaiàlam @msg not a VectorCraft file: {0} no és un fitxer de VectorCraft: {0} @msg not a VectorCraft shortcut set (missing `overrides`) no és un conjunt de dreceres de VectorCraft (falta `overrides`) @msg not an EMF or WMF file no és un fitxer EMF o WMF +@msg not an HP-GL file no és un fitxer HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` ha de ser una matriu d’1 a 255 colors #rrggbb @msg not an RTF file: it doesn't start with {\\rtf no és un fitxer RTF: no comença amb {\\rtf @msg not found no s’ha trobat @msg not in pattern editing mode no esteu en mode d’edició de motius @@ -5710,6 +5825,14 @@ digits Malayalam Malaiàlam @msg exit isolation mode first surt primer del mode d’aïllament @msg select an envelope selecciona un embolcall @msg select an image selecciona una imatge +@msg `background` must be edges, corners or colors `background` ha de ser edges, corners o colors +@msg `match` must be distance or channels `match` ha de ser distance o channels +@msg `{key}` must be from 0 to 100 `{key}` ha d’estar entre 0 i 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` ha de llistar d’1 a 16 colors, cadascun en hexadecimal (#rrggbb o #rgb) o com a black, white, red, green o blue +@msg the linked image shows its preview: embed or relink it first la imatge enllaçada mostra la previsualització: incrusta-la o torna a enllaçar-la primer +@msg a CMYK image has no transparency to set una imatge CMYK no té transparència per establir +@msg every pixel matches the background: no image would be left cada píxel coincideix amb el fons: no quedaria cap imatge +@msg an image of {w} × {h} pixels is too large to change una imatge de {w} × {h} píxels és massa gran per canviar-la @msg select an Image Trace object selecciona un objecte d’Image Trace @msg select an Intertwine group selecciona un grup Intertwine @msg select an object in perspective selecciona un objecte en perspectiva @@ -5750,7 +5873,7 @@ digits Malayalam Malaiàlam @msg span must be "object" or "selection", got {v} span ha de ser "object" o "selection", s’ha rebut {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" col·loca un `gradient`, no una mostra @msg span: "selection" places a gradient: give `gradient` span: "selection" col·loca un degradat: dona `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" col·loca un degradat lineal o radial, no un de lliure +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" col·loca un degradat lineal, radial, cònic o de rombe, no un de lliure @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" col·loca el degradat mateix: omet `start` i `end` (ja el col·loquen en coordenades del document) @msg Split Into Grid: select paths large enough for the grid Divideix en quadrícula: selecciona traçats prou grans per a la quadrícula @msg stop {i} needs `offset` la parada {i} necessita `offset` @@ -5924,7 +6047,7 @@ digits Malayalam Malaiàlam @msg unknown format format desconegut @msg unknown format `{f}` (Save writes {_1}) format desconegut `{f}` (Desa escriu {_1}) @msg unknown freeform mode `{m}` (points, lines) mode de forma lliure desconegut `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) tipus de degradat desconegut `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) tipus de degradat desconegut `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` ressaltat desconegut `{h}` @msg unknown option `{path}.{k}` opció desconeguda `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressions desconegudes `{o}` (preserve, simulate o discard) @@ -5985,7 +6108,13 @@ digits Malayalam Malaiàlam @msg x and y must be provided together cal proporcionar x i y alhora @msg x and y must both be numbers x i y han de ser tots dos nombres @msg Your unsaved changes are kept in this browser: reload the page to get them back. Els canvis no desats es conserven en aquest navegador: torna a carregar la pàgina per recuperar-los. -@msg zipped 32-bit PSD image data with prediction can't be read les dades d’imatge PSD de 32 bits comprimides amb predicció no es poden llegir +@msg zipped 1-bit PSD image data with prediction can't be read les dades d’imatge PSD d’1 bit comprimides amb predicció no es poden llegir +@msg the PSD file's layer data uses an unknown compression ({m}) les dades de capa del fitxer PSD utilitzen una compressió desconeguda ({m}) +@msg the PSD file's layer records are damaged els registres de capes del fitxer PSD estan malmesos +@msg the PSD file's layer groups are nested too deeply els grups de capes del fitxer PSD estan imbricats massa profundament +@msg a layer of the PSD file is too large to read una capa del fitxer PSD és massa gran per llegir-la +@msg the PSD file's layers take more memory to read than allowed les capes del fitxer PSD necessiten més memòria de la permesa per llegir-les +@msg the layers can't be read ({e}): the file opened as its merged image no es poden llegir les capes ({e}): el fitxer s’ha obert com a imatge combinada @msg zone must be a string zone ha de ser una cadena @msg zone must be tab, center, left, right, top or bottom zone ha de ser tab, center, left, right, top o bottom @msg {_1} failed: {e} {_1} ha fallat: {e} @@ -6035,6 +6164,8 @@ digits Malayalam Malaiàlam Version: {version} Versió: {version} Install “{name}” in place of the plug-in with the same ID? Instal·la «{name}» en lloc del complement amb el mateix ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Aquest fitxer no és el complement instal·lat abans amb aquest ID. Rep la configuració i la memòria cau desades per a aquest ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Una automatització ha demanat d’instal·lar aquest complement. Per instal·lar-lo, tria Objecte › Complements › Instal·la el complement… tu mateix. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Una automatització ha demanat d’instal·lar aquest complement. Per instal·lar-lo, tria Objecte › Complements › Instal·la el complement… tu mateix. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees «{name}» és un mòdul diferent del complement amb l’ID {_1} i rebria la configuració i la memòria cau desades per a aquest: instal·la’l amb `replace: true` quan l’usuari hi estigui d’acord File SHA-256: {hash} SHA-256 del fitxer: {hash} Read the objects it is given Llegir els objectes que rep @@ -6080,6 +6211,11 @@ digits Malayalam Malaiàlam @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) pressupost d’objectes (més de {MAX_OBJECTS} objectes de només lectura) +@msg instruction budget pressupost d’instruccions +@msg time budget pressupost de temps +@msg memory budget (the selection is too large to hand over) pressupost de memòria (la selecció és massa gran per passar-la) +@msg output size ({what} is {len} bytes, limit {max}) mida de la sortida ({what} fa {len} bytes, límit {max}) +@msg the plug-in's grant can't be removed from the plug-in store el permís del complement no es pot treure del magatzem de complements @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permís `{shown}` està reservat per a una API de complements posterior; aquest amfitrió no el concedeix @msg unknown permission `{shown}` permís desconegut `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants «{name}» demana els permisos {asked}: una persona els ha d’aprovar a l’aplicació d’escriptori, o passa `grant` en una sessió iniciada amb --allow-plugin-grants @@ -6092,6 +6228,12 @@ digits Malayalam Malaiàlam @msg command {name}: `label` must be 1-64 printable characters ordre {name}: `label` ha de tenir 1-64 caràcters imprimibles @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ordre {name}: fes servir un id d’1-{MAX_COMMAND_ID} caràcters d’a-z 0-9 _ que comenci per una lletra @msg command {name}: {e} ordre {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} (línia {line}, columna {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` ha de ser una llista d’ordres, cadascuna amb `id` i `label` +@msg command {name} must be an object with an `id` and a `label` l’ordre {name} ha de ser un objecte amb `id` i `label` +@msg missing field `{key}` falta el camp `{key}` +@msg duplicate field `{key}` el camp `{key}` està repetit @msg only a filter or a live effect declares `commands` només un filtre o un efecte dinàmic declara `commands` @msg “{name}” › {label}: {e} «{name}» › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed el mòdul no té el SHA-256 que indica `hash`: no s’ha instal·lat res @@ -6361,9 +6503,12 @@ anchor Points: Punts: @msg {label} must be a number {label} ha de ser un nombre @msg {label} must be a number of at least 0.1 {label} ha de ser un nombre de com a mínim 0,1 Advanced Character Formats Formats avançats de caràcters + Basic Paragraph Formats Formats bàsics de paràgraf + Composition Composició Horizontal Scale Escala horitzontal Vertical Scale Escala vertical @msg {label} must be a number from {min} to {max} {label} ha de ser un nombre de {min} a {max} +@msg {label} must be a whole number from {min} to {max} {label} ha de ser un nombre enter de {min} a {max} Character Color Color del caràcter OpenType Features Funcions OpenType Stylistic Sets Jocs estilístics @@ -6371,6 +6516,10 @@ anchor Points: Punts: @msg features lists at most {max} tags features admet com a màxim {max} etiquetes @msg unknown OpenType feature `{t}` funció OpenType desconeguda `{t}` @msg {label} must be a number above 0 and at most {max} {label} ha de ser un nombre superior a 0 i com a màxim {max} +@msg {label} must be at most {max} characters {label} ha de tenir com a màxim {max} caràcters +@msg {label} must be one character {label} ha de ser un sol caràcter +@msg at most {max} tab stops com a màxim {max} tabulacions +@msg unknown align `{other}` alineació desconeguda `{other}` @msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6541,6 +6690,12 @@ breakText Glyphs Glifs Delete the selected brushes? Voleu suprimir els pinzells seleccionats? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? Remove Strokes Elimina els traços + Place Brush Art Col·loca l’art del pinzell + Replace Brush Art Substitueix l’art del pinzell + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Hi ha traços que fan servir aquest pinzell. Voleu aplicar l’art nou a aquests traços, o deixar-los com estan i afegir una còpia del pinzell amb l’art nou? + Apply to Strokes Aplica als traços + Leave Strokes Deixa els traços +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` no té art (només en tenen els pinzells de dispersió, artístics i de motiu) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Eines d’organització Arrange in Grid… Organitza en quadrícula… @@ -6736,6 +6891,11 @@ breakText Glyphs Glifs @msg only an exporter or an importer declares `extensions` només un exportador o un importador declara `extensions` @msg an importer always gets an import's budget: leave `budget` out un importador sempre rep el pressupost d’una importació: ometeu `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Copia la informació de resolució de problemes +@msg Copied the troubleshooting info S’ha copiat la informació de resolució de problemes +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report La darrera sessió del VectorCraft va deixar de respondre abans de tancar-se. Ajuda › Copia la informació de resolució de problemes copia els detalls per a un informe d’error + # Safe Mode Safe Mode… Mode segur… Safe Mode Mode segur @@ -6756,6 +6916,8 @@ breakText Glyphs Glifs # Align to Pixel Grid Align to Pixel Grid Alinea a la quadrícula de píxels + Align New Objects to Pixel Grid Alinea els objectes nous a la quadrícula de píxels + Not Aligned to Pixel Grid No alineat a la quadrícula de píxels @msg only paths and compound paths can be aligned to the pixel grid només els traçats i els traçats compostos es poden alinear a la quadrícula de píxels @msg side is left or right, not `{s}` side ha de ser left o right, no `{s}` Ignore All Ignora-ho tot @@ -6786,8 +6948,33 @@ breakText Glyphs Glifs @plural {n} line cut|{n} lines cut {n} línia tallada|{n} línies tallades @msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` han de ser números de línies que la consola conserva, `first` abans de `last` +# Learn panel + Learn Aprèn + Explore tutorials Explora els tutorials + For you Per a vós + Skills Habilitats + Get started Primers passos + Quick skill guide Guia ràpida d’habilitats + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Tutorials pràctics breus de les eines essencials, agrupats per habilitat. Trieu una habilitat per veure’n els tutorials. + List Tutorials Llista els tutorials + Show Tutorial Mostra el tutorial +@msg missing `tutorial` (see learn.list) falta `tutorial` (vegeu learn.list) +@msg unknown tutorial `{id}` (see learn.list) tutorial desconegut `{id}` (vegeu learn.list) + # Deferred plug-in effects Refresh Deferred Effects Actualitza els efectes ajornats Deferred Effects Efectes ajornats @msg no plug-in effect is deferred no hi ha cap efecte de complement ajornat @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. S’ha obert amb {n} efecte de complement ajornat. Efecte › Actualitza els efectes ajornats l’executa.|S’ha obert amb {n} efectes de complement ajornats. Efecte › Actualitza els efectes ajornats els executa. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Eines de tall + Stencil Bridges… Ponts de plantilla… + Stencil Bridges Ponts de plantilla + Shortest Crossing Travessia més curta + Direction Direcció +@msg The selected art has no islands to bridge La il·lustració seleccionada no té illes per unir +@msg No bridge of this width fits across the selected art Cap pont d’aquesta amplada no cap a la il·lustració seleccionada +@msg Some islands could not be joined to the area around the art Algunes illes no s’han pogut unir a l’àrea que envolta la il·lustració +@msg `width` must be from {lo} to {hi} pt `width` ha d’estar entre {lo} i {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` ha de ser un nombre enter d’1 a {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e42f9bd215..4f751b0a80 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -118,6 +118,7 @@ PDF Presets… Přednastavení PDF… Perspective Grid Presets… Přednastavení perspektivní mřížky… Color Settings… Nastavení barev… + Assign Profile Přiřadit profil Assign Profile… Přiřadit profil… Keyboard Shortcuts… Klávesové zkratky… # Import Shortcut Set (Keyboard Shortcuts › Import…, File › Open of a .kys file) and its commands. @@ -202,6 +203,15 @@ Expand… Rozložit… Expand Appearance Rozložit vzhled Crop Image Oříznout obraz + Image Tools Nástroje obrazu + Remove Background… Odstranit pozadí… + Remove Background Odstranit pozadí + Background Pozadí + Edge Color Barva okraje + Picked Colors Vybrané barvy + Corner Color Barva rohů + Contiguous Souvislé + Each Channel Každý kanál Edit Path Upravit cestu Mask Maska Rasterize… Rastrovat… @@ -252,6 +262,10 @@ Blend Options… Možnosti prolnutí… Expand Rozložit Replace Spine Nahradit páteř + Create Spine Vytvořit páteř + Create Spine: Vytvořit páteř: + Always Vždy + Never Nikdy Reverse Spine Obrátit páteř Reverse Front to Back Obrátit pořadí zepředu dozadu Envelope Distort Deformace obálkou @@ -391,6 +405,8 @@ Stair Step Schody Gravity Gravitace Type on a Path Options… Možnosti textu na cestě… + Center on Top Vystředit nahoře + Center on Bottom Vystředit dole Threaded Text Zřetězený text Create Vytvořit Release Selection Uvolnit výběr @@ -406,6 +422,15 @@ Smart Punctuation… Inteligentní interpunkce… Create Outlines Převést na křivky Optical Margin Alignment Optické zarovnání okrajů + Dynamic Text Dynamický text + Dynamic Text Presets Předvolby dynamického textu + Arch Klenba +@msg select point type or type on a path vyberte bodový text nebo text na cestě +@msg type on a path in a thread cannot use Dynamic Text: {frames} text na cestě ve zřetězeném textu nemůže používat dynamický text: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} text na otevřené nebo složené cestě nelze vystředit nahoře ani dole: {open} +@msg type on a path with no length or no height cannot be centered: {flat} text na cestě bez délky nebo bez výšky nelze vystředit: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} text na cestě ve zřetězeném textu nelze vystředit nahoře ani dole: {frames} +@msg select type on a closed path vyberte text na uzavřené cestě Fill with Placeholder Text Vyplnit zástupným textem Insert Inline Symbol Vložit symbol do textu Show Hidden Characters Zobrazit skryté znaky @@ -477,6 +502,8 @@ Extrude & Bevel… Vysunutí a zkosení… 3D (Classic) 3D (klasické) Extrude & Bevel (Classic)… Vysunutí a zkosení (klasické)… + Revolve (Classic)… Rotační těleso (klasické)… + Rotate (Classic)… Otočit (klasické)… Surface Povrch Wireframe Drátový model No Shading Bez stínování @@ -550,6 +577,7 @@ Gaussian Blur… Gaussovské rozostření… View Zobrazení Preview Náhled + Preview: Náhled: Overprint Preview Náhled přetisků Pixel Preview Náhled obrazových bodů Trim View Oříznuté zobrazení @@ -790,8 +818,25 @@ Stun Pulse Omráčení Stealth Fade Plížení Shield Buff Štít + Textures Textury + Fine Grain Jemné zrno + Canvas Weave Tkané plátno + Burlap Sack Pytlovina + Cracked Glaze Popraskaná glazura + Mosaic Floor Mozaiková podlaha + Quilted Squares Prošívané čtverce + Leaded Glass Olovnaté sklo + Damp Paper Vlhký papír Outlines and Rules Obrysy a linky Hand-Drawn Ručně kreslené + Painted and Sketched Malované a skicované + Washed Blue Rozmytá modrá + Bristle Ochre Okr štětcem + Pastel Heather Pastelový vřes + Charcoal Shade Stín uhlem + Ink Contour Obrys tuší + Wet Ink Mokrá tuš + Fine Pen Jemné pero Gradient Finishes Přechodové povrchy Shape Effects Efekty tvarů Blends and Transparency Prolnutí a průhlednost @@ -811,6 +856,8 @@ Spectrum Gradients Spektrální přechody Sky Gradients Přechody oblohy Neutral Gradients Neutrální přechody + Organic Fades Organické přechody + Holographic Holografické Duotone Gradients Dvoutónové přechody Radial Glows Kruhové záře Save Swatch Library… Uložit knihovnu vzorníku… @@ -872,6 +919,13 @@ Dock Panel Ukotvit panel Dock to Top Ukotvit nahoru Dock to Bottom Ukotvit dolů + Control Bar Options Možnosti ovládacího panelu + Tool Options Možnosti nástroje + Object Options Možnosti objektu + Image Options Možnosti obrazu + Vertical Alignment Svislé zarovnání + Align and Distribute Zarovnat a rozmístit + Document Options Možnosti dokumentu Dock Control Bar Ukotvit ovládací panel Float Tool Group Plovoucí skupina nástrojů @@ -1165,6 +1219,8 @@ lighting Light Světlo Toolbar: Single/Double Column Panel nástrojů: jeden / dva sloupce Toolbar: Add Tool Panel nástrojů: přidat nástroj Toolbar: Remove Tool Panel nástrojů: odebrat nástroj + Add Tool… Přidat nástroj… + Remove Tool Odebrat nástroj Toolbar: Reset Panel nástrojů: obnovit Two Point Perspective Preset 1 Přednastavení dvoubodové perspektivy 1 Two Point Perspective Preset 2 Přednastavení dvoubodové perspektivy 2 @@ -1548,6 +1604,7 @@ digits Malayalam Malajálamské Roman Baseline Latinková účaří Select a text object to edit its character attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho znaků. Show Options Zobrazit možnosti + Show Recent Colors Zobrazit nedávné barvy Color Panel Options Možnosti panelu Barva Small Caps Kapitálky Small Caps (on the roadmap) Kapitálky (v plánu) @@ -1576,6 +1633,8 @@ digits Malayalam Malajálamské Scale at Center Měřítko od středu Up/Down: Nahoru/dolů: Left/Right: Vlevo/vpravo: + Tate-chu-yoko Up/Down Tate-chu-yoko nahoru/dolů + Tate-chu-yoko Left/Right Tate-chu-yoko vlevo/vpravo Underline Podtržení Vertical Scale % Svislá změna velikosti % Axis Osa @@ -1678,6 +1737,8 @@ digits Malayalam Malajálamské No gradient swatches Ve vzorníku nejsou žádné přechody Points: clicks add free points Body: kliknutím přidáte volné body Radial Gradient Kruhový přechod + Conic Gradient Kuželový přechod + Diamond Gradient Kosočtverečný přechod Reset to White, Black Obnovit na bílou a černou Reverse Gradient Obrátit přechod Save to Swatches Uložit do vzorníku @@ -1962,6 +2023,9 @@ digits Malayalam Malajálamské Right Indent Odsazení zprava Right-to-Left Paragraph Direction Směr odstavce zprava doleva Roman Hanging Punctuation Visící latinková interpunkce + Korean Line Break Anywhere Zalomení korejského řádku kdekoli + East Asian Composition Settings Nastavení východoasijské sazby + Korean Composition Settings Nastavení korejské sazby Select a text object to edit its paragraph attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho odstavce. Single-line Composer Sazba jednoho řádku Toggle Line Composer Přepnout sazbu řádků @@ -2048,6 +2112,7 @@ digits Malayalam Malajálamské Simulate Paper Simulovat papír Use Black Point Compensation Použít kompenzaci černého bodu Working CMYK (don't tag) Pracovní CMYK (neoznačovat) + Working RGB (don't tag) Pracovní RGB (neoznačovat) {name} (spot) {name} (přímá) Add to Profiles… Přidat do profilů… Align Stroke to Center Zarovnat tah na střed @@ -2350,6 +2415,8 @@ digits Malayalam Malajálamské Export Selected Art Only Exportovat jen vybranou kresbu Number of Colors: Počet barev: Raster File Format: Formát rastrového souboru: + Include Placed Images Zahrnout umístěné obrazy + Include Fill Hatches Zahrnout šrafy výplní True colour needs version 2004 or later: the nearest of 256 colours is written. Plné barvy vyžadují verzi 2004 nebo novější: zapíše se nejbližší z 256 barev. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Text se převede na křivky a tahy, které čára CAD nedokáže vykreslit, se stanou vyplněnými tvary. Type stays text, and every stroke is a line with its lineweight and dashes. Text zůstane textem a každý tah bude čárou s vlastní tloušťkou a čárkováním. @@ -2908,6 +2975,7 @@ antiAlias Sharp Ostré General › Thumbnails Obecné › Miniatury Grayscale images Obrazy ve stupních šedi Include non-printing layers Zahrnout netisknutelné vrstvy + Write pages longer than 200 in at full size in points Zapsat stránky delší než 200 in v plné velikosti v bodech Left: Vlevo: Mark as trapped Označit jako s přesahy barev Marks and Bleeds Značky a spadávky @@ -4506,10 +4574,13 @@ imageTrace Outline Obrys @msg `groupColors` must be an array `groupColors` musí být pole @msg `library` is a library id or name (see {list}) `library` je ID nebo název knihovny (viz {list}) @msg `mode` applies to freeform gradients `mode` platí pro volné přechody +@msg a negative `aspect` applies to conic gradients záporný `aspect` platí pro kuželové přechody +@msg `focal` applies to radial gradients `focal` platí pro radiální přechody @msg `preserve` must be an object `preserve` musí být objekt @msg `globalAdjust` must be an object `globalAdjust` musí být objekt @msg `sampleSize` must be 1, 3 or 5 `sampleSize` musí být 1, 3 nebo 5 @msg `stops` must be an array `stops` musí být pole +@msg `{key}` must be an array `{key}` musí být pole @msg `svg` must be an object of SVG options (see document.formats) `svg` musí být objekt s možnostmi SVG (viz document.formats) @msg `{_1}` is no save command `{_1}` není příkaz pro uložení @msg `{area}` is no recovery area name `{area}` není název oblasti obnovení @@ -4523,6 +4594,7 @@ imageTrace Outline Obrys @msg `{key}` must be a number, not {v} `{key}` musí být číslo, ne {v} @msg {key} must be Unix seconds (an integer) or null {key} musí být unixový čas v sekundách (celé číslo) nebo null @msg `{key}` must be a string `{key}` musí být řetězec +@msg `{key}` must be a profile name or null `{key}` musí být název profilu nebo null @msg `{key}` must be a whole number `{key}` musí být celé číslo @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` musí být celé číslo mezi {min} a {max} (zadáno {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` musí být mezi {min} a {max} (zadáno {x}) @@ -4675,6 +4747,7 @@ imageTrace Outline Obrys @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller stránka pracovní plochy {n} má {size}, což přesahuje limit stránky PDF 14 400 pt (200 in): zapisuje se s UserUnit {unit}, takže aplikace, které UserUnit ignorují, ji zobrazí tolikrát menší @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in stránka pracovní plochy {n} má {size}, což přesahuje limit stránky PDF 14 400 pt (200 in): stránky {label} se zapisují bez UserUnit, v bodech, a aplikace, které limit dodržují, stránku oříznou na 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 nemá UserUnit, který stránka delší než 14 400 pt (200 in) potřebuje, aby si zachovala velikost: soubor se zapíše jako PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 nemá UserUnit, který stránka delší než 14 400 pt (200 in) potřebuje, aby zůstala v limitu stránky PDF/A-2, 14 400 jednotek: soubor se zapíše jako PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units stránka pracovní plochy {n} má rozměr {size} a je příliš dlouhá a úzká pro strany stránky PDF od 3 do 14 400 jednotek: zapisuje se s UserUnit {unit}, která drží kratší stranu na 3 jednotkách nebo více, a aplikace, které limit dodržují, ořežou delší stranu na 14 400 jednotek @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard soubory {label} pojmou reálná čísla nejvýše {max} a stránka pracovní plochy {n}, dlouhá {side} pt, potřebuje větší: zvolte PDF 1.6 nebo novější bez standardu PDF/X, nebo menší pracovní plochu @msg invalid image data for `{0}` neplatná obrazová data pro `{0}` @@ -4822,6 +4895,8 @@ imageTrace Outline Obrys @msg not a stored central record nejde o uložený centrální záznam @msg not a valid plug-in module: {0} neplatný modul zásuvného modulu: {0} @msg not an EMF or WMF file nejde o soubor EMF ani WMF +@msg not an HP-GL file nejde o soubor HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` musí být pole 1 až 255 barev #rrggbb @msg not found nenalezeno @msg not in pattern editing mode není aktivní režim úprav vzorku @msg finish editing the pattern first nejprve dokončete úpravy vzorku @@ -4901,6 +4976,14 @@ imageTrace Outline Obrys @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 tato vektorizace by vytvořila více než {max} kotevních bodů, víc, než dokument plynule zobrazí: zvyšte Šum, snižte Cesty nebo Barvy, nebo zvolte přednastavení s nižší věrností @msg select an envelope vyberte obálku @msg select an image vyberte obraz +@msg `background` must be edges, corners or colors `background` musí být edges, corners nebo colors +@msg `match` must be distance or channels `match` musí být distance nebo channels +@msg `{key}` must be from 0 to 100 `{key}` musí být od 0 do 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` musí obsahovat 1 až 16 barev, každou šestnáctkově (#rrggbb nebo #rgb) nebo jako black, white, red, green či blue +@msg the linked image shows its preview: embed or relink it first propojený obraz zobrazuje náhled: nejprve jej vložte nebo znovu propojte +@msg a CMYK image has no transparency to set obraz CMYK nemá průhlednost, kterou by bylo možné nastavit +@msg every pixel matches the background: no image would be left každý obrazový bod odpovídá pozadí: nezbyl by žádný obraz +@msg an image of {w} × {h} pixels is too large to change obraz o velikosti {w} × {h} obrazových bodů je příliš velký na změnu @msg select an object in perspective vyberte objekt v perspektivě @msg select artwork (or a colour group) to recolor vyberte kresbu (nebo skupinu barev) k přebarvení @msg Recolor completed; {locked} and {hidden} were left unchanged Přebarvení dokončeno; beze změny: {locked} a {hidden} @@ -5007,7 +5090,7 @@ imageTrace Outline Obrys @msg unknown format neznámý formát @msg unknown format `{f}` (Save writes {_1}) neznámý formát `{f}` (Uložit zapisuje {_1}) @msg unknown freeform mode `{m}` (points, lines) neznámý režim volného přechodu `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) neznámý druh přechodu `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) neznámý druh přechodu `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` neznámé zvýraznění `{h}` @msg unknown option `{path}.{k}` neznámá možnost `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) neznámé přetisky `{o}` (preserve, simulate nebo discard) @@ -5207,6 +5290,8 @@ imageTrace Outline Obrys @msg invalid object id {value}: expected a non-negative integer neplatné ID objektu {value}: očekává se nezáporné celé číslo @msg `{key}` entry {index} is {value}, not a non-negative integer object id položka {index} v `{key}` je {value}, nikoli ID objektu (nezáporné celé číslo) @msg no such object id {value} objekt s ID {value} neexistuje +@msg id {value} is a ruler guide, not an object ID {value} patří vodítku, ne objektu +@msg a ruler guide goes only directly in a layer or sublayer vodítko může být jen přímo ve vrstvě nebo podvrstvě @msg id {value} is a layer, not an object ID {value} je vrstva, nikoli objekt @msg id {value} is a layer, not an object; move layers with layer.move ID {value} je vrstva, nikoli objekt; vrstvy přesunete pomocí layer.move @msg automation filesystem access is not granted: read authority is absent: {path} přístup automatizace k systému souborů není udělen: chybí oprávnění ke čtení: {path} @@ -5236,7 +5321,13 @@ imageTrace Outline Obrys @msg the HEIC or HEIF file holds a kind of image that can't be read soubor HEIC nebo HEIF obsahuje druh obrázku, který nelze přečíst @msg HEIC and HEIF images can't be opened in this build obrázky HEIC a HEIF nelze v tomto sestavení otevřít @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD je příliš velký na přečtení ({_1} × {_2} obrazových bodů) -@msg zipped 32-bit PSD image data with prediction can't be read zazipovaná 32bitová obrazová data PSD s predikcí nelze přečíst +@msg zipped 1-bit PSD image data with prediction can't be read zazipovaná 1bitová obrazová data PSD s predikcí nelze přečíst +@msg the PSD file's layer data uses an unknown compression ({m}) data vrstev souboru PSD používají neznámou kompresi ({m}) +@msg the PSD file's layer records are damaged záznamy vrstev souboru PSD jsou poškozené +@msg the PSD file's layer groups are nested too deeply skupiny vrstev souboru PSD jsou vnořené příliš hluboko +@msg a layer of the PSD file is too large to read vrstva souboru PSD je příliš velká na přečtení +@msg the PSD file's layers take more memory to read than allowed vrstvy souboru PSD potřebují ke čtení víc paměti, než je povoleno +@msg the layers can't be read ({e}): the file opened as its merged image vrstvy nelze přečíst ({e}): soubor se otevřel jako sloučený obraz @msg {depth}-bit PSD files in this colour mode can't be read {depth}bitové soubory PSD v tomto barevném režimu nelze přečíst @msg the PSD file is cut short soubor PSD je useknutý @msg the PSD file's header is damaged hlavička souboru PSD je poškozená @@ -5704,6 +5795,11 @@ mark-style Japanese Japonské Softness Měkkost Ambient Light Okolní světlo Light behind the object Světlo za objektem + Shadows Stíny + Distance from Object Vzdálenost od objektu + Shadow Bounds Hranice stínu + Behind Object Za objektem + Below Object Pod objektem 3D Lighting Preset Předvolba 3D osvětlení Standard Standardní Diffuse Rozptýlené @@ -5768,7 +5864,7 @@ mark-style Japanese Japonské @msg span must be "object" or "selection", got {v} span musí být "object" nebo "selection", ne {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" umísťuje `gradient`, ne vzorník @msg span: "selection" places a gradient: give `gradient` span: "selection" umísťuje přechod: zadejte `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" umísťuje lineární nebo radiální přechod, ne volný přechod +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" umísťuje lineární, radiální, kuželový nebo kosočtverečný přechod, ne volný přechod @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" umísťuje samotný přechod: vynechte `start` a `end` (ty ho už umísťují v souřadnicích dokumentu) Make Image Dynamic Nastavit obraz jako dynamický Import Data Sets… Importovat sady dat… @@ -5951,6 +6047,7 @@ mark-style Japanese Japonské Ruby Ruby Geometric Guides Geometrická vodítka Geometric Patterns Geometrické vzorky + Grit Textures Zrnité textury Ease In Pozvolný začátek Ease Out Pozvolný konec Ease In Out Pozvolný začátek a konec @@ -6009,6 +6106,8 @@ axis Y Axis osa Y Version: {version} Verze: {version} Install “{name}” in place of the plug-in with the same ID? Nainstalovat „{name}“ místo zásuvného modulu se stejným ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tento soubor není zásuvný modul dříve nainstalovaný s tímto ID. Získá nastavení a mezipaměť uchovávané pro toto ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. O instalaci tohoto zásuvného modulu požádala automatizace. Chcete-li ho nainstalovat, zvolte Objekt › Zásuvné moduly › Nainstalovat zásuvný modul… sami. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. O instalaci tohoto zásuvného modulu požádala automatizace. Chcete-li ho nainstalovat, zvolte Objekt › Zásuvné moduly › Nainstalovat zásuvný modul… sami. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}“ je jiný modul než zásuvný modul s ID {_1} a získal by nastavení a mezipaměť uchovávané pro něj: nainstalujte ho s `replace: true`, jakmile uživatel souhlasí File SHA-256: {hash} SHA-256 souboru: {hash} Read the objects it is given Číst objekty, které dostane @@ -6054,6 +6153,11 @@ axis Y Axis osa Y @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) rozpočet objektů (více než {MAX_OBJECTS} objektů jen pro čtení) +@msg instruction budget rozpočet instrukcí +@msg time budget časový rozpočet +@msg memory budget (the selection is too large to hand over) rozpočet paměti (výběr je příliš velký na předání) +@msg output size ({what} is {len} bytes, limit {max}) velikost výstupu ({what} má {len} bajtů, limit {max}) +@msg the plug-in's grant can't be removed from the plug-in store oprávnění zásuvného modulu nelze odebrat z úložiště zásuvných modulů @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it oprávnění `{shown}` je vyhrazeno pro pozdější API zásuvných modulů; tento hostitel ho neuděluje @msg unknown permission `{shown}` neznámé oprávnění `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ žádá o oprávnění {asked}: musí je schválit člověk v desktopové aplikaci, nebo předejte `grant` v relaci spuštěné s --allow-plugin-grants @@ -6066,6 +6170,12 @@ axis Y Axis osa Y @msg command {name}: `label` must be 1-64 printable characters příkaz {name}: `label` musí mít 1-64 tisknutelných znaků @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter příkaz {name}: použijte id o 1-{MAX_COMMAND_ID} znacích z a-z 0-9 _, které začíná písmenem @msg command {name}: {e} příkaz {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} (řádek {line}, sloupec {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` musí být seznam příkazů, každý s `id` a `label` +@msg command {name} must be an object with an `id` and a `label` příkaz {name} musí být objekt s `id` a `label` +@msg missing field `{key}` chybí pole `{key}` +@msg duplicate field `{key}` pole `{key}` je uvedeno dvakrát @msg only a filter or a live effect declares `commands` `commands` deklaruje jen filtr nebo živý efekt @msg “{name}” › {label}: {e} „{name}“ › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modul nemá SHA-256 uvedený v `hash`: nic nebylo nainstalováno @@ -6090,6 +6200,16 @@ axis Y Axis osa Y @msg message must be text message musí být text @msg allowContinue must be true or false allowContinue musí být true nebo false @msg Batch cannot play an action with a stop Dávka nemůže přehrát akci se zastavením + Insert Menu Item… Vložit položku nabídky… + Insert Menu Item Vložit položku nabídky + Menu Item: Položka nabídky: + No menu item matches. Žádná položka nabídky neodpovídá. + Several menu items match. Choose one from the list. Odpovídá několik položek nabídky. Vyberte jednu ze seznamu. + Items that open a dialog, and File, Window and Help menu items, are not listed. Položky, které otevírají dialogové okno, a položky nabídek Soubor, Okno a Nápověda nejsou uvedeny. +@msg command must be text command musí být text +@msg no menu item that can be inserted runs this command tento příkaz nespouští žádná položka nabídky, kterou lze vložit +@msg the action already has 10,000 steps akce už má 10 000 kroků +@msg the action set would be larger than 8 MiB sada akcí by byla větší než 8 MiB Playback Options Možnosti přehrávání Accelerated Zrychleně Step by Step Krok za krokem @@ -6128,6 +6248,12 @@ axis Y Axis osa Y Crosshair Zaměřovač Checkpoint Kontrolní bod Inventory Icons Ikony inventáře + Skill Icons Ikony dovedností + Attack Útok + Defend Obrana + Heal Léčení + Buff Posílení + Ult Ult Sword Meč Shield Štít Potion Lektvar @@ -6192,7 +6318,23 @@ axis Y Axis osa Y Dash Trail Čárkovaná stopa Speed Line Rychlostní čára Game Trails Herní stopy + Energy Beams Energetické paprsky + Laser Bolt Laserový výstřel + Plasma Arc Plazmový oblouk + Charge Wave Nabíjecí vlna + Spark Trail Jiskrová stopa Calligraphic Nibs Kaligrafická pera + Bristle Brushes Štětinové štětce + Fine Liner Jemná linka + Pointed Flat Špičatý plochý + Stubby Round Krátký kulatý + Dry Scrub Suché drhnutí + Soft Dome Měkká kopule + Filbert Plochý oválný + Angled Round Šikmý kulatý + Angled Flat Šikmý plochý + Fan Blender Vějíř na prolínání + Grass Fan Vějíř na trávu Pattern Borders Vzorkové okraje Scatter Shapes Rozptýlené tvary Save Brush Library… Uložit knihovnu štětců… @@ -6389,9 +6531,12 @@ anchor Points: Body: @msg {label} must be a number {label} musí být číslo @msg {label} must be a number of at least 0.1 {label} musí být číslo alespoň 0,1 Advanced Character Formats Rozšířené formáty znaků + Basic Paragraph Formats Základní formáty odstavce + Composition Sazba Horizontal Scale Vodorovná změna velikosti Vertical Scale Svislá změna velikosti @msg {label} must be a number from {min} to {max} {label} musí být číslo od {min} do {max} +@msg {label} must be a whole number from {min} to {max} {label} musí být celé číslo od {min} do {max} Character Color Barva znaků OpenType Features Funkce OpenType Stylistic Sets Stylistické sady @@ -6399,6 +6544,10 @@ anchor Points: Body: @msg features lists at most {max} tags features obsahuje nejvýše {max} značek @msg unknown OpenType feature `{t}` neznámá funkce OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musí být číslo větší než 0 a nejvýše {max} +@msg {label} must be at most {max} characters {label} smí mít nejvýše {max} znaků +@msg {label} must be one character {label} musí být jeden znak +@msg at most {max} tab stops nejvýše {max} zarážek tabulátoru +@msg unknown align `{other}` neznámé zarovnání `{other}` @msg no character style `{name}` styl znaků `{name}` neexistuje # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6560,6 +6709,12 @@ breakText Glyphs Glyfy Delete the selected brushes? Odstranit vybrané štětce? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Tahy používají jeden nebo více z těchto štětců. Odebrat štětce z těchto tahů a odstranit štětce? Remove Strokes Odebrat tahy + Place Brush Art Umístit kresbu štětce + Replace Brush Art Nahradit kresbu štětce + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Tahy používají tento štětec. Použít novou kresbu na tyto tahy, nebo je ponechat beze změny a přidat kopii štětce s novou kresbou? + Apply to Strokes Použít na tahy + Leave Strokes Ponechat tahy +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` nemá kresbu (mají ji jen rozptylové, obrazové a vzorkové štětce) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Nástroje uspořádání Arrange in Grid… Uspořádat do mřížky… @@ -6755,6 +6910,11 @@ breakText Glyphs Glyfy @msg only an exporter or an importer declares `extensions` `extensions` deklaruje jen exportní nebo importní zásuvný modul @msg an importer always gets an import's budget: leave `budget` out importní zásuvný modul dostává vždy rozpočet importu: vynechte `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Kopírovat informace pro řešení potíží +@msg Copied the troubleshooting info Informace pro řešení potíží zkopírovány +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Poslední relace VectorCraftu přestala odpovídat, než se zavřela. Nápověda › Kopírovat informace pro řešení potíží zkopíruje podrobnosti pro hlášení chyby + # Safe Mode Safe Mode… Nouzový režim… Safe Mode Nouzový režim @@ -6775,6 +6935,8 @@ breakText Glyphs Glyfy # Align to Pixel Grid Align to Pixel Grid Zarovnat na mřížku obrazových bodů + Align New Objects to Pixel Grid Zarovnat nové objekty na mřížku obrazových bodů + Not Aligned to Pixel Grid Nezarovnané na mřížku obrazových bodů @msg only paths and compound paths can be aligned to the pixel grid na mřížku obrazových bodů lze zarovnat jen cesty a složené cesty @msg side is left or right, not `{s}` side je left nebo right, ne `{s}` Ignore All Ignorovat vše @@ -6805,8 +6967,33 @@ breakText Glyphs Glyfy @plural {n} line cut|{n} lines cut {n} řádek zkrácen|{n} řádky zkráceny|{n} řádků zkráceno @msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last` +# Learn panel + Learn Výuka + Explore tutorials Prozkoumat výukové kurzy + For you Pro vás + Skills Dovednosti + Get started Začínáme + Quick skill guide Rychlý průvodce dovednostmi + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Krátké praktické výukové kurzy k základním nástrojům, seřazené podle dovedností. Vyberte dovednost a zobrazí se její kurzy. + List Tutorials Vypsat výukové kurzy + Show Tutorial Zobrazit výukový kurz +@msg missing `tutorial` (see learn.list) chybí `tutorial` (viz learn.list) +@msg unknown tutorial `{id}` (see learn.list) neznámý výukový kurz `{id}` (viz learn.list) + # Deferred plug-in effects Refresh Deferred Effects Obnovit odložené efekty Deferred Effects Odložené efekty @msg no plug-in effect is deferred žádný efekt zásuvného modulu není odložen @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Otevřeno s {n} odloženým efektem zásuvného modulu. Efekt › Obnovit odložené efekty jej spustí.|Otevřeno s {n} odloženými efekty zásuvných modulů. Efekt › Obnovit odložené efekty je spustí.|Otevřeno s {n} odloženými efekty zásuvných modulů. Efekt › Obnovit odložené efekty je spustí. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Nástroje pro řezání + Stencil Bridges… Můstky šablony… + Stencil Bridges Můstky šablony + Shortest Crossing Nejkratší přechod + Direction Směr +@msg The selected art has no islands to bridge Vybraná kresba nemá žádné ostrůvky k přemostění +@msg No bridge of this width fits across the selected art Přes vybranou kresbu se nevejde žádný můstek této šířky +@msg Some islands could not be joined to the area around the art Některé ostrůvky nebylo možné připojit k oblasti kolem kresby +@msg `width` must be from {lo} to {hi} pt `width` musí být od {lo} do {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musí být celé číslo od 1 do {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cf7aa67b3f..b5beaf4805 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -106,6 +106,7 @@ PDF Presets… PDF-forudindstillinger… Perspective Grid Presets… Forudindstillinger for perspektivgitter… Color Settings… Farveindstillinger… + Assign Profile Tildel profil Assign Profile… Tildel profil… Keyboard Shortcuts… Tastaturgenveje… Import Shortcut Set Importér genvejssæt @@ -189,6 +190,15 @@ Expand… Udvid… Expand Appearance Udvid udseende Crop Image Beskær billede + Image Tools Billedværktøjer + Remove Background… Fjern baggrund… + Remove Background Fjern baggrund + Background Baggrund + Edge Color Kantfarve + Picked Colors Valgte farver + Corner Color Hjørnefarve + Contiguous Sammenhængende + Each Channel Hver kanal Edit Path Redigér kurve Mask Maskér Rasterize… Rasterisér… @@ -238,6 +248,10 @@ Blend Options… Blandingsindstillinger… Expand Udvid Replace Spine Erstat rygrad + Create Spine Opret rygrad + Create Spine: Opret rygrad: + Always Altid + Never Aldrig Reverse Spine Omvend rygrad Reverse Front to Back Omvend fortil og bagtil Envelope Distort Kuvertforvrængning @@ -352,6 +366,8 @@ Stair Step Trappetrin Gravity Tyngdekraft Type on a Path Options… Indstillinger for tekst på kurve… + Center on Top Centrer øverst + Center on Bottom Centrer nederst Threaded Text Sammenkædet tekst Create Opret Release Selection Frigør markering @@ -367,6 +383,9 @@ Smart Punctuation… Smart tegnsætning… Create Outlines Opret konturer Optical Margin Alignment Optisk marginjustering + Dynamic Text Dynamisk tekst + Dynamic Text Presets Forudindstillinger for dynamisk tekst + Arch Hvælving Fill with Placeholder Text Udfyld med pladsholdertekst Insert Inline Symbol Indsæt indlejret symbol Show Hidden Characters Vis skjulte tegn @@ -437,6 +456,8 @@ Extrude & Bevel… Ekstrudér og facet… 3D (Classic) 3D (klassisk) Extrude & Bevel (Classic)… Ekstrudér og facet (klassisk)… + Revolve (Classic)… Omdrej (klassisk)… + Rotate (Classic)… Rotér (klassisk)… Surface Overflade Wireframe Trådmodel No Shading Ingen skyggelægning @@ -507,6 +528,7 @@ Gaussian Blur… Gaussisk sløring… View Vis Preview Forhåndsvisning + Preview: Forhåndsvisning: Overprint Preview Overprint-forhåndsvisning Pixel Preview Pixel-forhåndsvisning Trim View Beskåret visning @@ -729,8 +751,25 @@ Stun Pulse Bedøvelse Stealth Fade Snige Shield Buff Skjold + Textures Teksturer + Fine Grain Fin kornethed + Canvas Weave Lærredsvævning + Burlap Sack Jutesæk + Cracked Glaze Krakeleret glasur + Mosaic Floor Mosaikgulv + Quilted Squares Quiltede firkanter + Leaded Glass Blyindfattet glas + Damp Paper Fugtigt papir Outlines and Rules Konturer og linjer Hand-Drawn Håndtegnet + Painted and Sketched Malet og skitseret + Washed Blue Udvasket blå + Bristle Ochre Børsteokker + Pastel Heather Pastellyng + Charcoal Shade Kulskygge + Ink Contour Blækkontur + Wet Ink Vådt blæk + Fine Pen Fin pen Gradient Finishes Gradientfinish Shape Effects Formeffekter Blends and Transparency Blandinger og gennemsigtighed @@ -750,6 +789,8 @@ Spectrum Gradients Spektrumgradienter Sky Gradients Himmelgradienter Neutral Gradients Neutrale gradienter + Organic Fades Organiske toninger + Holographic Holografiske Duotone Gradients Duotonegradienter Radial Glows Radiale gløder Save Swatch Library… Gem bibliotek med farveprøver… @@ -808,6 +849,13 @@ Dock Panel Dok panel Dock to Top Dok øverst Dock to Bottom Dok nederst + Control Bar Options Indstillinger for kontrollinjen + Tool Options Værktøjsindstillinger + Object Options Objektindstillinger + Image Options Billedindstillinger + Vertical Alignment Lodret justering + Align and Distribute Justér og fordel + Document Options Dokumentindstillinger Dock Control Bar Dok kontrollinjen Float Tool Group Flydende værktøjsgruppe Services Tjenester @@ -1082,6 +1130,8 @@ lighting Light Lys Toolbar: Single/Double Column Værktøjslinje: Enkelt/dobbelt kolonne Toolbar: Add Tool Værktøjslinje: Tilføj værktøj Toolbar: Remove Tool Værktøjslinje: Fjern værktøj + Add Tool… Tilføj værktøj… + Remove Tool Fjern værktøj Toolbar: Reset Værktøjslinje: Nulstil Two Point Perspective Preset 1 2-punkts perspektivforudindstilling 1 Two Point Perspective Preset 2 2-punkts perspektivforudindstilling 2 @@ -1461,6 +1511,7 @@ digits Malayalam Malayalam Roman Baseline Romersk grundlinje Select a text object to edit its character attributes. Markér et tekstobjekt for at redigere dets tegnattributter. Show Options Vis indstillinger + Show Recent Colors Vis seneste farver Small Caps Kapitæler Small Caps (on the roadmap) Kapitæler (på vejkortet) Standard Vertical Roman Alignment Standard lodret romersk justering @@ -1488,6 +1539,8 @@ digits Malayalam Malayalam Scale at Center Skalér fra midten Up/Down: Op/ned: Left/Right: Venstre/højre: + Tate-chu-yoko Up/Down Tate-chu-yoko op/ned + Tate-chu-yoko Left/Right Tate-chu-yoko venstre/højre Underline Understreget Vertical Scale % Lodret skalering % Axis Akse @@ -1590,6 +1643,8 @@ digits Malayalam Malayalam No gradient swatches Ingen gradientfarveprøver Points: clicks add free points Punkter: klik tilføjer frie punkter Radial Gradient Radial gradient + Conic Gradient Konisk gradient + Diamond Gradient Diamantgradient Reset to White, Black Nulstil til hvid, sort Reverse Gradient Omvend gradient Save to Swatches Gem i farveprøver @@ -1770,6 +1825,9 @@ digits Malayalam Malayalam Right Indent Højre indrykning Right-to-Left Paragraph Direction Afsnitsretning fra højre mod venstre Roman Hanging Punctuation Romersk hængende tegnsætning + Korean Line Break Anywhere Koreansk linjeskift hvor som helst + East Asian Composition Settings Indstillinger for østasiatisk komposition + Korean Composition Settings Indstillinger for koreansk komposition Select a text object to edit its paragraph attributes. Markér et tekstobjekt for at redigere dets afsnitsattributter. Single-line Composer Enlinjesætter Toggle Line Composer Skift linjesætter @@ -1856,6 +1914,7 @@ digits Malayalam Malayalam Simulate Paper Simulér papir Use Black Point Compensation Brug sortpunktskompensation Working CMYK (don't tag) Arbejds-CMYK (mærk ikke) + Working RGB (don't tag) Arbejds-RGB (mærk ikke) {name} (spot) {name} (spotfarve) Add to Profiles… Tilføj til profiler… Align Stroke to Center Justér kontur til midten @@ -2155,6 +2214,8 @@ digits Malayalam Malayalam Export Selected Art Only Eksportér kun markeret grafik Number of Colors: Antal farver: Raster File Format: Rasterfilformat: + Include Placed Images Medtag placerede billeder + Include Fill Hatches Medtag skraveringer af udfyldninger True colour needs version 2004 or later: the nearest of 256 colours is written. Ægte farve kræver version 2004 eller senere: den nærmeste af 256 farver skrives. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Tekst bliver til omrids, og konturer, som en CAD-linje ikke kan tegne, bliver til udfyldte figurer. Type stays text, and every stroke is a line with its lineweight and dashes. Tekst forbliver tekst, og hver kontur er en linje med sin linjevægt og streger. @@ -2698,6 +2759,7 @@ antiAlias Sharp Skarp General › Thumbnails Generelt › Miniaturer Grayscale images Gråtonebilleder Include non-printing layers Medtag lag, der ikke udskrives + Write pages longer than 200 in at full size in points Skriv sider længere end 200 in i fuld størrelse i punkter Left: Venstre: Mark as trapped Markér som trappet Marks and Bleeds Mærker og udløb @@ -4183,6 +4245,8 @@ imageTrace Outline Kontur @msg `gradient` must be an object `gradient` skal være et objekt @msg `library` is a library id or name (see {list}) `library` er et biblioteks-id eller -navn (se {list}) @msg `mode` applies to freeform gradients `mode` gælder for freeform-gradienter +@msg a negative `aspect` applies to conic gradients et negativt `aspect` gælder for koniske gradienter +@msg `focal` applies to radial gradients `focal` gælder for radiale gradienter @msg `sampleSize` must be 1, 3 or 5 `sampleSize` skal være 1, 3 eller 5 @msg `stops` must be an array `stops` skal være et array @msg `svg` must be an object of SVG options (see document.formats) `svg` skal være et objekt med SVG-indstillinger (se document.formats) @@ -4451,6 +4515,8 @@ imageTrace Outline Kontur @msg not a stored central record ikke en gemt central post @msg not a valid plug-in module: {0} ikke et gyldigt plug-in-modul: {0} @msg not an EMF or WMF file ikke en EMF- eller WMF-fil +@msg not an HP-GL file ikke en HP-GL-fil +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` skal være et array af 1 til 255 #rrggbb-farver @msg not found ikke fundet @msg not in pattern editing mode ikke i mønsterredigeringstilstand @msg finish editing the pattern first afslut først redigeringen af mønsteret @@ -4618,7 +4684,7 @@ imageTrace Outline Kontur @msg unknown format ukendt format @msg unknown format `{f}` (Save writes {_1}) ukendt format `{f}` (Gem skriver {_1}) @msg unknown freeform mode `{m}` (points, lines) ukendt freeform-tilstand `{m}` (punkter, linjer) -@msg unknown gradient kind `{k}` (linear, radial, freeform) ukendt gradienttype `{k}` (lineær, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) ukendt gradienttype `{k}` (lineær, radial, konisk, diamant, freeform) @msg unknown highlight `{h}` ukendt fremhævning `{h}` @msg unknown option `{path}.{k}` ukendt indstilling `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ukendt overprint `{o}` (bevar, simulér eller forkast) @@ -4802,6 +4868,8 @@ imageTrace Outline Kontur @msg invalid object id {value}: expected a non-negative integer ugyldigt objekt-id {value}: et ikke-negativt heltal var forventet @msg `{key}` entry {index} is {value}, not a non-negative integer object id element {index} i `{key}` er {value}, ikke et objekt-id (et ikke-negativt heltal) @msg no such object id {value} der findes intet objekt med id {value} +@msg id {value} is a ruler guide, not an object id {value} er en hjælpelinje, ikke et objekt +@msg a ruler guide goes only directly in a layer or sublayer en hjælpelinje kan kun ligge direkte i et lag eller underlag @msg automation filesystem access is not granted: read authority is absent: {path} automatiseringens adgang til filsystemet er ikke tildelt: læserettighed mangler: {path} @msg automation filesystem access is not granted: write authority is absent: {path} automatiseringens adgang til filsystemet er ikke tildelt: skriverettighed mangler: {path} @msg automation path rejected: outside the read root {root}: {path} automatiseringssti afvist: uden for læseroden {root}: {path} @@ -4818,7 +4886,13 @@ imageTrace Outline Kontur @msg the PSD file has an unknown colour mode ({m}) PSD-filen har en ukendt farvetilstand ({m}) @msg the PSD file's image data uses an unknown compression ({m}) PSD-filens billeddata bruger en ukendt komprimering ({m}) @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD-billedet er for stort til at læse ({_1} × {_2} pixels) -@msg zipped 32-bit PSD image data with prediction can't be read zippet 32-bit PSD-billeddata med prædiktion kan ikke læses +@msg zipped 1-bit PSD image data with prediction can't be read zippet 1-bit PSD-billeddata med prædiktion kan ikke læses +@msg the PSD file's layer data uses an unknown compression ({m}) PSD-filens lagdata bruger en ukendt komprimering ({m}) +@msg the PSD file's layer records are damaged PSD-filens lagposter er beskadigede +@msg the PSD file's layer groups are nested too deeply PSD-filens laggrupper er indlejret for dybt +@msg a layer of the PSD file is too large to read et lag i PSD-filen er for stort til at læse +@msg the PSD file's layers take more memory to read than allowed PSD-filens lag kræver mere hukommelse at læse end tilladt +@msg the layers can't be read ({e}): the file opened as its merged image lagene kan ikke læses ({e}): filen blev åbnet som sit samlede billede @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bit PSD-filer i denne farvetilstand kan ikke læses @msg the PSD file is cut short PSD-filen er afkortet @msg the PSD file's header is damaged PSD-filens header er beskadiget @@ -5226,6 +5300,11 @@ mark-style Japanese Japansk Softness Blødhed Ambient Light Omgivelseslys Light behind the object Lys bag objektet + Shadows Skygger + Distance from Object Afstand fra objektet + Shadow Bounds Skyggegrænser + Behind Object Bag objektet + Below Object Under objektet 3D Lighting Preset Forudindstilling for 3D-belysning Standard Standard Diffuse Diffust @@ -5369,7 +5448,7 @@ mark-style Japanese Japansk @msg span must be "object" or "selection", got {v} span skal være "object" eller "selection", fik {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" placerer en `gradient`, ikke en farveprøve @msg span: "selection" places a gradient: give `gradient` span: "selection" placerer en overgang: angiv `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" placerer en lineær eller radial overgang, ikke en fri +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" placerer en lineær, radial, konisk eller diamantformet overgang, ikke en fri @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" placerer overgangen selv: udelad `start` og `end` (de placerer den allerede i dokumentkoordinater) Make Image Dynamic Gør billede dynamisk Import Data Sets… Importér datasæt… @@ -5797,6 +5876,7 @@ swatch Bright Violet Kraftig violet Ruby Ruby Geometric Guides Geometriske hjælpelinjer Geometric Patterns Geometriske mønstre + Grit Textures Kornede teksturer Ease In Langsom start Ease Out Langsom slutning Ease In Out Langsom start og slutning @@ -5850,6 +5930,7 @@ axis Y Axis Y-akse Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? Installér »{name}« i stedet for det plug-in, der har samme id? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Denne fil er ikke det plug-in, der før var installeret med dette id. Den får de indstillinger og den cache, der er gemt for dette id. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. En automatisering bad om at installere dette plug-in. Vælg selv Objekt › Plug-ins › Installér plug-in… for at installere det. File SHA-256: {hash} Filens SHA-256: {hash} Read the objects it is given Læse de objekter, den får Change, add and delete objects in the document Ændre, tilføje og slette objekter i dokumentet @@ -5882,6 +5963,16 @@ axis Y Axis Y-akse @msg message must be text message skal være tekst @msg allowContinue must be true or false allowContinue skal være true eller false @msg Batch cannot play an action with a stop Batch kan ikke afspille en handling med et stop + Insert Menu Item… Indsæt menupunkt… + Insert Menu Item Indsæt menupunkt + Menu Item: Menupunkt: + No menu item matches. Intet menupunkt passer. + Several menu items match. Choose one from the list. Flere menupunkter passer. Vælg et fra listen. + Items that open a dialog, and File, Window and Help menu items, are not listed. Punkter, der åbner en dialogboks, og punkter i menuerne Filer, Vindue og Hjælp vises ikke. +@msg command must be text command skal være tekst +@msg no menu item that can be inserted runs this command intet menupunkt, der kan indsættes, kører denne kommando +@msg the action already has 10,000 steps handlingen har allerede 10.000 trin +@msg the action set would be larger than 8 MiB handlingssættet ville blive større end 8 MiB Playback Options Afspilningsindstillinger Accelerated Accelereret Step by Step Trin for trin @@ -5915,6 +6006,12 @@ axis Y Axis Y-akse Crosshair Sigtekorn Checkpoint Kontrolpunkt Inventory Icons Inventarikoner + Skill Icons Færdighedsikoner + Attack Angreb + Defend Forsvar + Heal Helbredelse + Buff Buff + Ult Ult Sword Sværd Shield Skjold Potion Eliksir @@ -5973,7 +6070,23 @@ axis Y Axis Y-akse Dash Trail Streget spor Speed Line Hastighedslinje Game Trails Spilspor + Energy Beams Energistråler + Laser Bolt Laserbolt + Plasma Arc Plasmabue + Charge Wave Opladningsbølge + Spark Trail Gnistsvær Calligraphic Nibs Kalligrafiske penne + Bristle Brushes Børstepensler + Fine Liner Fin streg + Pointed Flat Spids flad + Stubby Round Kort rund + Dry Scrub Tør skrubning + Soft Dome Blød kuppel + Filbert Oval flad + Angled Round Skrå rund + Angled Flat Skrå flad + Fan Blender Blendevifte + Grass Fan Græsvifte Pattern Borders Mønsterborter Scatter Shapes Spredte former Save Brush Library… Gem penselbibliotek… @@ -6317,6 +6430,12 @@ breakText Glyphs Glyffer Delete the selected brushes? Slet de valgte pensler? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Streger bruger en eller flere af disse pensler. Fjern penslerne fra stregerne, og slet penslerne? Remove Strokes Fjern streger + Place Brush Art Placér penselgrafik + Replace Brush Art Erstat penselgrafik + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Streger bruger denne pensel. Anvend den nye grafik på stregerne, eller lad dem være, som de er, og tilføj en kopi af penslen med den nye grafik? + Apply to Strokes Anvend på streger + Leave Strokes Bevar streger +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` har ingen grafik (det har kun sprednings-, grafik- og mønsterpensler) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Arrangeringsværktøjer Arrange in Grid… Arrangér i gitter… @@ -6499,6 +6618,11 @@ breakText Glyphs Glyffer No importer plug-ins installed Ingen import-plug-ins installeret Read files you open in its format and make documents from them Læse filer, du åbner i dens format, og lave dokumenter ud fra dem +# Copy Troubleshooting Info + Copy Troubleshooting Info Kopiér fejlfindingsoplysninger +@msg Copied the troubleshooting info Kopierede fejlfindingsoplysningerne +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Den seneste VectorCraft-session holdt op med at svare, før den blev lukket. Hjælp › Kopiér fejlfindingsoplysninger kopierer detaljerne til en fejlrapport + # Safe Mode Safe Mode… Sikker tilstand… Safe Mode Sikker tilstand @@ -6519,6 +6643,8 @@ breakText Glyphs Glyffer # Align to Pixel Grid Align to Pixel Grid Juster efter pixelgitter + Align New Objects to Pixel Grid Juster nye objekter efter pixelgitter + Not Aligned to Pixel Grid Ikke justeret efter pixelgitter @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` Edit Custom Dictionary Redigér egen ordliste Entry: Opslag: @@ -6544,6 +6670,26 @@ breakText Glyphs Glyffer @plural {n} earlier line dropped|{n} earlier lines dropped {n} tidligere linje fjernet|{n} tidligere linjer fjernet @plural {n} line cut|{n} lines cut {n} linje afkortet|{n} linjer afkortet +# Learn panel + Learn Lær + Explore tutorials Udforsk vejledninger + For you Til dig + Skills Færdigheder + Get started Kom i gang + Quick skill guide Hurtig færdighedsguide + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Korte praktiske vejledninger til de vigtigste værktøjer, ordnet efter færdighed. Vælg en færdighed for at se dens vejledninger. + List Tutorials Vis vejledninger + Show Tutorial Vis vejledning +@msg missing `tutorial` (see learn.list) `tutorial` mangler (se learn.list) +@msg unknown tutorial `{id}` (see learn.list) ukendt vejledning `{id}` (se learn.list) + # Deferred plug-in effects Refresh Deferred Effects Opdatér udskudte effekter Deferred Effects Udskudte effekter + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Skæreværktøjer + Stencil Bridges… Stencilbroer… + Stencil Bridges Stencilbroer + Shortest Crossing Korteste krydsning + Direction Retning diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b339033e66..52455507a5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -237,6 +237,7 @@ font-technology Variable Variabel Asset Export Settings Einstellungen für den Asset-Export Assets Assets Assign Zuweisen + Assign Profile Profil zuweisen Assign Profile… Profil zuweisen… Assign: Zuweisen: Attach to Active Plane An aktiver Perspektivebene anbringen @@ -679,6 +680,15 @@ font-technology Variable Variabel Created: Erstellt: Crop Schnittmengenfläche Crop Image Bild beschneiden + Image Tools Bildwerkzeuge + Remove Background… Hintergrund entfernen… + Remove Background Hintergrund entfernen + Background Hintergrund + Edge Color Randfarbe + Picked Colors Ausgewählte Farben + Corner Color Eckfarbe + Contiguous Zusammenhängend + Each Channel Jeder Kanal Edit Path Pfad bearbeiten Mask Maske Crop Marks Schnittmarken @@ -798,6 +808,14 @@ font-technology Variable Variabel Disable Auto Add/Delete Automatisches Hinzufügen/Löschen deaktivieren Disable Opacity Mask Deckkraftmaske deaktivieren Discard Verwerfen + Preserve Beibehalten + TIFF (Black & White) TIFF (Schwarzweiß) + TIFF (8-bit Color) TIFF (8-Bit-Farbe) + High Resolution Hohe Auflösung + Medium Resolution Mittlere Auflösung + Low Resolution Niedrige Auflösung + Language Level 2 Sprachebene 2 + Language Level 3 Sprachebene 3 Discard Empty Type Leeren Text verwerfen Discard Recovered Documents Wiederhergestellte Dokumente verwerfen Discard White Overprint in Output Weißes Überdrucken in der Ausgabe verwerfen @@ -1114,6 +1132,8 @@ font-technology Variable Variabel Extrude & Bevel… Extrudieren und abgeflachte Kante… 3D (Classic) 3D (klassisch) Extrude & Bevel (Classic)… Extrudieren und abgeflachte Kante (klassisch)… + Revolve (Classic)… Kreiseln (klassisch)… + Rotate (Classic)… Drehen (klassisch)… Surface Oberfläche Wireframe Drahtmodell No Shading Keine Schattierung @@ -1426,6 +1446,14 @@ file-filter Templates Vorlagen Hair Space Haarspatium Hand Tool Hand-Werkzeug Hand-Drawn Handgezeichnet + Painted and Sketched Gemalt und skizziert + Washed Blue Verwaschenes Blau + Bristle Ochre Borstenocker + Pastel Heather Pastellheide + Charcoal Shade Kohleschatten + Ink Contour Tuschekontur + Wet Ink Nasse Tusche + Fine Pen Feine Feder Handles Griffe Hard Light Hartes Licht Hard Mix Hart mischen @@ -1655,6 +1683,7 @@ file-filter Templates Vorlagen Include Linked Files Verknüpfte Dateien einschließen Include Metadata Metadaten einschließen Include non-printing layers Nicht druckende Ebenen einschließen + Write pages longer than 200 in at full size in points Seiten über 200 in in voller Größe in Punkt schreiben Include SVG Code SVG-Code einschließen Include Swatches for Tints Farbfelder für Tonwerte einschließen Inflate… Aufblasen… @@ -2288,12 +2317,23 @@ file-filter Templates Vorlagen Open… Öffnen… Optical Optisch Optical Margin Alignment Optischer Randausgleich + Dynamic Text Dynamischer Text + Dynamic Text Presets Vorgaben für dynamischen Text + Arch Rundbogen +@msg select point type or type on a path wählen Sie Punkttext oder Pfadtext aus +@msg type on a path in a thread cannot use Dynamic Text: {frames} Pfadtext in verkettetem Text kann keinen dynamischen Text verwenden: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} Pfadtext auf einem offenen oder zusammengesetzten Pfad lässt sich nicht oben oder unten zentrieren: {open} +@msg type on a path with no length or no height cannot be centered: {flat} Pfadtext auf einem Pfad ohne Länge oder ohne Höhe lässt sich nicht zentrieren: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} Pfadtext in verkettetem Text lässt sich nicht oben oder unten zentrieren: {frames} +@msg select type on a closed path wählen Sie Pfadtext auf einem geschlossenen Pfad aus Optimize for fast web view Für schnelle Webanzeige optimieren Optimized Optimiert Options Optionen Options for Selection… Optionen für Auswahl… Options: Optionen: Options… Optionen… + Organic Fades Organische Verläufe + Holographic Holografisch or more spaces with a tab oder mehr Leerzeichen durch einen Tabulator Order: Reihenfolge: Ordinals Ordinalzahlen @@ -2487,6 +2527,7 @@ diagnostics ui Oberfläche Presets: Vorgaben: Press Mit Preview Vorschau + Preview: Vorschau: Preview All Layers Vorschau aller Ebenen Preview in Browser Vorschau im Browser Preview in Browser needs the desktop app (the web downloads files instead) „Vorschau im Browser“ erfordert die Desktop-App (im Web werden stattdessen Dateien heruntergeladen) @@ -2567,6 +2608,8 @@ digits Malayalam Malayalam Radial Radial Radial Glows Radiale Leuchteffekte Radial Gradient Radialer Verlauf + Conic Gradient Konischer Verlauf + Diamond Gradient Rautenverlauf Radius 1 Radius 1 Radius 2 Radius 2 Radius1 Radius1 @@ -2579,6 +2622,8 @@ digits Malayalam Malayalam Range: Bereich: Raster Effects Rastereffekte Raster File Format: Pixelbild-Dateiformat: + Include Placed Images Platzierte Bilder einschließen + Include Fill Hatches Füllschraffuren einschließen Raster Sample Size: Aufnahmebereich in Pixelbildern: Raster/Vector Balance: Pixelbild-Vektor-Abgleich: Rasterize In Pixelbild umwandeln @@ -2760,6 +2805,10 @@ digits Malayalam Malayalam Replace Font Schrift ersetzen Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Ersetzen Sie sie durch eine andere Datei oder ignorieren Sie sie: Ihre Bilder zeigen weiterhin die mit dem Dokument gespeicherte Vorschau. Replace Spine Achse ersetzen + Create Spine Achse erstellen + Create Spine: Achse erstellen: + Always Immer + Never Nie Replace Symbol Symbol ersetzen Reset Transformation Transformation zurücksetzen Replace With Font Durch Schrift ersetzen @@ -2839,6 +2888,9 @@ digits Malayalam Malayalam Rise… Ansteigend… Roman Baseline Lateinische Grundlinie Roman Hanging Punctuation Hängende Interpunktion (lateinisch) + Korean Line Break Anywhere Koreanischer Zeilenumbruch überall + East Asian Composition Settings Einstellungen für ostasiatischen Satz + Korean Composition Settings Einstellungen für koreanischen Satz Rotate Drehen Rotate 90° CW Um 90° im Uhrzeigersinn drehen Rotate Tool Drehen-Werkzeug @@ -3124,6 +3176,15 @@ digits Malayalam Malayalam Stun Pulse Betäubung Stealth Fade Schleichen Shield Buff Schild + Textures Texturen + Fine Grain Feine Körnung + Canvas Weave Leinwandgewebe + Burlap Sack Jutesack + Cracked Glaze Craquelé-Glasur + Mosaic Floor Mosaikboden + Quilted Squares Gesteppte Quadrate + Leaded Glass Bleiglas + Damp Paper Feuchtes Papier Shape Form Shape Builder Formerstellung Shape Builder Regions Formerstellungsbereiche @@ -3186,6 +3247,7 @@ digits Malayalam Malayalam Show Modified Geänderte einblenden Show Note Notiz einblenden Show Options Optionen einblenden + Show Recent Colors Zuletzt verwendete Farben einblenden Show Original Path Originalpfad einblenden Open this dialog with these settings next time Dieses Dialogfeld nächstes Mal mit diesen Einstellungen öffnen Auto-Simplify Automatisch vereinfachen @@ -3474,6 +3536,8 @@ effect Points Punkte Scale at Center Von der Mitte aus skalieren Up/Down: Oben/Unten: Left/Right: Links/Rechts: + Tate-chu-yoko Up/Down Tate-chu-yoko oben/unten + Tate-chu-yoko Left/Right Tate-chu-yoko links/rechts Temperature Temperatur Temperature/Tint… Temperatur/Farbstich… Template Vorlage @@ -3544,6 +3608,8 @@ effect Points Punkte Toolbar: Single/Double Column Werkzeugleiste: ein-/zweispaltig Toolbar: Add Tool Werkzeugleiste: Werkzeug hinzufügen Toolbar: Remove Tool Werkzeugleiste: Werkzeug entfernen + Add Tool… Werkzeug hinzufügen… + Remove Tool Werkzeug entfernen Toolbar: Reset Werkzeugleiste: Zurücksetzen Toolbars Werkzeugleisten Tools Werkzeuge @@ -3615,6 +3681,8 @@ effect Points Punkte Type on a Path Pfadtext Type on a Path Options Pfadtextoptionen Type on a Path Options… Pfadtextoptionen… + Center on Top Oben zentrieren + Center on Bottom Unten zentrieren Type on a Path Tool Pfadtext-Werkzeug Type Orientation Textrichtung Type stays text, and every stroke is a line with its lineweight and dashes. Text bleibt Text, und jede Kontur ist eine Linie mit ihrer Linienstärke und ihren Strichen. @@ -3773,6 +3841,7 @@ effect Points Punkte Windows Windows Working CMYK CMYK-Arbeitsfarbraum Working CMYK (don't tag) CMYK-Arbeitsfarbraum (nicht kennzeichnen) + Working RGB (don't tag) RGB-Arbeitsfarbraum (nicht kennzeichnen) Workspace Arbeitsbereich Workspace {i} Arbeitsbereich {i} Wrinkle Tool Zerknittern-Werkzeug @@ -3961,6 +4030,13 @@ theme Appearance Erscheinungsbild Dock Panel Bedienfeld andocken Dock to Top Oben andocken Dock to Bottom Unten andocken + Control Bar Options Optionen der Steuerungsleiste + Tool Options Werkzeugoptionen + Object Options Objektoptionen + Image Options Bildoptionen + Vertical Alignment Vertikale Ausrichtung + Align and Distribute Ausrichten und verteilen + Document Options Dokumentoptionen Dock Control Bar Steuerungsleiste andocken Drag to float the toolbar Ziehen, um die Werkzeugleiste abzulösen Drag to the window's left or right edge to dock Zum Andocken an den linken oder rechten Fensterrand ziehen @@ -4113,10 +4189,13 @@ theme Appearance Erscheinungsbild @msg `groupColors` must be an array `groupColors` muss ein Array sein @msg `library` is a library id or name (see {list}) `library` ist die ID oder der Name einer Bibliothek (siehe {list}) @msg `mode` applies to freeform gradients `mode` gilt für Freiformverläufe +@msg a negative `aspect` applies to conic gradients ein negatives `aspect` gilt für konische Verläufe +@msg `focal` applies to radial gradients `focal` gilt für radiale Verläufe @msg `preserve` must be an object `preserve` muss ein Objekt sein @msg `globalAdjust` must be an object `globalAdjust` muss ein Objekt sein @msg `sampleSize` must be 1, 3 or 5 `sampleSize` muss 1, 3 oder 5 sein @msg `stops` must be an array `stops` muss ein Array sein +@msg `{key}` must be an array `{key}` muss ein Array sein @msg `svg` must be an object of SVG options (see document.formats) `svg` muss ein Objekt mit SVG-Optionen sein (siehe document.formats) @msg `{_1}` is no save command `{_1}` ist kein Speicherbefehl @msg `{area}` is no recovery area name `{area}` ist kein Name eines Wiederherstellungsbereichs @@ -4130,6 +4209,7 @@ theme Appearance Erscheinungsbild @msg `{key}` must be a number, not {v} `{key}` muss eine Zahl sein, nicht {v} @msg {key} must be Unix seconds (an integer) or null {key} muss eine Unix-Zeit in Sekunden (eine ganze Zahl) oder null sein @msg `{key}` must be a string `{key}` muss eine Zeichenfolge sein +@msg `{key}` must be a profile name or null `{key}` muss ein Profilname oder null sein @msg `{key}` must be a whole number `{key}` muss eine ganze Zahl sein @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` muss eine ganze Zahl zwischen {min} und {max} sein (erhalten: {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` muss zwischen {min} und {max} liegen (erhalten: {x}) @@ -4282,6 +4362,7 @@ theme Appearance Erscheinungsbild @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller die Seite der Zeichenfläche {n} ist {size} groß und damit länger als die PDF-Seitengrenze von 14.400 pt (200 in): sie wird mit einer UserUnit von {unit} geschrieben, daher zeigen Apps, die UserUnit ignorieren, sie entsprechend oft kleiner an @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in die Seite der Zeichenfläche {n} ist {size} groß und damit länger als die PDF-Seitengrenze von 14.400 pt (200 in): {label}-Seiten werden ohne UserUnit in Punkt geschrieben, und Apps, die die Grenze einhalten, schneiden die Seite auf 200 in ab @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 hat keine UserUnit, die eine Seite länger als 14.400 pt (200 in) braucht, um ihre Größe zu behalten: die Datei wird als PDF 1.6 geschrieben +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 hat keine UserUnit, die eine Seite länger als 14.400 pt (200 in) braucht, um innerhalb der PDF/A-2-Seitengrenze von 14.400 Einheiten zu bleiben: die Datei wird als PDF 1.6 geschrieben @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units die Seite der Zeichenfläche {n} ist {size} groß und damit zu lang und schmal für PDF-Seitenlängen von 3 bis 14.400 Einheiten: sie wird mit einer UserUnit von {unit} geschrieben, die die kurze Seite bei mindestens 3 Einheiten hält, und Apps, die die Grenze einhalten, schneiden die lange Seite auf 14.400 Einheiten ab @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-Dateien fassen reelle Zahlen bis {max}, und die Seite der Zeichenfläche {n} mit {side} pt Länge braucht größere: wählen Sie PDF 1.6 oder höher ohne PDF/X-Standard oder eine kleinere Zeichenfläche @msg invalid image data for `{0}` ungültige Bilddaten für `{0}` @@ -4431,6 +4512,8 @@ theme Appearance Erscheinungsbild @msg not a stored central record kein gespeicherter zentraler Eintrag @msg not a valid plug-in module: {0} kein gültiges Plug-in-Modul: {0} @msg not an EMF or WMF file keine EMF- oder WMF-Datei +@msg not an HP-GL file keine HP-GL-Datei +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` muss ein Array von 1 bis 255 Farben der Form #rrggbb sein @msg not found nicht gefunden @msg not in pattern editing mode nicht im Musterbearbeitungsmodus @msg finish editing the pattern first beenden Sie zuerst die Bearbeitung des Musters @@ -4510,6 +4593,14 @@ theme Appearance Erscheinungsbild @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 diese Nachzeichnung würde mehr als {max} Ankerpunkte erzeugen, mehr als das Dokument flüssig darstellen kann: Erhöhen Sie „Rauschen“, verringern Sie „Pfade“ oder „Farben“ oder wählen Sie eine Vorgabe mit geringerer Genauigkeit @msg select an envelope wählen Sie eine Hülle aus @msg select an image wählen Sie ein Bild aus +@msg `background` must be edges, corners or colors `background` muss edges, corners oder colors sein +@msg `match` must be distance or channels `match` muss distance oder channels sein +@msg `{key}` must be from 0 to 100 `{key}` muss von 0 bis 100 sein +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` muss 1 bis 16 Farben enthalten, jede hexadezimal (#rrggbb oder #rgb) oder als black, white, red, green oder blue +@msg the linked image shows its preview: embed or relink it first das verknüpfte Bild zeigt seine Vorschau: Betten Sie es zuerst ein oder verknüpfen Sie es neu +@msg a CMYK image has no transparency to set ein CMYK-Bild hat keine Transparenz, die festgelegt werden kann +@msg every pixel matches the background: no image would be left jedes Pixel entspricht dem Hintergrund: Es würde kein Bild übrig bleiben +@msg an image of {w} × {h} pixels is too large to change ein Bild mit {w} × {h} Pixeln ist zu groß, um geändert zu werden @msg select an object in perspective wählen Sie ein Objekt in der Perspektive aus @msg select artwork (or a colour group) to recolor wählen Sie eine Grafik (oder eine Farbgruppe) zum Neufärben aus @msg Recolor completed; {locked} and {hidden} were left unchanged Neufärben abgeschlossen; unverändert: {locked} und {hidden} @@ -4616,7 +4707,7 @@ theme Appearance Erscheinungsbild @msg unknown format unbekanntes Format @msg unknown format `{f}` (Save writes {_1}) unbekanntes Format `{f}` („Speichern“ schreibt {_1}) @msg unknown freeform mode `{m}` (points, lines) unbekannter Freiformmodus `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) unbekannte Verlaufsart `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) unbekannte Verlaufsart `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` unbekannte Hervorhebung `{h}` @msg unknown option `{path}.{k}` unbekannte Option `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) unbekannter Wert für overprints `{o}` (preserve, simulate oder discard) @@ -4863,6 +4954,8 @@ theme Appearance Erscheinungsbild @msg invalid object id {value}: expected a non-negative integer ungültige Objekt-ID {value}: erwartet wird eine nicht negative ganze Zahl @msg `{key}` entry {index} is {value}, not a non-negative integer object id Eintrag {index} von `{key}` ist {value}, keine Objekt-ID (nicht negative ganze Zahl) @msg no such object id {value} kein Objekt mit der ID {value} +@msg id {value} is a ruler guide, not an object die ID {value} gehört zu einer Hilfslinie, nicht zu einem Objekt +@msg a ruler guide goes only directly in a layer or sublayer eine Hilfslinie kann nur direkt in einer Ebene oder Unterebene liegen @msg id {value} is a layer, not an object die ID {value} ist eine Ebene, kein Objekt @msg id {value} is a layer, not an object; move layers with layer.move die ID {value} ist eine Ebene, kein Objekt; verschieben Sie Ebenen mit layer.move @msg automation filesystem access is not granted: read authority is absent: {path} Dateisystemzugriff für die Automatisierung ist nicht gewährt: Die Leseberechtigung fehlt: {path} @@ -4959,7 +5052,7 @@ theme Appearance Erscheinungsbild The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Die Hauptfarbe wird zur Konturfarbe. Die anderen Farben wandern ebenso weit um den Farbkreis wie die Hauptfarbe und behalten ihre Sättigung und Helligkeit. RGB: RGB: CMYK: CMYK: -# PSD files (opened and placed as their merged image). +# PSD files. @msg not a PSD file keine PSD-Datei @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode PSD-Dateien im Mehrkanalmodus können nicht gelesen werden: Speichern Sie die Datei im RGB-, CMYK- oder Graustufenmodus @msg the PSD file has an unknown colour mode ({m}) die PSD-Datei hat einen unbekannten Farbmodus ({m}) @@ -4979,7 +5072,13 @@ theme Appearance Erscheinungsbild @msg the HEIC or HEIF file holds a kind of image that can't be read die HEIC- oder HEIF-Datei enthält eine Bildart, die nicht gelesen werden kann @msg HEIC and HEIF images can't be opened in this build HEIC- und HEIF-Bilder können in diesem Build nicht geöffnet werden @msg the PSD image is too large to read ({_1} × {_2} pixels) das PSD-Bild ist zu groß zum Lesen ({_1} × {_2} Pixel) -@msg zipped 32-bit PSD image data with prediction can't be read ZIP-komprimierte 32-Bit-PSD-Bilddaten mit Vorhersage können nicht gelesen werden +@msg zipped 1-bit PSD image data with prediction can't be read ZIP-komprimierte 1-Bit-PSD-Bilddaten mit Vorhersage können nicht gelesen werden +@msg the PSD file's layer data uses an unknown compression ({m}) die Ebenendaten der PSD-Datei verwenden eine unbekannte Komprimierung ({m}) +@msg the PSD file's layer records are damaged die Ebenendatensätze der PSD-Datei sind beschädigt +@msg the PSD file's layer groups are nested too deeply die Ebenengruppen der PSD-Datei sind zu tief verschachtelt +@msg a layer of the PSD file is too large to read eine Ebene der PSD-Datei ist zu groß zum Lesen +@msg the PSD file's layers take more memory to read than allowed die Ebenen der PSD-Datei brauchen zum Lesen mehr Speicher als erlaubt +@msg the layers can't be read ({e}): the file opened as its merged image die Ebenen können nicht gelesen werden ({e}): die Datei wurde als ihr zusammengefügtes Bild geöffnet @msg {depth}-bit PSD files in this colour mode can't be read {depth}-Bit-PSD-Dateien in diesem Farbmodus können nicht gelesen werden @msg the JPEG XL file is cut short die JPEG-XL-Datei ist unvollständig @msg the JPEG XL container is too large to read der JPEG-XL-Container ist zu groß zum Lesen @@ -5279,6 +5378,11 @@ effect Soft Weich Softness Weichheit Ambient Light Umgebungslicht Light behind the object Licht hinter dem Objekt + Shadows Schatten + Distance from Object Abstand vom Objekt + Shadow Bounds Schattenbegrenzung + Behind Object Hinter dem Objekt + Below Object Unter dem Objekt 3D Lighting Preset 3D-Beleuchtungsvorgabe Standard Standard Diffuse Diffus @@ -5346,7 +5450,7 @@ effect Soft Weich @msg span must be "object" or "selection", got {v} span muss "object" oder "selection" sein, nicht {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" platziert einen `gradient`, kein Farbfeld @msg span: "selection" places a gradient: give `gradient` span: "selection" platziert einen Verlauf: geben Sie `gradient` an -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" platziert einen linearen oder radialen Verlauf, keinen Freiform-Verlauf +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" platziert einen linearen, radialen, konischen oder Rautenverlauf, keinen Freiform-Verlauf @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" platziert den Verlauf selbst: lassen Sie `start` und `end` weg (sie platzieren ihn bereits in Dokumentkoordinaten) Make Image Dynamic Bild dynamisch machen Import Data Sets… Datensätze importieren… @@ -5532,6 +5636,7 @@ effect Soft Weich Ruby Ruby Geometric Guides Geometrische Hilfslinien Geometric Patterns Geometrische Muster + Grit Textures Körnige Texturen Ease In Langsam starten Ease Out Langsam enden Ease In Out Langsam starten und enden @@ -5592,6 +5697,8 @@ axis Y Axis Y-Achse Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? „{name}“ anstelle des Plug-ins mit derselben ID installieren? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Diese Datei ist nicht das Plug-in, das vorher mit dieser ID installiert war. Sie erhält die Einstellungen und den Cache, die für diese ID gespeichert sind. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Eine Automatisierung hat angefordert, dieses Plug-in zu installieren. Um es zu installieren, wählen Sie selbst „Objekt › Plug-ins › Plug-in installieren…“. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Eine Automatisierung hat angefordert, dieses Plug-in zu installieren. Um es zu installieren, wählen Sie selbst „Objekt › Plug-ins › Plug-in installieren…“. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}“ ist ein anderes Modul als das Plug-in mit der ID {_1} und würde die dafür gespeicherten Einstellungen und den Cache erhalten: Installieren Sie es mit `replace: true`, sobald der Benutzer zustimmt File SHA-256: {hash} Datei-SHA-256: {hash} Read the objects it is given Die Objekte lesen, die es erhält @@ -5637,6 +5744,11 @@ axis Y Axis Y-Achse @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben) @msg object budget (more than {MAX_OBJECTS} read-only objects) Objektbudget (mehr als {MAX_OBJECTS} schreibgeschützte Objekte) +@msg instruction budget Anweisungsbudget +@msg time budget Zeitbudget +@msg memory budget (the selection is too large to hand over) Speicherbudget (die Auswahl ist zu groß zum Übergeben) +@msg output size ({what} is {len} bytes, limit {max}) Ausgabegröße ({what} ist {len} Byte groß, Grenze {max}) +@msg the plug-in's grant can't be removed from the plug-in store die Berechtigung des Plug-ins kann nicht aus dem Plug-in-Speicher entfernt werden @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it die Berechtigung `{shown}` ist für eine spätere Plug-in-API reserviert; dieser Host gewährt sie nicht @msg unknown permission `{shown}` unbekannte Berechtigung `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ verlangt die Berechtigungen {asked}: Eine Person muss sie in der Desktop-App genehmigen, oder übergeben Sie `grant` in einer mit --allow-plugin-grants gestarteten Sitzung @@ -5649,6 +5761,12 @@ axis Y Axis Y-Achse @msg command {name}: `label` must be 1-64 printable characters Befehl {name}: `label` muss 1-64 druckbare Zeichen haben @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter Befehl {name}: Verwenden Sie eine ID aus 1-{MAX_COMMAND_ID} Zeichen aus a-z 0-9 _, die mit einem Buchstaben beginnt @msg command {name}: {e} Befehl {name}: {e} +@msg manifest: {e} Manifest: {e} +@msg manifest: {e} at line {line} column {column} Manifest: {e} (Zeile {line}, Spalte {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` muss eine Liste von Befehlen sein, jeder mit `id` und `label` +@msg command {name} must be an object with an `id` and a `label` der Befehl {name} muss ein Objekt mit `id` und `label` sein +@msg missing field `{key}` fehlendes Feld `{key}` +@msg duplicate field `{key}` doppeltes Feld `{key}` @msg only a filter or a live effect declares `commands` nur ein Filter oder ein Live-Effekt deklariert `commands` @msg “{name}” › {label}: {e} „{name}“ › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed das Modul hat nicht den SHA-256-Wert aus `hash`: Es wurde nichts installiert @@ -5673,6 +5791,16 @@ axis Y Axis Y-Achse @msg message must be text message muss Text sein @msg allowContinue must be true or false allowContinue muss true oder false sein @msg Batch cannot play an action with a stop Die Stapelverarbeitung kann keine Aktion mit einem Stopp abspielen + Insert Menu Item… Menübefehl einfügen… + Insert Menu Item Menübefehl einfügen + Menu Item: Menübefehl: + No menu item matches. Kein Menübefehl passt. + Several menu items match. Choose one from the list. Mehrere Menübefehle passen. Wählen Sie einen aus der Liste. + Items that open a dialog, and File, Window and Help menu items, are not listed. Befehle, die ein Dialogfeld öffnen, sowie Befehle der Menüs „Datei“, „Fenster“ und „Hilfe“ werden nicht aufgeführt. +@msg command must be text command muss Text sein +@msg no menu item that can be inserted runs this command kein einfügbarer Menübefehl führt diesen Befehl aus +@msg the action already has 10,000 steps die Aktion hat bereits 10.000 Schritte +@msg the action set would be larger than 8 MiB der Aktionssatz wäre größer als 8 MiB Playback Options Wiedergabeoptionen Accelerated Beschleunigt Step by Step Schrittweise @@ -5711,6 +5839,12 @@ axis Y Axis Y-Achse Crosshair Fadenkreuz Checkpoint Kontrollpunkt Inventory Icons Inventar-Symbole + Skill Icons Fähigkeitssymbole + Attack Angriff + Defend Verteidigung + Heal Heilung + Buff Buff + Ult Ult Sword Schwert Shield Schild Potion Trank @@ -5775,7 +5909,23 @@ axis Y Axis Y-Achse Dash Trail Strichelspur Speed Line Geschwindigkeitslinie Game Trails Spielspuren + Energy Beams Energiestrahlen + Laser Bolt Laserbolzen + Plasma Arc Plasmabogen + Charge Wave Ladewelle + Spark Trail Funkenspur Calligraphic Nibs Kalligrafie-Federn + Bristle Brushes Borstenpinsel-Set + Fine Liner Feiner Liner + Pointed Flat Spitzer Flachpinsel + Stubby Round Kurzer Rundpinsel + Dry Scrub Trockenes Schrubben + Soft Dome Weiche Kuppel + Filbert Katzenzunge + Angled Round Schräger Rundpinsel + Angled Flat Schräger Flachpinsel + Fan Blender Fächer zum Verblenden + Grass Fan Grasfächer Pattern Borders Musterbordüren Scatter Shapes Streuformen Save Brush Library… Pinsel-Bibliothek speichern… @@ -5975,9 +6125,12 @@ anchor Points: Punkte: @msg {label} must be a number {label} muss eine Zahl sein @msg {label} must be a number of at least 0.1 {label} muss eine Zahl von mindestens 0,1 sein Advanced Character Formats Erweiterte Zeichenformate + Basic Paragraph Formats Grundlegende Absatzformate + Composition Satz Horizontal Scale Horizontale Skalierung Vertical Scale Vertikale Skalierung @msg {label} must be a number from {min} to {max} {label} muss eine Zahl von {min} bis {max} sein +@msg {label} must be a whole number from {min} to {max} {label} muss eine ganze Zahl von {min} bis {max} sein Character Color Zeichenfarbe OpenType Features OpenType-Funktionen Stylistic Sets Stilsätze @@ -5985,6 +6138,10 @@ anchor Points: Punkte: @msg features lists at most {max} tags features enthält höchstens {max} Tags @msg unknown OpenType feature `{t}` unbekannte OpenType-Funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} muss eine Zahl über 0 und höchstens {max} sein +@msg {label} must be at most {max} characters {label} darf höchstens {max} Zeichen lang sein +@msg {label} must be one character {label} muss genau ein Zeichen sein +@msg at most {max} tab stops höchstens {max} Tabstopps +@msg unknown align `{other}` unbekannte Ausrichtung `{other}` @msg no character style `{name}` Zeichenformat `{name}` nicht gefunden # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6147,6 +6304,12 @@ breakText Glyphs Glyphen Delete the selected brushes? Ausgewählte Pinsel löschen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturen verwenden einen oder mehrere dieser Pinsel. Pinsel von diesen Konturen entfernen und die Pinsel löschen? Remove Strokes Konturen entfernen + Place Brush Art Pinselgrafik platzieren + Replace Brush Art Pinselgrafik ersetzen + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturen verwenden diesen Pinsel. Die neue Grafik auf diese Konturen anwenden oder sie unverändert lassen und eine Kopie des Pinsels mit der neuen Grafik hinzufügen? + Apply to Strokes Auf Konturen anwenden + Leave Strokes Konturen beibehalten +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` hat keine Grafik (nur Spezial-, Bild- und Musterpinsel haben eine) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Anordnungswerkzeuge Arrange in Grid… In Raster anordnen… @@ -6342,6 +6505,11 @@ breakText Glyphs Glyphen @msg only an exporter or an importer declares `extensions` nur ein Export- oder Import-Plug-in gibt `extensions` an @msg an importer always gets an import's budget: leave `budget` out ein Import-Plug-in erhält immer das Budget eines Imports: Lassen Sie `budget` weg +# Copy Troubleshooting Info + Copy Troubleshooting Info Informationen zur Fehlerbehebung kopieren +@msg Copied the troubleshooting info Informationen zur Fehlerbehebung kopiert +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Die letzte VectorCraft-Sitzung reagierte nicht mehr, bevor sie geschlossen wurde. Hilfe › Informationen zur Fehlerbehebung kopieren kopiert die Details für einen Fehlerbericht + # Safe Mode Safe Mode… Abgesicherter Modus… Safe Mode Abgesicherter Modus @@ -6362,6 +6530,8 @@ breakText Glyphs Glyphen # Align to Pixel Grid Align to Pixel Grid Am Pixelraster ausrichten + Align New Objects to Pixel Grid Neue Objekte am Pixelraster ausrichten + Not Aligned to Pixel Grid Nicht am Pixelraster ausgerichtet @msg only paths and compound paths can be aligned to the pixel grid nur Pfade und zusammengesetzte Pfade können am Pixelraster ausgerichtet werden @msg side is left or right, not `{s}` side ist left oder right, nicht `{s}` Ignore All Alle ignorieren @@ -6392,8 +6562,33 @@ breakText Glyphs Glyphen @plural {n} line cut|{n} lines cut {n} Zeile gekürzt|{n} Zeilen gekürzt @msg `first` and `last` must be numbers of lines the console holds, first before last `first` und `last` müssen Nummern von Zeilen sein, die die Konsole enthält, `first` vor `last` +# Learn panel + Learn Lernen + Explore tutorials Lernprogramme entdecken + For you Für Sie + Skills Fertigkeiten + Get started Erste Schritte + Quick skill guide Kurzanleitung zu Fertigkeiten + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Kurze praktische Lernprogramme zu den wichtigsten Werkzeugen, nach Fertigkeiten geordnet. Wählen Sie eine Fertigkeit, um ihre Lernprogramme zu sehen. + List Tutorials Lernprogramme auflisten + Show Tutorial Lernprogramm anzeigen +@msg missing `tutorial` (see learn.list) `tutorial` fehlt (siehe learn.list) +@msg unknown tutorial `{id}` (see learn.list) unbekanntes Lernprogramm `{id}` (siehe learn.list) + # Deferred plug-in effects Refresh Deferred Effects Zurückgestellte Effekte aktualisieren Deferred Effects Zurückgestellte Effekte @msg no plug-in effect is deferred kein Plug-in-Effekt ist zurückgestellt @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Mit {n} zurückgestelltem Plug-in-Effekt geöffnet. Effekt › Zurückgestellte Effekte aktualisieren führt ihn aus.|Mit {n} zurückgestellten Plug-in-Effekten geöffnet. Effekt › Zurückgestellte Effekte aktualisieren führt sie aus. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Schneidwerkzeuge + Stencil Bridges… Schablonenstege… + Stencil Bridges Schablonenstege + Shortest Crossing Kürzeste Querung + Direction Richtung +@msg The selected art has no islands to bridge Das ausgewählte Bildmaterial hat keine Inseln zum Verbinden +@msg No bridge of this width fits across the selected art Kein Steg dieser Breite passt über das ausgewählte Bildmaterial +@msg Some islands could not be joined to the area around the art Einige Inseln konnten nicht mit der Fläche um das Bildmaterial verbunden werden +@msg `width` must be from {lo} to {hi} pt `width` muss zwischen {lo} und {hi} pt liegen +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` muss eine ganze Zahl von 1 bis {MAX_BRIDGES_PER_ISLAND} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 114ed5a524..dfb942176b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -240,6 +240,7 @@ font-technology Variable Μεταβλητές Asset Export Settings Ρυθμίσεις εξαγωγής στοιχείων Assets Στοιχεία Assign Αντιστοίχιση + Assign Profile Ανάθεση προφίλ Assign Profile… Ανάθεση προφίλ… Assign: Αντιστοίχιση: Attach to Active Plane Προσάρτηση στο ενεργό επίπεδο @@ -660,6 +661,15 @@ font-technology Variable Μεταβλητές Created: Δημιουργήθηκε: Crop Περικοπή Crop Image Περικοπή εικόνας + Image Tools Εργαλεία εικόνας + Remove Background… Αφαίρεση φόντου… + Remove Background Αφαίρεση φόντου + Background Φόντο + Edge Color Χρώμα άκρης + Picked Colors Επιλεγμένα χρώματα + Corner Color Χρώμα γωνιών + Contiguous Συνεχόμενα + Each Channel Κάθε κανάλι Edit Path Επεξεργασία διαδρομής Mask Μάσκα Crop Marks Σημάδια ξακρίσματος @@ -1087,6 +1097,8 @@ font-technology Variable Μεταβλητές Extrude & Bevel… Εξώθηση και λοξότμηση… 3D (Classic) 3D (κλασικό) Extrude & Bevel (Classic)… Εξώθηση και λοξότμηση (κλασικό)… + Revolve (Classic)… Περιστροφή γύρω από άξονα (κλασικό)… + Rotate (Classic)… Περιστροφή (κλασικό)… Surface Επιφάνεια Wireframe Συρματόπλεγμα No Shading Χωρίς σκίαση @@ -1364,6 +1376,14 @@ font-technology Variable Μεταβλητές Hair Space Πολύ λεπτό διάστημα Hand Tool Χέρι (Hand Tool) Hand-Drawn Σχεδιασμένο στο χέρι + Painted and Sketched Ζωγραφισμένο και σκιτσαρισμένο + Washed Blue Ξεπλυμένο μπλε + Bristle Ochre Ώχρα με πινέλο + Pastel Heather Παστέλ ρείκι + Charcoal Shade Σκιά με κάρβουνο + Ink Contour Περίγραμμα με μελάνι + Wet Ink Υγρό μελάνι + Fine Pen Λεπτή πένα Handles Λαβές Hard Light Έντονο φως Hard Mix Έντονη ανάμειξη @@ -1578,6 +1598,7 @@ font-technology Variable Μεταβλητές Include Linked Files Συμπερίληψη συνδεδεμένων αρχείων Include Metadata Συμπερίληψη μεταδεδομένων Include non-printing layers Συμπερίληψη μη εκτυπώσιμων επιπέδων + Write pages longer than 200 in at full size in points Εγγραφή σελίδων μεγαλύτερων από 200 in σε πλήρες μέγεθος, σε στιγμές Include SVG Code Συμπερίληψη κώδικα SVG Include Swatches for Tints Συμπερίληψη δειγμάτων για αποχρώσεις Inflate… Φούσκωμα… @@ -1830,6 +1851,8 @@ font-technology Variable Μεταβλητές Options: Επιλογές: Options… Επιλογές… Ordinals Τακτικοί αριθμοί + Organic Fades Οργανικές διαβαθμίσεις + Holographic Ολογραφικά Orientation Προσανατολισμός Orientation: Προσανατολισμός: Original Πρωτότυπο @@ -1878,6 +1901,7 @@ font-technology Variable Μεταβλητές Preset: Προεπιλογή: Presets: Προεπιλογές: Preview Προεπισκόπηση + Preview: Προεπισκόπηση: Previous Προηγούμενο Print Εκτύπωση Printer Εκτυπωτής @@ -1897,6 +1921,8 @@ font-technology Variable Μεταβλητές Quick Actions Γρήγορες ενέργειες Radial Ακτινικό Radial Gradient Ακτινωτό ντεγκραντέ + Conic Gradient Κωνικό ντεγκραντέ + Diamond Gradient Ρομβοειδές ντεγκραντέ Random Τυχαίο Range: Εύρος: Rasterize Μετατροπή σε εικονοστοιχεία @@ -1938,6 +1964,9 @@ font-technology Variable Μεταβλητές Right: Δεξιά: Rise… Ανύψωση… Roman Hanging Punctuation Κρεμαστή στίξη όρθιας γραφής + Korean Line Break Anywhere Αλλαγή γραμμής κορεατικών οπουδήποτε + East Asian Composition Settings Ρυθμίσεις σύνθεσης ανατολικής Ασίας + Korean Composition Settings Ρυθμίσεις κορεατικής σύνθεσης Rotate Περιστροφή Rotate View Tool Εργαλείο περιστροφής προβολής (Rotate View Tool) Trackpad Gesture to Rotate View Περιστροφή προβολής με χειρονομία στην επιφάνεια αφής @@ -2203,6 +2232,13 @@ axis Both Και τα δύο Dock Panel Αγκύρωση πάνελ Dock to Top Αγκύρωση επάνω Dock to Bottom Αγκύρωση κάτω + Control Bar Options Επιλογές γραμμής ελέγχου + Tool Options Επιλογές εργαλείου + Object Options Επιλογές αντικειμένου + Image Options Επιλογές εικόνας + Vertical Alignment Κατακόρυφη στοίχιση + Align and Distribute Στοίχιση και κατανομή + Document Options Επιλογές εγγράφου Dock Control Bar Αγκύρωση γραμμής ελέγχου @msg no library `{id}` Δεν υπάρχει βιβλιοθήκη με αναγνωριστικό `{id}` @msg select some type first Επιλέξτε πρώτα κάποιο κείμενο @@ -2346,10 +2382,13 @@ axis Both Και τα δύο @msg `groupColors` must be an array Το `groupColors` πρέπει να είναι πίνακας @msg `library` is a library id or name (see {list}) Το `library` είναι αναγνωριστικό ή όνομα βιβλιοθήκης (δείτε {list}) @msg `mode` applies to freeform gradients Το `mode` ισχύει για ντεγκραντέ ελεύθερης μορφής +@msg a negative `aspect` applies to conic gradients Το αρνητικό `aspect` ισχύει για κωνικά ντεγκραντέ +@msg `focal` applies to radial gradients Το `focal` ισχύει για ακτινικά ντεγκραντέ @msg `preserve` must be an object Το `preserve` πρέπει να είναι αντικείμενο @msg `globalAdjust` must be an object Το `globalAdjust` πρέπει να είναι αντικείμενο @msg `sampleSize` must be 1, 3 or 5 Το `sampleSize` πρέπει να είναι 1, 3 ή 5 @msg `stops` must be an array Το `stops` πρέπει να είναι πίνακας +@msg `{key}` must be an array Το `{key}` πρέπει να είναι πίνακας @msg `svg` must be an object of SVG options (see document.formats) Το `svg` πρέπει να είναι αντικείμενο επιλογών SVG (δείτε document.formats) @msg `{_1}` is no save command Το `{_1}` δεν είναι εντολή αποθήκευσης @msg `{area}` is no recovery area name Το `{area}` δεν είναι όνομα περιοχής ανάκτησης @@ -2363,6 +2402,7 @@ axis Both Και τα δύο @msg `{key}` must be a number, not {v} Το `{key}` πρέπει να είναι αριθμός, όχι {v} @msg {key} must be Unix seconds (an integer) or null {key}: πρέπει να είναι χρόνος Unix σε δευτερόλεπτα (ακέραιος) ή null @msg `{key}` must be a string Το `{key}` πρέπει να είναι συμβολοσειρά +@msg `{key}` must be a profile name or null Το `{key}` πρέπει να είναι όνομα προφίλ ή null @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 between {min} and {max} (got {x}) Το `{key}` πρέπει να είναι μεταξύ {min} και {max} (δόθηκε {x}) @@ -3050,6 +3090,15 @@ theme Appearance Εμφάνιση Open the URL in the web browser Άνοιγμα της διεύθυνσης στο πρόγραμμα περιήγησης Optical Οπτική Optical Margin Alignment Οπτική στοίχιση περιθωρίου + Dynamic Text Δυναμικό κείμενο + Dynamic Text Presets Προεπιλογές δυναμικού κειμένου + Arch Αψίδα +@msg select point type or type on a path επιλέξτε κείμενο σημείου ή κείμενο σε διαδρομή +@msg type on a path in a thread cannot use Dynamic Text: {frames} το κείμενο σε διαδρομή μέσα σε συνδεδεμένο κείμενο δεν μπορεί να χρησιμοποιήσει δυναμικό κείμενο: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} κείμενο σε ανοιχτή ή σύνθετη διαδρομή δεν μπορεί να κεντραριστεί επάνω ή κάτω: {open} +@msg type on a path with no length or no height cannot be centered: {flat} κείμενο σε διαδρομή χωρίς μήκος ή χωρίς ύψος δεν μπορεί να κεντραριστεί: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} το κείμενο σε διαδρομή μέσα σε συνδεδεμένο κείμενο δεν μπορεί να κεντραριστεί επάνω ή κάτω: {frames} +@msg select type on a closed path επιλέξτε κείμενο σε κλειστή διαδρομή Optimize for fast web view Βελτιστοποίηση για γρήγορη προβολή στον ιστό Options for Selection… Επιλογές για την επιλογή… or more spaces with a tab ή περισσότερα διαστήματα με στηλοθέτη @@ -3257,6 +3306,8 @@ digits Malayalam Μαλαγιάλαμ Randomly change saturation and brightness Τυχαία αλλαγή κορεσμού και φωτεινότητας Raster Effects Εφέ ράστερ Raster File Format: Μορφή αρχείου ράστερ: + Include Placed Images Συμπερίληψη τοποθετημένων εικόνων + Include Fill Hatches Συμπερίληψη διαγραμμίσεων γεμισμάτων Raster Sample Size: Μέγεθος δείγματος ράστερ: Raster/Vector Balance: Ισορροπία ράστερ/διανυσμάτων: Rasterize Unsupported Art Μετατροπή μη υποστηριζόμενου σχεδίου σε ράστερ @@ -3404,6 +3455,10 @@ digits Malayalam Μαλαγιάλαμ Replace Font Αντικατάσταση γραμματοσειράς Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Αντικαταστήστε το με άλλο αρχείο ή αγνοήστε το: οι εικόνες του θα συνεχίσουν να εμφανίζουν την προεπισκόπηση που αποθηκεύτηκε στο έγγραφο. Replace Spine Αντικατάσταση κεντρικής καμπύλης + Create Spine Δημιουργία κεντρικής καμπύλης + Create Spine: Δημιουργία κεντρικής καμπύλης: + Always Πάντα + Never Ποτέ Replace Symbol Αντικατάσταση συμβόλου Reset Transformation Επαναφορά μετασχηματισμού Replace With Font Αντικατάσταση με γραμματοσειρά @@ -3632,6 +3687,15 @@ digits Malayalam Μαλαγιάλαμ Stun Pulse Ζάλη Stealth Fade Αορασία Shield Buff Ασπίδα + Textures Υφές + Fine Grain Λεπτός κόκκος + Canvas Weave Ύφανση καμβά + Burlap Sack Λινάτσα + Cracked Glaze Ραγισμένο γλάσο + Mosaic Floor Ψηφιδωτό δάπεδο + Quilted Squares Καπιτονέ τετράγωνα + Leaded Glass Μολυβδόδετο γυαλί + Damp Paper Υγρό χαρτί Shape Builder Regions Περιοχές δημιουργίας σχημάτων Shape Effects Εφέ σχημάτων Shape Mode Λειτουργία σχήματος @@ -3677,6 +3741,7 @@ digits Malayalam Μαλαγιάλαμ Show Modified Εμφάνιση τροποποιημένων Show Note Εμφάνιση σημείωσης Show Options Εμφάνιση επιλογών + Show Recent Colors Εμφάνιση πρόσφατων χρωμάτων Show Original Path Εμφάνιση αρχικής διαδρομής Open this dialog with these settings next time Άνοιγμα αυτού του παραθύρου με αυτές τις ρυθμίσεις την επόμενη φορά Auto-Simplify Αυτόματη απλοποίηση @@ -3904,6 +3969,8 @@ digits Malayalam Μαλαγιάλαμ Scale at Center Κλιμάκωση από το κέντρο Up/Down: Πάνω/Κάτω: Left/Right: Αριστερά/Δεξιά: + Tate-chu-yoko Up/Down Tate-chu-yoko πάνω/κάτω + Tate-chu-yoko Left/Right Tate-chu-yoko αριστερά/δεξιά Temperature/Tint… Θερμοκρασία/Απόχρωση… Templates Folder Φάκελος προτύπων Text Displayed in Cell: Κείμενο που εμφανίζεται στο κελί: @@ -3957,6 +4024,8 @@ digits Malayalam Μαλαγιάλαμ Toolbar: Single/Double Column Γραμμή εργαλείων: Μονή/Διπλή στήλη Toolbar: Add Tool Γραμμή εργαλείων: Προσθήκη εργαλείου Toolbar: Remove Tool Γραμμή εργαλείων: Αφαίρεση εργαλείου + Add Tool… Προσθήκη εργαλείου… + Remove Tool Αφαίρεση εργαλείου Toolbar: Reset Γραμμή εργαλείων: Επαναφορά Top in Front Επάνω μπροστά Top-Justified Tab Στηλοθέτης επάνω στοίχισης @@ -4002,6 +4071,8 @@ digits Malayalam Μαλαγιάλαμ Type on a Path Κείμενο σε διαδρομή Type on a Path Options Επιλογές κειμένου σε διαδρομή Type on a Path Options… Επιλογές κειμένου σε διαδρομή… + Center on Top Κεντράρισμα επάνω + Center on Bottom Κεντράρισμα κάτω Type on a Path Tool Κείμενο σε διαδρομή (Type on a Path Tool) Type Orientation Προσανατολισμός κειμένου Type stays text, and every stroke is a line with its lineweight and dashes. Το κείμενο διατηρείται ως κείμενο και κάθε περίγραμμα γίνεται γραμμή με το πάχος και τις παύλες του. @@ -4137,6 +4208,7 @@ digits Malayalam Μαλαγιάλαμ Width Profiles Προφίλ πλάτους Width Tool Πλάτος (Width Tool) Working CMYK (don't tag) Χώρος εργασίας CMYK (χωρίς ετικέτα) + Working RGB (don't tag) Χώρος εργασίας RGB (χωρίς ετικέτα) Workspace {i} Χώρος εργασίας {i} Wrinkle Tool Πτυχώσεις (Wrinkle Tool) Write Layers Εγγραφή επιπέδων @@ -4321,6 +4393,7 @@ digits Malayalam Μαλαγιάλαμ @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller η σελίδα του πίνακα σχεδίασης {n} είναι {size}, μεγαλύτερη από το όριο σελίδας PDF των 14.400 pt (200 in): γράφεται με UserUnit {unit}, οπότε οι εφαρμογές που αγνοούν το UserUnit την εμφανίζουν τόσες φορές μικρότερη @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in η σελίδα του πίνακα σχεδίασης {n} είναι {size}, μεγαλύτερη από το όριο σελίδας PDF των 14.400 pt (200 in): οι σελίδες {label} γράφονται χωρίς UserUnit, σε στιγμές, και οι εφαρμογές που τηρούν το όριο κόβουν τη σελίδα στις 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 το PDF 1.5 δεν έχει UserUnit, που χρειάζεται μια σελίδα μεγαλύτερη από 14.400 pt (200 in) για να κρατήσει το μέγεθός της: το αρχείο γράφεται ως PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 το PDF 1.4 δεν έχει UserUnit, που χρειάζεται μια σελίδα μεγαλύτερη από 14.400 pt (200 in) για να μείνει εντός του ορίου σελίδας του PDF/A-2, 14.400 μονάδων: το αρχείο γράφεται ως PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units η σελίδα του πίνακα σχεδίασης {n} είναι {size}, πολύ μακριά και στενή για τις πλευρές σελίδας PDF από 3 έως 14.400 μονάδες: γράφεται με UserUnit {unit}, που κρατά τη μικρή πλευρά στις 3 μονάδες ή περισσότερο, και οι εφαρμογές που τηρούν το όριο κόβουν τη μεγάλη πλευρά στις 14.400 μονάδες @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard τα αρχεία {label} δέχονται πραγματικούς αριθμούς έως {max}, και η σελίδα του πίνακα σχεδίασης {n}, μήκους {side} pt, χρειάζεται μεγαλύτερους: επιλέξτε PDF 1.6 ή νεότερο χωρίς πρότυπο PDF/X, ή μικρότερο πίνακα σχεδίασης @msg invalid image data for `{0}` μη έγκυρα δεδομένα εικόνας για `{0}` @@ -4469,6 +4542,8 @@ digits Malayalam Μαλαγιάλαμ @msg not a stored central record δεν είναι αποθηκευμένη κεντρική εγγραφή @msg not a valid plug-in module: {0} δεν είναι έγκυρη μονάδα προσθέτου: {0} @msg not an EMF or WMF file δεν είναι αρχείο EMF ή WMF +@msg not an HP-GL file δεν είναι αρχείο HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors το `pens` πρέπει να είναι πίνακας 1 έως 255 χρωμάτων #rrggbb @msg not found δεν βρέθηκε @msg not in pattern editing mode δεν βρίσκεστε σε λειτουργία επεξεργασίας μοτίβου @msg finish editing the pattern first ολοκληρώστε πρώτα την επεξεργασία του μοτίβου @@ -4542,6 +4617,14 @@ digits Malayalam Μαλαγιάλαμ @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} σημεία αγκύρωσης, περισσότερα από όσα μπορεί να εμφανίσει ομαλά το έγγραφο: αυξήστε τον Θόρυβο, μειώστε τις Διαδρομές ή τα Χρώματα ή επιλέξτε προεπιλογή χαμηλότερης πιστότητας @msg select an envelope επιλέξτε περίβλημα @msg select an image επιλέξτε εικόνα +@msg `background` must be edges, corners or colors το `background` πρέπει να είναι edges, corners ή colors +@msg `match` must be distance or channels το `match` πρέπει να είναι distance ή channels +@msg `{key}` must be from 0 to 100 το `{key}` πρέπει να είναι από 0 έως 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue το `colors` πρέπει να περιέχει 1 έως 16 χρώματα, το καθένα σε δεκαεξαδική μορφή (#rrggbb ή #rgb) ή ως black, white, red, green ή blue +@msg the linked image shows its preview: embed or relink it first η συνδεδεμένη εικόνα εμφανίζει την προεπισκόπησή της: ενσωματώστε ή επανασυνδέστε την πρώτα +@msg a CMYK image has no transparency to set μια εικόνα CMYK δεν έχει διαφάνεια για να οριστεί +@msg every pixel matches the background: no image would be left κάθε εικονοστοιχείο ταιριάζει με το φόντο: δεν θα έμενε καμία εικόνα +@msg an image of {w} × {h} pixels is too large to change η εικόνα {w} × {h} εικονοστοιχείων είναι υπερβολικά μεγάλη για να αλλάξει @msg select an object in perspective επιλέξτε αντικείμενο σε προοπτική @msg select artwork (or a colour group) to recolor επιλέξτε σχέδιο (ή ομάδα χρωμάτων) για επαναχρωματισμό @msg Recolor completed; {locked} and {hidden} were left unchanged Ο επαναχρωματισμός ολοκληρώθηκε· χωρίς αλλαγή: {locked} και {hidden} @@ -4648,7 +4731,7 @@ digits Malayalam Μαλαγιάλαμ @msg unknown format άγνωστη μορφή @msg unknown format `{f}` (Save writes {_1}) άγνωστη μορφή `{f}` (η Αποθήκευση υποστηρίζει {_1}) @msg unknown freeform mode `{m}` (points, lines) άγνωστη λειτουργία ελεύθερης μορφής `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) άγνωστος τύπος ντεγκραντέ `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) άγνωστος τύπος ντεγκραντέ `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` άγνωστη επισήμανση `{h}` @msg unknown option `{path}.{k}` άγνωστη επιλογή `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) άγνωστη επιλογή υπερεκτύπωσης `{o}` (preserve, simulate ή discard) @@ -4886,6 +4969,8 @@ digits Malayalam Μαλαγιάλαμ @msg invalid object id {value}: expected a non-negative integer μη έγκυρο αναγνωριστικό αντικειμένου {value}: αναμένεται μη αρνητικός ακέραιος @msg `{key}` entry {index} is {value}, not a non-negative integer object id το στοιχείο {index} του `{key}` είναι {value}, όχι αναγνωριστικό αντικειμένου (μη αρνητικός ακέραιος) @msg no such object id {value} δεν υπάρχει αντικείμενο με αναγνωριστικό {value} +@msg id {value} is a ruler guide, not an object το αναγνωριστικό {value} ανήκει σε οδηγό, όχι σε αντικείμενο +@msg a ruler guide goes only directly in a layer or sublayer ένας οδηγός μπορεί να βρίσκεται μόνο απευθείας σε επίπεδο ή υποεπίπεδο @msg id {value} is a layer, not an object το αναγνωριστικό {value} είναι επίπεδο, όχι αντικείμενο @msg id {value} is a layer, not an object; move layers with layer.move το αναγνωριστικό {value} είναι επίπεδο, όχι αντικείμενο· μετακινήστε τα επίπεδα με το layer.move @msg automation filesystem access is not granted: read authority is absent: {path} δεν έχει επιτραπεί πρόσβαση αυτοματισμού στο σύστημα αρχείων: δεν υπάρχει δικαίωμα ανάγνωσης: {path} @@ -4915,7 +5000,13 @@ digits Malayalam Μαλαγιάλαμ @msg the HEIC or HEIF file holds a kind of image that can't be read το αρχείο HEIC ή HEIF περιέχει είδος εικόνας που δεν είναι δυνατό να διαβαστεί @msg HEIC and HEIF images can't be opened in this build οι εικόνες HEIC και HEIF δεν μπορούν να ανοίξουν σε αυτή την έκδοση @msg the PSD image is too large to read ({_1} × {_2} pixels) η εικόνα PSD είναι πολύ μεγάλη για ανάγνωση ({_1} × {_2} εικονοστοιχεία) -@msg zipped 32-bit PSD image data with prediction can't be read τα συμπιεσμένα δεδομένα εικόνας PSD 32 bit με πρόβλεψη δεν διαβάζονται +@msg zipped 1-bit PSD image data with prediction can't be read τα συμπιεσμένα δεδομένα εικόνας PSD 1 bit με πρόβλεψη δεν διαβάζονται +@msg the PSD file's layer data uses an unknown compression ({m}) τα δεδομένα επιπέδων του αρχείου PSD χρησιμοποιούν άγνωστη συμπίεση ({m}) +@msg the PSD file's layer records are damaged οι εγγραφές επιπέδων του αρχείου PSD είναι κατεστραμμένες +@msg the PSD file's layer groups are nested too deeply οι ομάδες επιπέδων του αρχείου PSD είναι ένθετες σε υπερβολικό βάθος +@msg a layer of the PSD file is too large to read ένα επίπεδο του αρχείου PSD είναι πολύ μεγάλο για ανάγνωση +@msg the PSD file's layers take more memory to read than allowed τα επίπεδα του αρχείου PSD χρειάζονται περισσότερη μνήμη για ανάγνωση από όση επιτρέπεται +@msg the layers can't be read ({e}): the file opened as its merged image τα επίπεδα δεν μπορούν να διαβαστούν ({e}): το αρχείο άνοιξε ως η συγχωνευμένη εικόνα του @msg {depth}-bit PSD files in this colour mode can't be read τα αρχεία PSD {depth} bit δεν διαβάζονται σε αυτήν τη λειτουργία χρώματος @msg the PSD file is cut short το αρχείο PSD είναι περικομμένο @msg the PSD file's header is damaged η κεφαλίδα του αρχείου PSD είναι κατεστραμμένη @@ -5383,6 +5474,11 @@ digits Malayalam Μαλαγιάλαμ to set spacing and orientation για ορισμό απόστασης και προσανατολισμού : : Light behind the object Φως πίσω από το αντικείμενο + Shadows Σκιές + Distance from Object Απόσταση από το αντικείμενο + Shadow Bounds Όρια σκιάς + Behind Object Πίσω από το αντικείμενο + Below Object Κάτω από το αντικείμενο 3D Lighting Preset Προεπιλογή φωτισμού 3D Standard Τυπικός Diffuse Διάχυτος @@ -5733,7 +5829,7 @@ effect Points Σημεία @msg span must be "object" or "selection", got {v} το span πρέπει να είναι "object" ή "selection", δόθηκε {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 span: το "selection" τοποθετεί γραμμικό ή ακτινικό ντεγκραντέ, όχι ελεύθερης μορφής +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: το "selection" τοποθετεί γραμμικό, ακτινικό, κωνικό ή ρομβοειδές ντεγκραντέ, όχι ελεύθερης μορφής @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: το "selection" τοποθετεί το ίδιο το ντεγκραντέ: παραλείψτε τα `start` και `end` (το τοποθετούν ήδη σε συντεταγμένες εγγράφου) @msg the Color Picker is not open ο επιλογέας χρώματος δεν είναι ανοιχτός @msg the Simplify slider is not open ο ρυθμιστής Απλοποίησης δεν είναι ανοιχτός @@ -5902,6 +5998,7 @@ effect Points Σημεία Ruby Ruby Geometric Guides Γεωμετρικοί οδηγοί Geometric Patterns Γεωμετρικά μοτίβα + Grit Textures Κοκκώδεις υφές Ease In Ομαλή αρχή Ease Out Ομαλό τέλος Ease In Out Ομαλή αρχή και τέλος @@ -5960,6 +6057,8 @@ axis Y Axis Άξονας Y Version: {version} Έκδοση: {version} Install “{name}” in place of the plug-in with the same ID? Να εγκατασταθεί το «{name}» στη θέση του πρόσθετου με το ίδιο αναγνωριστικό; This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Αυτό το αρχείο δεν είναι το πρόσθετο που ήταν εγκατεστημένο πριν με αυτό το αναγνωριστικό. Παίρνει τις ρυθμίσεις και την κρυφή μνήμη που διατηρούνται για αυτό το αναγνωριστικό. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Μια αυτοματοποίηση ζήτησε να εγκατασταθεί αυτό το πρόσθετο. Για να το εγκαταστήσετε, επιλέξτε Αντικείμενο › Πρόσθετα › Εγκατάσταση προσθέτου… μόνοι σας. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Μια αυτοματοποίηση ζήτησε να εγκατασταθεί αυτό το πρόσθετο. Για να το εγκαταστήσετε, επιλέξτε Αντικείμενο › Πρόσθετα › Εγκατάσταση προσθέτου… μόνοι σας. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees το «{name}» είναι άλλη λειτουργική μονάδα από το πρόσθετο με αναγνωριστικό {_1} και θα έπαιρνε τις ρυθμίσεις και την κρυφή μνήμη που διατηρούνται για αυτό: εγκαταστήστε το με `replace: true` μόλις συμφωνήσει ο χρήστης File SHA-256: {hash} SHA-256 αρχείου: {hash} Read the objects it is given Ανάγνωση των αντικειμένων που του δίνονται @@ -6005,6 +6104,11 @@ axis Y Axis Άξονας Y @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) προϋπολογισμός αντικειμένων (περισσότερα από {MAX_OBJECTS} αντικείμενα μόνο για ανάγνωση) +@msg instruction budget προϋπολογισμός εντολών +@msg time budget χρονικός προϋπολογισμός +@msg memory budget (the selection is too large to hand over) προϋπολογισμός μνήμης (η επιλογή είναι πολύ μεγάλη για να παραδοθεί) +@msg output size ({what} is {len} bytes, limit {max}) μέγεθος εξόδου ({what}: {len} byte, όριο {max}) +@msg the plug-in's grant can't be removed from the plug-in store η άδεια του πρόσθετου δεν μπορεί να αφαιρεθεί από τον χώρο αποθήκευσης πρόσθετων @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it το δικαίωμα `{shown}` είναι δεσμευμένο για μεταγενέστερο API προσθέτων· αυτός ο κεντρικός υπολογιστής δεν το παραχωρεί @msg unknown permission `{shown}` άγνωστο δικαίωμα `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants το «{name}» ζητά τα δικαιώματα {asked}: πρέπει να τα εγκρίνει ένα άτομο στην εφαρμογή επιφάνειας εργασίας ή περάστε `grant` σε μια συνεδρία που ξεκίνησε με --allow-plugin-grants @@ -6017,6 +6121,12 @@ axis Y Axis Άξονας Y @msg command {name}: `label` must be 1-64 printable characters εντολή {name}: το `label` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter εντολή {name}: χρησιμοποιήστε αναγνωριστικό 1-{MAX_COMMAND_ID} χαρακτήρων από a-z 0-9 _ που αρχίζει με γράμμα @msg command {name}: {e} εντολή {name}: {e} +@msg manifest: {e} αρχείο δηλώσεων: {e} +@msg manifest: {e} at line {line} column {column} αρχείο δηλώσεων: {e} (γραμμή {line}, στήλη {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` το `commands` πρέπει να είναι λίστα εντολών, καθεμία με `id` και `label` +@msg command {name} must be an object with an `id` and a `label` η εντολή {name} πρέπει να είναι αντικείμενο με `id` και `label` +@msg missing field `{key}` λείπει το πεδίο `{key}` +@msg duplicate field `{key}` το πεδίο `{key}` εμφανίζεται δύο φορές @msg only a filter or a live effect declares `commands` μόνο ένα φίλτρο ή ένα δυναμικό εφέ δηλώνει `commands` @msg “{name}” › {label}: {e} «{name}» › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed η λειτουργική μονάδα δεν έχει το SHA-256 που δίνει το `hash`: δεν εγκαταστάθηκε τίποτα @@ -6041,6 +6151,16 @@ axis Y Axis Άξονας Y @msg message must be text Το message πρέπει να είναι κείμενο @msg allowContinue must be true or false Το allowContinue πρέπει να είναι true ή false @msg Batch cannot play an action with a stop Η μαζική επεξεργασία δεν μπορεί να αναπαράγει ενέργεια με διακοπή + Insert Menu Item… Εισαγωγή στοιχείου μενού… + Insert Menu Item Εισαγωγή στοιχείου μενού + Menu Item: Στοιχείο μενού: + No menu item matches. Κανένα στοιχείο μενού δεν ταιριάζει. + Several menu items match. Choose one from the list. Ταιριάζουν πολλά στοιχεία μενού. Επιλέξτε ένα από τη λίστα. + Items that open a dialog, and File, Window and Help menu items, are not listed. Τα στοιχεία που ανοίγουν παράθυρο διαλόγου και τα στοιχεία των μενού «Αρχείο», «Παράθυρο» και «Βοήθεια» δεν εμφανίζονται. +@msg command must be text Το command πρέπει να είναι κείμενο +@msg no menu item that can be inserted runs this command κανένα στοιχείο μενού που μπορεί να εισαχθεί δεν εκτελεί αυτή την εντολή +@msg the action already has 10,000 steps η ενέργεια έχει ήδη 10.000 βήματα +@msg the action set would be larger than 8 MiB το σύνολο ενεργειών θα ξεπερνούσε τα 8 MiB Playback Options Επιλογές αναπαραγωγής Accelerated Επιταχυμένα Step by Step Βήμα προς βήμα @@ -6079,6 +6199,12 @@ axis Y Axis Άξονας Y Crosshair Σταυρόνημα Checkpoint Σημείο ελέγχου Inventory Icons Εικονίδια αποθέματος + Skill Icons Εικονίδια δεξιοτήτων + Attack Επίθεση + Defend Άμυνα + Heal Θεραπεία + Buff Ενίσχυση + Ult Ult Sword Ξίφος Shield Ασπίδα Potion Φίλτρο @@ -6143,7 +6269,23 @@ axis Y Axis Άξονας Y Dash Trail Διακεκομμένο ίχνος Speed Line Γραμμή ταχύτητας Game Trails Ίχνη παιχνιδιού + Energy Beams Δέσμες ενέργειας + Laser Bolt Βολίδα λέιζερ + Plasma Arc Τόξο πλάσματος + Charge Wave Κύμα φόρτισης + Spark Trail Ίχνος σπινθήρων Calligraphic Nibs Καλλιγραφικές πένες + Bristle Brushes Πινέλα με τρίχες + Fine Liner Λεπτή γραμμή + Pointed Flat Μυτερό πλακέ + Stubby Round Κοντό στρογγυλό + Dry Scrub Ξηρό τρίψιμο + Soft Dome Μαλακός θόλος + Filbert Γλώσσα γάτας + Angled Round Λοξό στρογγυλό + Angled Flat Λοξό πλακέ + Fan Blender Βεντάλια ανάμειξης + Grass Fan Βεντάλια για γρασίδι Pattern Borders Περιθώρια μοτίβου Scatter Shapes Σχήματα διασποράς Save Brush Library… Αποθήκευση βιβλιοθήκης πινέλων… @@ -6340,9 +6482,12 @@ anchor Points: Σημεία: @msg {label} must be a number Το {label} πρέπει να είναι αριθμός @msg {label} must be a number of at least 0.1 Το {label} πρέπει να είναι αριθμός τουλάχιστον 0,1 Advanced Character Formats Σύνθετες μορφές χαρακτήρων + Basic Paragraph Formats Βασικές μορφές παραγράφου + Composition Σύνθεση Horizontal Scale Οριζόντια κλίμακα Vertical Scale Κατακόρυφη κλίμακα @msg {label} must be a number from {min} to {max} Το {label} πρέπει να είναι αριθμός από {min} έως {max} +@msg {label} must be a whole number from {min} to {max} Το {label} πρέπει να είναι ακέραιος αριθμός από {min} έως {max} Character Color Χρώμα χαρακτήρων OpenType Features Χαρακτηριστικά OpenType Stylistic Sets Στιλιστικά σύνολα @@ -6350,6 +6495,10 @@ anchor Points: Σημεία: @msg features lists at most {max} tags Το features περιέχει έως {max} ετικέτες @msg unknown OpenType feature `{t}` άγνωστο χαρακτηριστικό OpenType `{t}` @msg {label} must be a number above 0 and at most {max} Το {label} πρέπει να είναι αριθμός μεγαλύτερος από 0 και έως {max} +@msg {label} must be at most {max} characters Το {label} πρέπει να έχει έως {max} χαρακτήρες +@msg {label} must be one character Το {label} πρέπει να είναι ένας χαρακτήρας +@msg at most {max} tab stops έως {max} στάσεις στηλοθέτη +@msg unknown align `{other}` άγνωστη στοίχιση `{other}` @msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6512,6 +6661,12 @@ breakText Glyphs Γλύφοι Delete the selected brushes? Να διαγραφούν τα επιλεγμένα πινέλα; Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Περιγράμματα χρησιμοποιούν ένα ή περισσότερα από αυτά τα πινέλα. Να αφαιρεθούν τα πινέλα από αυτά τα περιγράμματα και να διαγραφούν τα πινέλα; Remove Strokes Αφαίρεση περιγραμμάτων + Place Brush Art Τοποθέτηση σχεδίου πινέλου + Replace Brush Art Αντικατάσταση σχεδίου πινέλου + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Περιγράμματα χρησιμοποιούν αυτό το πινέλο. Να εφαρμοστεί το νέο σχέδιο σε αυτά τα περιγράμματα ή να μείνουν ως έχουν και να προστεθεί αντίγραφο του πινέλου με το νέο σχέδιο; + Apply to Strokes Εφαρμογή στα περιγράμματα + Leave Strokes Διατήρηση περιγραμμάτων +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` δεν έχει σχέδιο (έχουν μόνο τα πινέλα διασποράς, σχεδίου και μοτίβου) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Εργαλεία διάταξης Arrange in Grid… Διάταξη σε πλέγμα… @@ -6707,6 +6862,11 @@ breakText Glyphs Γλύφοι @msg only an exporter or an importer declares `extensions` μόνο ένα πρόσθετο εξαγωγής ή εισαγωγής δηλώνει `extensions` @msg an importer always gets an import's budget: leave `budget` out ένα πρόσθετο εισαγωγής παίρνει πάντα τον προϋπολογισμό μιας εισαγωγής: παραλείψτε το `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Αντιγραφή πληροφοριών αντιμετώπισης προβλημάτων +@msg Copied the troubleshooting info Οι πληροφορίες αντιμετώπισης προβλημάτων αντιγράφηκαν +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Η τελευταία συνεδρία του VectorCraft σταμάτησε να αποκρίνεται πριν κλείσει. Βοήθεια › Αντιγραφή πληροφοριών αντιμετώπισης προβλημάτων αντιγράφει τις λεπτομέρειες για αναφορά σφάλματος + # Safe Mode Safe Mode… Ασφαλής λειτουργία… Safe Mode Ασφαλής λειτουργία @@ -6727,6 +6887,8 @@ breakText Glyphs Γλύφοι # Align to Pixel Grid Align to Pixel Grid Στοίχιση στο πλέγμα εικονοστοιχείων + Align New Objects to Pixel Grid Στοίχιση νέων αντικειμένων στο πλέγμα εικονοστοιχείων + Not Aligned to Pixel Grid Μη στοιχισμένα στο πλέγμα εικονοστοιχείων @msg only paths and compound paths can be aligned to the pixel grid μόνο διαδρομές και σύνθετες διαδρομές μπορούν να στοιχιστούν στο πλέγμα εικονοστοιχείων @msg side is left or right, not `{s}` το side είναι left ή right, όχι `{s}` Ignore All Παράβλεψη όλων @@ -6757,8 +6919,33 @@ breakText Glyphs Γλύφοι @plural {n} line cut|{n} lines cut {n} γραμμή περικόπηκε|{n} γραμμές περικόπηκαν @msg `first` and `last` must be numbers of lines the console holds, first before last Τα `first` και `last` πρέπει να είναι αριθμοί γραμμών που κρατά η κονσόλα, το `first` πριν από το `last` +# Learn panel + Learn Εκμάθηση + Explore tutorials Εξερεύνηση οδηγών εκμάθησης + For you Για εσάς + Skills Δεξιότητες + Get started Πρώτα βήματα + Quick skill guide Γρήγορος οδηγός δεξιοτήτων + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Σύντομοι πρακτικοί οδηγοί για τα βασικά εργαλεία, ομαδοποιημένοι ανά δεξιότητα. Επιλέξτε μια δεξιότητα για να δείτε τους οδηγούς της. + List Tutorials Λίστα οδηγών εκμάθησης + Show Tutorial Εμφάνιση οδηγού εκμάθησης +@msg missing `tutorial` (see learn.list) λείπει το `tutorial` (δείτε learn.list) +@msg unknown tutorial `{id}` (see learn.list) άγνωστος οδηγός εκμάθησης `{id}` (δείτε learn.list) + # Deferred plug-in effects Refresh Deferred Effects Ανανέωση εφέ σε αναμονή Deferred Effects Εφέ σε αναμονή @msg no plug-in effect is deferred κανένα εφέ προσθέτου δεν είναι σε αναμονή @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Άνοιξε με {n} εφέ προσθέτου σε αναμονή. Το Εφέ › Ανανέωση εφέ σε αναμονή το εκτελεί.|Άνοιξε με {n} εφέ προσθέτων σε αναμονή. Το Εφέ › Ανανέωση εφέ σε αναμονή τα εκτελεί. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Εργαλεία κοπής + Stencil Bridges… Γέφυρες στένσιλ… + Stencil Bridges Γέφυρες στένσιλ + Shortest Crossing Συντομότερη διέλευση + Direction Κατεύθυνση +@msg The selected art has no islands to bridge Το επιλεγμένο γραφικό δεν έχει νησίδες για γεφύρωση +@msg No bridge of this width fits across the selected art Καμία γέφυρα αυτού του πλάτους δεν χωράει στο επιλεγμένο γραφικό +@msg Some islands could not be joined to the area around the art Ορισμένες νησίδες δεν ήταν δυνατό να συνδεθούν με την περιοχή γύρω από το γραφικό +@msg `width` must be from {lo} to {hi} pt Το `width` πρέπει να είναι από {lo} έως {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} Το `count` πρέπει να είναι ακέραιος από 1 έως {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c0e50d82e9..7ee7980085 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -262,6 +262,7 @@ font-technology Variable Variables Asset Export Settings Ajustes de exportación de recursos Assets Recursos Assign Asignar + Assign Profile Asignar perfil Assign Profile… Asignar perfil… Assign: Asignar: Attach to Active Plane Adjuntar al plano activo @@ -700,6 +701,15 @@ font-technology Variable Variables Created: Creado: Crop Recortar Crop Image Recortar imagen + Image Tools Herramientas de imagen + Remove Background… Quitar fondo… + Remove Background Quitar fondo + Background Fondo + Edge Color Color del borde + Picked Colors Colores elegidos + Corner Color Color de las esquinas + Contiguous Contiguo + Each Channel Cada canal Edit Path Editar trazado Mask Máscara Crop Marks Marcas de corte @@ -1143,6 +1153,8 @@ font-technology Variable Variables Extrude & Bevel… Extrusión y biselado… 3D (Classic) 3D (clásico) Extrude & Bevel (Classic)… Extrusión y biselado (clásico)… + Revolve (Classic)… Revolución (clásico)… + Rotate (Classic)… Rotar (clásico)… Surface Superficie Wireframe Malla No Shading Sin sombreado @@ -1443,6 +1455,14 @@ font-technology Variable Variables Hair Space Espacio fino Hand Tool Herramienta Mano Hand-Drawn Dibujado a mano + Painted and Sketched Pintado y bocetado + Washed Blue Azul lavado + Bristle Ochre Ocre de cerdas + Pastel Heather Brezo pastel + Charcoal Shade Sombra al carboncillo + Ink Contour Contorno de tinta + Wet Ink Tinta húmeda + Fine Pen Plumilla fina Handles Manejadores Hard Light Luz fuerte Hard Mix Mezcla definida @@ -1659,6 +1679,7 @@ font-technology Variable Variables Include Linked Files Incluir archivos vinculados Include Metadata Incluir metadatos Include non-printing layers Incluir capas no imprimibles + Write pages longer than 200 in at full size in points Escribir las páginas de más de 200 in a tamaño real, en puntos Include SVG Code Incluir código SVG Include Swatches for Tints Incluir muestras para matices Inflate… Inflar… @@ -2334,12 +2355,23 @@ font-technology Variable Variables Open… Abrir… Optical Óptico Optical Margin Alignment Alineación óptica de márgenes + Dynamic Text Texto dinámico + Dynamic Text Presets Ajustes preestablecidos de texto dinámico + Arch Bóveda +@msg select point type or type on a path seleccione texto de punto o texto en trazado +@msg type on a path in a thread cannot use Dynamic Text: {frames} el texto en trazado de un texto enlazado no puede usar texto dinámico: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} el texto en un trazado abierto o compuesto no se puede centrar arriba o abajo: {open} +@msg type on a path with no length or no height cannot be centered: {flat} el texto en un trazado sin longitud o sin altura no se puede centrar: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} el texto en trazado de un texto enlazado no se puede centrar arriba o abajo: {frames} +@msg select type on a closed path seleccione texto en un trazado cerrado Optimize for fast web view Optimizar para vista web rápida Optimized Optimizado Options Opciones Options for Selection… Opciones de la selección… Options: Opciones: Options… Opciones… + Organic Fades Desvanecidos orgánicos + Holographic Holográficos or more spaces with a tab o más espacios por una tabulación Order: Orden: Ordinals Ordinales @@ -2531,6 +2563,7 @@ font-technology Variable Variables Presets: Preajustes: Press Presiona Preview Vista previa + Preview: Vista previa: Preview All Layers Previsualizar todas las capas Preview in Browser Previsualizar en el navegador Preview in Browser needs the desktop app (the web downloads files instead) Previsualizar en el navegador requiere la aplicación de escritorio (la versión web descarga los archivos) @@ -2609,6 +2642,8 @@ digits Malayalam Malayálam Radial Radial Radial Glows Resplandores radiales Radial Gradient Degradado radial + Conic Gradient Degradado cónico + Diamond Gradient Degradado de rombo Radius 1 Radio 1 Radius 2 Radio 2 Radius1 Radio1 @@ -2621,6 +2656,8 @@ digits Malayalam Malayálam Range: Rango: Raster Effects Efectos de rasterización Raster File Format: Formato de archivo ráster: + Include Placed Images Incluir imágenes colocadas + Include Fill Hatches Incluir sombreados de relleno Raster Sample Size: Tamaño de muestra ráster: Raster/Vector Balance: Equilibrio ráster/vectorial: Rasterize Rasterizar @@ -2802,6 +2839,10 @@ digits Malayalam Malayálam Replace Font Reemplazar fuente Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Reemplázalo con otro archivo o ignóralo: sus imágenes seguirán mostrando la vista previa guardada con el documento. Replace Spine Reemplazar eje + Create Spine Crear eje + Create Spine: Crear eje: + Always Siempre + Never Nunca Replace Symbol Reemplazar símbolo Reset Transformation Restablecer transformación Replace With Font Reemplazar con fuente @@ -2880,6 +2921,9 @@ digits Malayalam Malayálam Rise… Ascenso… Roman Baseline Línea de base latina Roman Hanging Punctuation Puntuación colgante romana + Korean Line Break Anywhere Salto de línea coreano en cualquier lugar + East Asian Composition Settings Ajustes de composición de Asia oriental + Korean Composition Settings Ajustes de composición coreana Rotate Rotar Rotate 90° CW Rotar 90° en sentido horario Rotate Tool Herramienta Rotar @@ -3163,6 +3207,15 @@ digits Malayalam Malayálam Stun Pulse Aturdimiento Stealth Fade Sigilo Shield Buff Escudo + Textures Texturas + Fine Grain Grano fino + Canvas Weave Tejido de lienzo + Burlap Sack Saco de arpillera + Cracked Glaze Esmalte agrietado + Mosaic Floor Suelo de mosaico + Quilted Squares Cuadros acolchados + Leaded Glass Vidrio emplomado + Damp Paper Papel húmedo Shape Forma Shape Builder Generador de formas Shape Builder Regions Regiones del generador de formas @@ -3225,6 +3278,7 @@ digits Malayalam Malayálam Show Modified Mostrar modificados Show Note Mostrar nota Show Options Mostrar opciones + Show Recent Colors Mostrar colores recientes Show Original Path Mostrar trazado original Open this dialog with these settings next time Abrir este cuadro de diálogo con estos ajustes la próxima vez Auto-Simplify Simplificar automáticamente @@ -3529,6 +3583,8 @@ digits Malayalam Malayálam Scale at Center Escalar desde el centro Up/Down: Arriba/abajo: Left/Right: Izquierda/derecha: + Tate-chu-yoko Up/Down Tate-chu-yoko arriba/abajo + Tate-chu-yoko Left/Right Tate-chu-yoko izquierda/derecha Temperature Temperatura Temperature/Tint… Temperatura/tinte… Template Plantilla @@ -3599,6 +3655,8 @@ digits Malayalam Malayálam Toolbar: Single/Double Column Barra de herramientas: columna simple/doble Toolbar: Add Tool Barra de herramientas: añadir herramienta Toolbar: Remove Tool Barra de herramientas: quitar herramienta + Add Tool… Añadir herramienta… + Remove Tool Quitar herramienta Toolbar: Reset Barra de herramientas: restablecer Toolbars Barras de herramientas Tools Herramientas @@ -3669,6 +3727,8 @@ digits Malayalam Malayálam Type on a Path Texto en trazado Type on a Path Options Opciones de texto en trazado Type on a Path Options… Opciones de texto en trazado… + Center on Top Centrar arriba + Center on Bottom Centrar abajo Type on a Path Tool Herramienta Texto en trazado Type Orientation Orientación del texto Type stays text, and every stroke is a line with its lineweight and dashes. El texto sigue siendo texto, y cada trazo es una línea con su grosor y guiones. @@ -3862,6 +3922,7 @@ digits Malayalam Malayálam Windows Windows Working CMYK CMYK de trabajo Working CMYK (don't tag) CMYK de trabajo (sin etiquetar) + Working RGB (don't tag) RGB de trabajo (sin etiquetar) Workspace Espacio de trabajo Workspace {i} Espacio de trabajo {i} Wrinkle Tool Herramienta Arrugar @@ -4045,6 +4106,13 @@ axis Both Ambos Dock Panel Anclar panel Dock to Top Anclar arriba Dock to Bottom Anclar abajo + Control Bar Options Opciones de la barra de control + Tool Options Opciones de herramienta + Object Options Opciones de objeto + Image Options Opciones de imagen + Vertical Alignment Alineación vertical + Align and Distribute Alinear y distribuir + Document Options Opciones de documento Dock Control Bar Anclar barra de control Drag to float the toolbar Arrastrar para hacer flotar la barra de herramientas Drag to the window's left or right edge to dock Arrastrar al borde izquierdo o derecho de la ventana para anclar @@ -4197,10 +4265,13 @@ axis Both Ambos @msg `groupColors` must be an array `groupColors` debe ser una lista @msg `library` is a library id or name (see {list}) `library` es el id o el nombre de una biblioteca (consulta {list}) @msg `mode` applies to freeform gradients `mode` se aplica a los degradados de forma libre +@msg a negative `aspect` applies to conic gradients un `aspect` negativo se aplica a los degradados cónicos +@msg `focal` applies to radial gradients `focal` se aplica a los degradados radiales @msg `preserve` must be an object `preserve` debe ser un objeto @msg `globalAdjust` must be an object `globalAdjust` debe ser un objeto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` debe ser 1, 3 o 5 @msg `stops` must be an array `stops` debe ser una lista +@msg `{key}` must be an array `{key}` debe ser una lista @msg `svg` must be an object of SVG options (see document.formats) `svg` debe ser un objeto con opciones de SVG (consulta document.formats) @msg `{_1}` is no save command `{_1}` no es un comando de guardado @msg `{area}` is no recovery area name `{area}` no es el nombre de un área de recuperación @@ -4214,6 +4285,7 @@ axis Both Ambos @msg `{key}` must be a number, not {v} `{key}` debe ser un número, no {v} @msg {key} must be Unix seconds (an integer) or null {key} debe ser un tiempo Unix en segundos (un entero) o null @msg `{key}` must be a string `{key}` debe ser un texto +@msg `{key}` must be a profile name or null `{key}` debe ser un nombre de perfil o null @msg `{key}` must be a whole number `{key}` debe ser un número entero @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` debe ser un número entero entre {min} y {max} (se recibió {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` debe estar entre {min} y {max} (se recibió {x}) @@ -4366,6 +4438,7 @@ axis Both Ambos @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la página de la mesa de trabajo {n} mide {size}, más que el límite de página de PDF de 14.400 pt (200 in): se escribe con un UserUnit de {unit}, así que las aplicaciones que ignoran UserUnit la muestran ese número de veces más pequeña @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la página de la mesa de trabajo {n} mide {size}, más que el límite de página de PDF de 14.400 pt (200 in): las páginas {label} se escriben sin UserUnit, en puntos, y las aplicaciones que respetan el límite recortan la página a 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 no tiene UserUnit, que una página de más de 14.400 pt (200 in) necesita para conservar su tamaño: el archivo se escribe como PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 no tiene UserUnit, que una página de más de 14.400 pt (200 in) necesita para no superar el límite de página de PDF/A-2, de 14.400 unidades: el archivo se escribe como PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la página de la mesa de trabajo {n} mide {size}, demasiado larga y estrecha para los lados de página de PDF de 3 a 14.400 unidades: se escribe con una UserUnit de {unit}, que mantiene el lado corto en 3 unidades o más, y las aplicaciones que respetan el límite recortan el lado largo a 14.400 unidades @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard los archivos {label} admiten números reales de hasta {max}, y la página de la mesa de trabajo {n}, de {side} pt, necesita otros mayores: elija PDF 1.6 o posterior sin estándar PDF/X, o una mesa de trabajo más pequeña @msg invalid image data for `{0}` datos de imagen no válidos para `{0}` @@ -4514,6 +4587,8 @@ axis Both Ambos @msg not a stored central record no es un registro central almacenado @msg not a valid plug-in module: {0} no es un módulo de plugin válido: {0} @msg not an EMF or WMF file no es un archivo EMF ni WMF +@msg not an HP-GL file no es un archivo HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` debe ser una lista de 1 a 255 colores #rrggbb @msg not found no se encontró @msg not in pattern editing mode no está en el modo de edición de motivos @msg finish editing the pattern first termina primero la edición del motivo @@ -4593,6 +4668,14 @@ axis Both Ambos @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 este calco crearía más de {max} puntos de ancla, más de los que el documento puede mostrar con fluidez: sube Ruido, baja Trazados o Colores, o elige un preajuste de menor fidelidad @msg select an envelope selecciona una envolvente @msg select an image selecciona una imagen +@msg `background` must be edges, corners or colors `background` debe ser edges, corners o colors +@msg `match` must be distance or channels `match` debe ser distance o channels +@msg `{key}` must be from 0 to 100 `{key}` debe estar entre 0 y 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` debe contener de 1 a 16 colores, cada uno en hexadecimal (#rrggbb o #rgb) o como black, white, red, green o blue +@msg the linked image shows its preview: embed or relink it first la imagen vinculada muestra su vista previa: incrústala o vuelve a vincularla primero +@msg a CMYK image has no transparency to set una imagen CMYK no tiene transparencia que establecer +@msg every pixel matches the background: no image would be left todos los píxeles coinciden con el fondo: no quedaría ninguna imagen +@msg an image of {w} × {h} pixels is too large to change una imagen de {w} × {h} píxeles es demasiado grande para cambiarla @msg select an object in perspective selecciona un objeto en perspectiva @msg select artwork (or a colour group) to recolor selecciona la ilustración (o un grupo de colores) que quieres volver a colorear @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloreado completado; sin cambios: {locked} y {hidden} @@ -4699,7 +4782,7 @@ axis Both Ambos @msg unknown format formato desconocido @msg unknown format `{f}` (Save writes {_1}) formato desconocido `{f}` (Guardar escribe {_1}) @msg unknown freeform mode `{m}` (points, lines) modo de forma libre desconocido `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) tipo de degradado desconocido `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) tipo de degradado desconocido `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` resaltado desconocido `{h}` @msg unknown option `{path}.{k}` opción desconocida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpresiones desconocidas `{o}` (preserve, simulate o discard) @@ -4925,6 +5008,8 @@ axis Both Ambos @msg invalid object id {value}: expected a non-negative integer identificador de objeto no válido {value}: se esperaba un entero no negativo @msg `{key}` entry {index} is {value}, not a non-negative integer object id la entrada {index} de `{key}` es {value}, no un identificador de objeto (un entero no negativo) @msg no such object id {value} no existe el objeto con el identificador {value} +@msg id {value} is a ruler guide, not an object el identificador {value} es de una guía, no de un objeto +@msg a ruler guide goes only directly in a layer or sublayer una guía solo puede estar directamente en una capa o subcapa @msg id {value} is a layer, not an object el identificador {value} es una capa, no un objeto @msg id {value} is a layer, not an object; move layers with layer.move el identificador {value} es una capa, no un objeto; mueva las capas con layer.move @msg automation filesystem access is not granted: read authority is absent: {path} la automatización no tiene acceso al sistema de archivos: falta el permiso de lectura: {path} @@ -4954,7 +5039,13 @@ axis Both Ambos @msg the HEIC or HEIF file holds a kind of image that can't be read el archivo HEIC o HEIF contiene un tipo de imagen que no se puede leer @msg HEIC and HEIF images can't be opened in this build las imágenes HEIC y HEIF no se pueden abrir en esta compilación @msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles) -@msg zipped 32-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 32 bits comprimidos en ZIP con predicción +@msg zipped 1-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 1 bit comprimidos en ZIP con predicción +@msg the PSD file's layer data uses an unknown compression ({m}) los datos de capa del archivo PSD usan una compresión desconocida ({m}) +@msg the PSD file's layer records are damaged los registros de capas del archivo PSD están dañados +@msg the PSD file's layer groups are nested too deeply los grupos de capas del archivo PSD están anidados a demasiada profundidad +@msg a layer of the PSD file is too large to read una capa del archivo PSD es demasiado grande para leerla +@msg the PSD file's layers take more memory to read than allowed las capas del archivo PSD necesitan más memoria de la permitida para leerlas +@msg the layers can't be read ({e}): the file opened as its merged image no se pueden leer las capas ({e}): el archivo se abrió como su imagen combinada @msg {depth}-bit PSD files in this colour mode can't be read los archivos PSD de {depth} bits en este modo de color no se pueden leer @msg the PSD file is cut short el archivo PSD está incompleto @msg the PSD file's header is damaged el encabezado del archivo PSD está dañado @@ -5645,6 +5736,11 @@ mark-style Japanese Japonesas Softness Suavidad Ambient Light Luz ambiental Light behind the object Luz detrás del objeto + Shadows Sombras + Distance from Object Distancia del objeto + Shadow Bounds Límites de la sombra + Behind Object Detrás del objeto + Below Object Debajo del objeto 3D Lighting Preset Ajuste preestablecido de iluminación 3D Standard Estándar Diffuse Difusa @@ -5710,7 +5806,7 @@ mark-style Japanese Japonesas @msg span must be "object" or "selection", got {v} span debe ser "object" o "selection", no {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" coloca un `gradient`, no una muestra @msg span: "selection" places a gradient: give `gradient` span: "selection" coloca un degradado: indique `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" coloca un degradado lineal o radial, no uno de forma libre +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" coloca un degradado lineal, radial, cónico o de rombo, no uno de forma libre @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" coloca el propio degradado: omita `start` y `end` (ya lo colocan en coordenadas del documento) Make Image Dynamic Hacer imagen dinámica Import Data Sets… Importar conjuntos de datos… @@ -5893,6 +5989,7 @@ mark-style Japanese Japonesas Ruby Ruby Geometric Guides Guías geométricas Geometric Patterns Motivos geométricos + Grit Textures Texturas granuladas Ease In Entrada suave Ease Out Salida suave Ease In Out Entrada y salida suaves @@ -5951,6 +6048,8 @@ axis Y Axis Eje Y Version: {version} Versión: {version} Install “{name}” in place of the plug-in with the same ID? ¿Instalar “{name}” en lugar del plugin con el mismo ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este archivo no es el plugin instalado antes con este ID. Recibe la configuración y la caché guardadas para ese ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Una automatización pidió instalar este plugin. Para instalarlo, elige Objeto › Plugins › Instalar plugin… tú mismo. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Una automatización pidió instalar este plugin. Para instalarlo, elige Objeto › Plugins › Instalar plugin… tú mismo. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}” es un módulo distinto del plugin con ID {_1} y recibiría la configuración y la caché guardadas para él: instálalo con `replace: true` cuando el usuario lo acepte File SHA-256: {hash} SHA-256 del archivo: {hash} Read the objects it is given Leer los objetos que recibe @@ -5996,6 +6095,11 @@ axis Y Axis Eje Y @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) presupuesto de memoria (el objeto {_1} necesita {size} bytes de entrada, quedan {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) presupuesto de objetos (más de {MAX_OBJECTS} objetos de solo lectura) +@msg instruction budget presupuesto de instrucciones +@msg time budget presupuesto de tiempo +@msg memory budget (the selection is too large to hand over) presupuesto de memoria (la selección es demasiado grande para entregarla) +@msg output size ({what} is {len} bytes, limit {max}) tamaño de salida ({what} ocupa {len} bytes, límite {max}) +@msg the plug-in's grant can't be removed from the plug-in store el permiso del plugin no se puede quitar del almacén de plugins @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permiso `{shown}` está reservado para una API de plugins posterior; este host no lo concede @msg unknown permission `{shown}` permiso desconocido `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” pide los permisos {asked}: una persona debe aprobarlos en la aplicación de escritorio, o pasa `grant` en una sesión iniciada con --allow-plugin-grants @@ -6008,6 +6112,12 @@ axis Y Axis Eje Y @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` debe tener 1-64 caracteres imprimibles @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que empiece por una letra @msg command {name}: {e} comando {name}: {e} +@msg manifest: {e} manifiesto: {e} +@msg manifest: {e} at line {line} column {column} manifiesto: {e} (línea {line}, columna {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` debe ser una lista de comandos, cada uno con `id` y `label` +@msg command {name} must be an object with an `id` and a `label` el comando {name} debe ser un objeto con `id` y `label` +@msg missing field `{key}` falta el campo `{key}` +@msg duplicate field `{key}` el campo `{key}` está repetido @msg only a filter or a live effect declares `commands` solo un filtro o un efecto interactivo declara `commands` @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed el módulo no tiene el SHA-256 que indica `hash`: no se instaló nada @@ -6032,6 +6142,16 @@ axis Y Axis Eje Y @msg message must be text message debe ser texto @msg allowContinue must be true or false allowContinue debe ser true o false @msg Batch cannot play an action with a stop Lote no puede reproducir una acción con una parada + Insert Menu Item… Insertar elemento de menú… + Insert Menu Item Insertar elemento de menú + Menu Item: Elemento de menú: + No menu item matches. Ningún elemento de menú coincide. + Several menu items match. Choose one from the list. Coinciden varios elementos de menú. Elija uno de la lista. + Items that open a dialog, and File, Window and Help menu items, are not listed. No se muestran los elementos que abren un cuadro de diálogo ni los de los menús Archivo, Ventana y Ayuda. +@msg command must be text command debe ser texto +@msg no menu item that can be inserted runs this command ningún elemento de menú que se pueda insertar ejecuta este comando +@msg the action already has 10,000 steps la acción ya tiene 10 000 pasos +@msg the action set would be larger than 8 MiB el conjunto de acciones superaría los 8 MiB Playback Options Opciones de reproducción Accelerated Acelerada Step by Step Paso a paso @@ -6070,6 +6190,12 @@ axis Y Axis Eje Y Crosshair Punto de mira Checkpoint Punto de control Inventory Icons Iconos de inventario + Skill Icons Iconos de habilidad + Attack Ataque + Defend Defensa + Heal Curación + Buff Mejora + Ult Ult Sword Espada Shield Escudo Potion Poción @@ -6134,7 +6260,23 @@ axis Y Axis Eje Y Dash Trail Estela discontinua Speed Line Línea de velocidad Game Trails Estelas de juego + Energy Beams Haces de energía + Laser Bolt Proyectil láser + Plasma Arc Arco de plasma + Charge Wave Onda de carga + Spark Trail Estela de chispas Calligraphic Nibs Plumillas caligráficas + Bristle Brushes Pinceles de cerdas + Fine Liner Delineador fino + Pointed Flat Plano puntiagudo + Stubby Round Redondo corto + Dry Scrub Frotado seco + Soft Dome Cúpula suave + Filbert Lengua de gato + Angled Round Redondo biselado + Angled Flat Plano biselado + Fan Blender Abanico difuminador + Grass Fan Abanico de hierba Pattern Borders Bordes de motivo Scatter Shapes Formas de dispersión Save Brush Library… Guardar biblioteca de pinceles… @@ -6332,9 +6474,12 @@ anchor Points: Puntos: @msg {label} must be a number {label} debe ser un número @msg {label} must be a number of at least 0.1 {label} debe ser un número de al menos 0,1 Advanced Character Formats Formatos avanzados de caracteres + Basic Paragraph Formats Formatos básicos de párrafo + Composition Composición Horizontal Scale Escala horizontal Vertical Scale Escala vertical @msg {label} must be a number from {min} to {max} {label} debe ser un número de {min} a {max} +@msg {label} must be a whole number from {min} to {max} {label} debe ser un número entero de {min} a {max} Character Color Color de los caracteres OpenType Features Funciones OpenType Stylistic Sets Conjuntos estilísticos @@ -6342,6 +6487,10 @@ anchor Points: Puntos: @msg features lists at most {max} tags features admite como máximo {max} etiquetas @msg unknown OpenType feature `{t}` función OpenType desconocida `{t}` @msg {label} must be a number above 0 and at most {max} {label} debe ser un número mayor que 0 y como máximo {max} +@msg {label} must be at most {max} characters {label} debe tener como máximo {max} caracteres +@msg {label} must be one character {label} debe ser un solo carácter +@msg at most {max} tab stops como máximo {max} tabulaciones +@msg unknown align `{other}` alineación desconocida `{other}` @msg no character style `{name}` No existe el estilo de carácter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6503,6 +6652,12 @@ breakText Glyphs Glifos Delete the selected brushes? ¿Eliminar los pinceles seleccionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Algunos trazos usan uno o más de estos pinceles. ¿Quitar los pinceles de esos trazos y eliminar los pinceles? Remove Strokes Quitar trazos + Place Brush Art Colocar ilustración del pincel + Replace Brush Art Reemplazar ilustración del pincel + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Algunos trazos usan este pincel. ¿Aplicar la nueva ilustración a esos trazos, o dejarlos como están y añadir una copia del pincel con la nueva ilustración? + Apply to Strokes Aplicar a los trazos + Leave Strokes Dejar los trazos +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` no tiene ilustración (solo la tienen los pinceles de dispersión, de arte y de motivo) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Herramientas de organización Arrange in Grid… Organizar en cuadrícula… @@ -6698,6 +6853,11 @@ breakText Glyphs Glifos @msg only an exporter or an importer declares `extensions` solo un plugin de exportación o de importación declara `extensions` @msg an importer always gets an import's budget: leave `budget` out un plugin de importación siempre recibe el presupuesto de una importación: omita `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Copiar información de solución de problemas +@msg Copied the troubleshooting info Se copió la información de solución de problemas +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report La última sesión de VectorCraft dejó de responder antes de cerrarse. Ayuda › Copiar información de solución de problemas copia los detalles para un informe de error + # Safe Mode Safe Mode… Modo seguro… Safe Mode Modo seguro @@ -6718,6 +6878,8 @@ breakText Glyphs Glifos # Align to Pixel Grid Align to Pixel Grid Alinear con cuadrícula de píxeles + Align New Objects to Pixel Grid Alinear objetos nuevos con cuadrícula de píxeles + Not Aligned to Pixel Grid No alineado con cuadrícula de píxeles @msg only paths and compound paths can be aligned to the pixel grid solo los trazados y los trazados compuestos se pueden alinear con la cuadrícula de píxeles @msg side is left or right, not `{s}` side es left o right, no `{s}` Ignore All Omitir todo @@ -6748,8 +6910,33 @@ breakText Glyphs Glifos @plural {n} line cut|{n} lines cut {n} línea recortada|{n} líneas recortadas @msg `first` and `last` must be numbers of lines the console holds, first before last `first` y `last` deben ser números de líneas que la consola conserva, `first` antes que `last` +# Learn panel + Learn Aprender + Explore tutorials Explorar tutoriales + For you Para ti + Skills Habilidades + Get started Primeros pasos + Quick skill guide Guía rápida de habilidades + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Tutoriales prácticos breves sobre las herramientas esenciales, agrupados por habilidad. Elige una habilidad para ver sus tutoriales. + List Tutorials Enumerar tutoriales + Show Tutorial Mostrar tutorial +@msg missing `tutorial` (see learn.list) falta `tutorial` (consulta learn.list) +@msg unknown tutorial `{id}` (see learn.list) tutorial desconocido `{id}` (consulta learn.list) + # Deferred plug-in effects Refresh Deferred Effects Actualizar efectos aplazados Deferred Effects Efectos aplazados @msg no plug-in effect is deferred no hay ningún efecto de plugin aplazado @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Se abrió con {n} efecto de plugin aplazado. Efecto › Actualizar efectos aplazados lo ejecuta.|Se abrió con {n} efectos de plugin aplazados. Efecto › Actualizar efectos aplazados los ejecuta. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Herramientas de corte + Stencil Bridges… Puentes de plantilla… + Stencil Bridges Puentes de plantilla + Shortest Crossing Cruce más corto + Direction Dirección +@msg The selected art has no islands to bridge La ilustración seleccionada no tiene islas que unir +@msg No bridge of this width fits across the selected art Ningún puente de este ancho cabe en la ilustración seleccionada +@msg Some islands could not be joined to the area around the art Algunas islas no se pudieron unir al área que rodea la ilustración +@msg `width` must be from {lo} to {hi} pt `width` debe estar entre {lo} y {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` debe ser un número entero entre 1 y {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index cdbd875764..faa24de7e1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -126,6 +126,7 @@ PDF Presets… PDF-esiasetukset… Perspective Grid Presets… Perspektiiviruudukon esiasetukset… Color Settings… Väriasetukset… + Assign Profile Määritä profiili Assign Profile… Määritä profiili… Keyboard Shortcuts… Pikanäppäimet… Import Shortcut Set Tuo pikanäppäinjoukko @@ -209,6 +210,15 @@ Expand… Laajenna… Expand Appearance Laajenna ulkoasu Crop Image Rajaa kuva + Image Tools Kuvatyökalut + Remove Background… Poista tausta… + Remove Background Poista tausta + Background Tausta + Edge Color Reunan väri + Picked Colors Valitut värit + Corner Color Kulmien väri + Contiguous Yhtenäinen + Each Channel Jokainen kanava Edit Path Muokkaa polkua Mask Maski Rasterize… Rasteroi… @@ -259,6 +269,10 @@ Blend Options… Sulautuksen asetukset… Expand Laajenna Replace Spine Korvaa selkäranka + Create Spine Luo selkäranka + Create Spine: Luo selkäranka: + Always Aina + Never Ei koskaan Reverse Spine Käännä selkäranka Reverse Front to Back Käännä edestä taakse Envelope Distort Vääristyskuori @@ -388,6 +402,8 @@ Stair Step Porras Gravity Painovoima Type on a Path Options… Teksti polulla -asetukset… + Center on Top Keskitä ylös + Center on Bottom Keskitä alas Threaded Text Ketjutettu teksti Create Luo Release Selection Vapauta valinta @@ -403,6 +419,15 @@ Smart Punctuation… Älykäs välimerkitys… Create Outlines Muunna ääriviivoiksi Optical Margin Alignment Optinen reunustasaus + Dynamic Text Dynaaminen teksti + Dynamic Text Presets Dynaamisen tekstin esiasetukset + Arch Holvi +@msg select point type or type on a path valitse pisteteksti tai polkuteksti +@msg type on a path in a thread cannot use Dynamic Text: {frames} ketjutetun tekstin polkuteksti ei voi käyttää dynaamista tekstiä: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} avoimella polulla tai yhdistelmäpolulla olevaa tekstiä ei voi keskittää ylös tai alas: {open} +@msg type on a path with no length or no height cannot be centered: {flat} polkutekstiä ei voi keskittää polulle, jolla ei ole pituutta tai korkeutta: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} ketjutetun tekstin polkutekstiä ei voi keskittää ylös tai alas: {frames} +@msg select type on a closed path valitse suljetulla polulla oleva teksti Fill with Placeholder Text Täytä paikkamerkkitekstillä Insert Inline Symbol Lisää tekstinsisäinen symboli Show Hidden Characters Näytä piilotetut merkit @@ -474,6 +499,8 @@ Extrude & Bevel… Pursota ja viistä… 3D (Classic) 3D (perinteinen) Extrude & Bevel (Classic)… Pursota ja viistä (perinteinen)… + Revolve (Classic)… Pyöräytä (perinteinen)… + Rotate (Classic)… Kierrä (perinteinen)… Surface Pinta Wireframe Rautalanka No Shading Ei varjostusta @@ -544,6 +571,7 @@ Gaussian Blur… Gaussin sumennus… View Näytä Preview Esikatselu + Preview: Esikatselu: Overprint Preview Päällepainatuksen esikatselu Pixel Preview Pikseliesikatselu Trim View Rajattu näkymä @@ -781,8 +809,25 @@ Stun Pulse Tainnutus Stealth Fade Hiipiminen Shield Buff Kilpi + Textures Tekstuurit + Fine Grain Hieno rae + Canvas Weave Kanvaskudos + Burlap Sack Juuttisäkki + Cracked Glaze Krakeloitu lasite + Mosaic Floor Mosaiikkilattia + Quilted Squares Tikatut ruudut + Leaded Glass Lyijylasi + Damp Paper Kostea paperi Outlines and Rules Ääriviivat ja viivat Hand-Drawn Käsin piirretyt + Painted and Sketched Maalatut ja luonnostellut + Washed Blue Haalea sininen + Bristle Ochre Harjasokra + Pastel Heather Pastellikanerva + Charcoal Shade Hiilivarjo + Ink Contour Mustekontuuri + Wet Ink Märkä muste + Fine Pen Hieno kynä Gradient Finishes Liukuväriviimeistelyt Shape Effects Muototehosteet Blends and Transparency Sulautukset ja läpinäkyvyys @@ -802,6 +847,8 @@ Spectrum Gradients Spektriliukuvärit Sky Gradients Taivasliukuvärit Neutral Gradients Neutraalit liukuvärit + Organic Fades Orgaaniset häivytykset + Holographic Holografiset Duotone Gradients Kaksisävyliukuvärit Radial Glows Säteittäiset hehkut Save Swatch Library… Tallenna värimallikirjasto… @@ -860,6 +907,13 @@ Dock Panel Telakoi paneeli Dock to Top Telakoi ylös Dock to Bottom Telakoi alas + Control Bar Options Ohjauspalkin asetukset + Tool Options Työkalun asetukset + Object Options Objektin asetukset + Image Options Kuvan asetukset + Vertical Alignment Pystysuora tasaus + Align and Distribute Tasaa ja jaa + Document Options Asiakirjan asetukset Dock Control Bar Telakoi ohjauspalkki Float Tool Group Kelluta työkaluryhmä Services Palvelut @@ -1143,6 +1197,8 @@ lighting Light Valo Toolbar: Single/Double Column Työkalurivi: yksi/kaksi saraketta Toolbar: Add Tool Työkalurivi: lisää työkalu Toolbar: Remove Tool Työkalurivi: poista työkalu + Add Tool… Lisää työkalu… + Remove Tool Poista työkalu Toolbar: Reset Työkalurivi: palauta Two Point Perspective Preset 1 Kahden pisteen perspektiivin esiasetus 1 Two Point Perspective Preset 2 Kahden pisteen perspektiivin esiasetus 2 @@ -1522,6 +1578,7 @@ digits Malayalam Malajalam Roman Baseline Latinalainen perusviiva Select a text object to edit its character attributes. Valitse tekstiobjekti, jonka merkkimääritteitä haluat muokata. Show Options Näytä asetukset + Show Recent Colors Näytä viimeisimmät värit Small Caps Kapiteelit Small Caps (on the roadmap) Kapiteelit (suunnitteilla) Standard Vertical Roman Alignment Tavallinen pystysuuntainen latinalainen tasaus @@ -1549,6 +1606,8 @@ digits Malayalam Malajalam Scale at Center Skaalaa keskeltä Up/Down: Ylös/alas: Left/Right: Vasen/oikea: + Tate-chu-yoko Up/Down Tate-chu-yoko ylös/alas + Tate-chu-yoko Left/Right Tate-chu-yoko vasen/oikea Underline Alleviivaus Vertical Scale % Pystyskaalaus % Axis Akseli @@ -1651,6 +1710,8 @@ digits Malayalam Malajalam No gradient swatches Ei liukuvärimalleja Points: clicks add free points Pisteet: napsautukset lisäävät vapaita pisteitä Radial Gradient Säteittäinen liukuväri + Conic Gradient Kartiomainen liukuväri + Diamond Gradient Vinoneliöliukuväri Reset to White, Black Palauta valkoinen, musta Reverse Gradient Käännä liukuväri Save to Swatches Tallenna värimalleihin @@ -1923,6 +1984,9 @@ digits Malayalam Malajalam Right Indent Oikea sisennys Right-to-Left Paragraph Direction Kappaleen suunta oikealta vasemmalle Roman Hanging Punctuation Latinalaiset riippuvat välimerkit + Korean Line Break Anywhere Korean rivinvaihto missä tahansa + East Asian Composition Settings Itäaasialaisen ladonnan asetukset + Korean Composition Settings Korean ladonnan asetukset Select a text object to edit its paragraph attributes. Valitse tekstiobjekti, jonka kappalemääritteitä haluat muokata. Single-line Composer Yhden rivin asettelu Toggle Line Composer Vaihda rivien asettelu @@ -2009,6 +2073,7 @@ digits Malayalam Malajalam Simulate Paper Simuloi paperia Use Black Point Compensation Käytä mustan pisteen kompensointia Working CMYK (don't tag) Työ-CMYK (ei tunnistetta) + Working RGB (don't tag) Työ-RGB (ei tunnistetta) {name} (spot) {name} (spottiväri) Add to Profiles… Lisää profiileihin… Align Stroke to Center Tasaa viiva keskelle @@ -2309,6 +2374,8 @@ digits Malayalam Malajalam Export Selected Art Only Vie vain valittu kuvitus Number of Colors: Värien määrä: Raster File Format: Rasteritiedoston muoto: + Include Placed Images Sisällytä sijoitetut kuvat + Include Fill Hatches Sisällytä täyttöjen viivoitukset True colour needs version 2004 or later: the nearest of 256 colours is written. Täysväri vaatii version 2004 tai uudemman: käytetään lähintä 256 väristä. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Teksti muunnetaan ääriviivoiksi, ja viivat, joita CAD-viiva ei pysty piirtämään, muuttuvat täytetyiksi muodoiksi. Type stays text, and every stroke is a line with its lineweight and dashes. Teksti säilyy tekstinä, ja jokainen viiva on viiva, jolla on oma viivanpaksuutensa ja katkoviivansa. @@ -2852,6 +2919,7 @@ antiAlias Sharp Terävä General › Thumbnails Yleiset › Pikkukuvat Grayscale images Harmaasävykuvat Include non-printing layers Sisällytä tulostumattomat tasot + Write pages longer than 200 in at full size in points Kirjoita yli 200 in pitkät sivut täysikokoisina pisteinä Left: Vasen: Mark as trapped Merkitse ylitäytetyksi Marks and Bleeds Merkit ja leikkuuvarat @@ -4420,10 +4488,13 @@ imageTrace Outline Ääriviiva @msg `groupColors` must be an array `groupColors` on oltava taulukko @msg `library` is a library id or name (see {list}) `library` on kirjaston tunnus tai nimi (ks. {list}) @msg `mode` applies to freeform gradients `mode` koskee vapaamuotoisia liukuvärejä +@msg a negative `aspect` applies to conic gradients negatiivinen `aspect` koskee kartiomaisia liukuvärejä +@msg `focal` applies to radial gradients `focal` koskee säteittäisiä liukuvärejä @msg `preserve` must be an object `preserve` on oltava objekti @msg `globalAdjust` must be an object `globalAdjust` on oltava objekti @msg `sampleSize` must be 1, 3 or 5 `sampleSize` on oltava 1, 3 tai 5 @msg `stops` must be an array `stops` on oltava taulukko +@msg `{key}` must be an array `{key}` on oltava taulukko @msg `svg` must be an object of SVG options (see document.formats) `svg` on oltava SVG-asetusten objekti (ks. document.formats) @msg `{_1}` is no save command `{_1}` ei ole tallennuskomento @msg `{area}` is no recovery area name `{area}` ei ole palautusalueen nimi @@ -4437,6 +4508,7 @@ imageTrace Outline Ääriviiva @msg `{key}` must be a number, not {v} `{key}` on oltava luku, ei {v} @msg {key} must be Unix seconds (an integer) or null {key} on oltava Unix-aika sekunteina (kokonaisluku) tai null @msg `{key}` must be a string `{key}` on oltava merkkijono +@msg `{key}` must be a profile name or null `{key}` on oltava profiilin nimi tai null @msg `{key}` must be a whole number `{key}` on oltava kokonaisluku @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` on oltava kokonaisluku väliltä {min}–{max} (saatiin {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` on oltava väliltä {min}–{max} (saatiin {x}) @@ -4583,6 +4655,7 @@ imageTrace Outline Ääriviiva @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller piirtoalustan {n} sivu on {size}, pidempi kuin PDF:n 14 400 pt:n (200 in) sivuraja: se kirjoitetaan UserUnit-arvolla {unit}, joten UserUnitin ohittavat sovellukset näyttävät sen niin monta kertaa pienempänä @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in piirtoalustan {n} sivu on {size}, pidempi kuin PDF:n 14 400 pt:n (200 in) sivuraja: {label}-sivut kirjoitetaan ilman UserUnitia, pisteinä, ja rajaa noudattavat sovellukset rajaavat sivun 200 in:iin @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5:ssä ei ole UserUnitia, jota yli 14 400 pt:n (200 in) sivu tarvitsee säilyttääkseen kokonsa: tiedosto kirjoitetaan PDF 1.6:na +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4:ssä ei ole UserUnitia, jota yli 14 400 pt:n (200 in) sivu tarvitsee pysyäkseen PDF/A-2:n 14 400 yksikön sivurajan sisällä: tiedosto kirjoitetaan PDF 1.6:na @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units piirtoalustan {n} sivu on {size}, liian pitkä ja kapea PDF:n sivuille, jotka ovat 3:sta 14 400 yksikköön: se kirjoitetaan UserUnit-arvolla {unit}, joka pitää lyhyen sivun vähintään 3 yksikössä, ja rajaa noudattavat sovellukset leikkaavat pitkän sivun 14 400 yksikköön @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-tiedostot sallivat reaaliluvut enintään {max}, ja piirtoalustan {n} sivu, {side} pt pitkä, tarvitsee suurempia: valitse PDF 1.6 tai uudempi ilman PDF/X-standardia tai pienempi piirtoalusta @msg invalid image data for `{0}` virheellinen kuvadata kohteelle `{0}` @@ -4730,6 +4803,8 @@ imageTrace Outline Ääriviiva @msg not a stored central record ei tallennettu keskushakemistotietue @msg not a valid plug-in module: {0} ei kelvollinen laajennusmoduuli: {0} @msg not an EMF or WMF file ei EMF- tai WMF-tiedosto +@msg not an HP-GL file ei HP-GL-tiedosto +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` on oltava 1–255 #rrggbb-värin taulukko @msg not found ei löytynyt @msg not in pattern editing mode ei kuvion muokkaustilassa @msg finish editing the pattern first lopeta ensin kuvion muokkaus @@ -4803,6 +4878,14 @@ imageTrace Outline Ääriviiva @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 tämä jäljitys tuottaisi yli {max} ankkuripistettä, enemmän kuin asiakirja näyttää sujuvasti: nosta kohinaa, vähennä polkuja tai värejä tai valitse epätarkempi esiasetus @msg select an envelope valitse vääristyskuori @msg select an image valitse kuva +@msg `background` must be edges, corners or colors `background`-arvon on oltava edges, corners tai colors +@msg `match` must be distance or channels `match`-arvon on oltava distance tai channels +@msg `{key}` must be from 0 to 100 `{key}`-arvon on oltava väliltä 0–100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors`-arvossa on oltava 1–16 väriä, kukin heksadesimaalina (#rrggbb tai #rgb) tai muodossa black, white, red, green tai blue +@msg the linked image shows its preview: embed or relink it first linkitetty kuva näyttää esikatselunsa: upota tai linkitä se ensin uudelleen +@msg a CMYK image has no transparency to set CMYK-kuvalla ei ole asetettavaa läpinäkyvyyttä +@msg every pixel matches the background: no image would be left jokainen pikseli vastaa taustaa: kuvaa ei jäisi jäljelle +@msg an image of {w} × {h} pixels is too large to change kuva, jonka koko on {w} × {h} pikseliä, on liian suuri muutettavaksi @msg select an object in perspective valitse perspektiivissä oleva objekti @msg select artwork (or a colour group) to recolor valitse uudelleenväritettävä kuvitus (tai väriryhmä) @msg Recolor completed; {locked} and {hidden} were left unchanged Uudelleenväritys valmis; muuttamatta jäi: {locked} ja {hidden} @@ -4909,7 +4992,7 @@ imageTrace Outline Ääriviiva @msg unknown format tuntematon muoto @msg unknown format `{f}` (Save writes {_1}) tuntematon muoto `{f}` (Tallenna kirjoittaa muotoja {_1}) @msg unknown freeform mode `{m}` (points, lines) tuntematon vapaamuototila `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) tuntematon liukuvärin laji `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) tuntematon liukuvärin laji `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` tuntematon korostus `{h}` @msg unknown option `{path}.{k}` tuntematon asetus `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) tuntematon päällepainatusten käsittely `{o}` (preserve, simulate tai discard) @@ -5109,6 +5192,8 @@ imageTrace Outline Ääriviiva @msg invalid object id {value}: expected a non-negative integer virheellinen objektitunnus {value}: odotettiin ei-negatiivista kokonaislukua @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}`-luettelon kohde {index} on {value}, ei objektitunnus (ei-negatiivinen kokonaisluku) @msg no such object id {value} objektia tunnuksella {value} ei ole +@msg id {value} is a ruler guide, not an object tunnus {value} on apuviivan, ei objektin +@msg a ruler guide goes only directly in a layer or sublayer apuviiva voi olla vain suoraan tasossa tai alatasossa @msg id {value} is a layer, not an object tunnus {value} on taso, ei objekti @msg id {value} is a layer, not an object; move layers with layer.move tunnus {value} on taso, ei objekti; siirrä tasoja komennolla layer.move @msg automation filesystem access is not granted: read authority is absent: {path} automaation tiedostojärjestelmäkäyttöä ei ole myönnetty: lukuoikeus puuttuu: {path} @@ -5138,7 +5223,13 @@ imageTrace Outline Ääriviiva @msg the HEIC or HEIF file holds a kind of image that can't be read tässä HEIC- tai HEIF-tiedostossa on kuvatyyppi, jota ei voi lukea @msg HEIC and HEIF images can't be opened in this build HEIC- ja HEIF-kuvia ei voi avata tässä versiossa @msg the PSD image is too large to read ({_1} × {_2} pixels) tämä PSD-kuva on liian suuri luettavaksi ({_1} × {_2} pikseliä) -@msg zipped 32-bit PSD image data with prediction can't be read ennustusta käyttävää zip-pakattua 32-bittistä PSD-kuvadataa ei voi lukea +@msg zipped 1-bit PSD image data with prediction can't be read ennustusta käyttävää zip-pakattua 1-bittistä PSD-kuvadataa ei voi lukea +@msg the PSD file's layer data uses an unknown compression ({m}) tämän PSD-tiedoston tasodata käyttää tuntematonta pakkausta ({m}) +@msg the PSD file's layer records are damaged tämän PSD-tiedoston tasotietueet ovat vahingoittuneet +@msg the PSD file's layer groups are nested too deeply tämän PSD-tiedoston tasoryhmät ovat sisäkkäin liian syvällä +@msg a layer of the PSD file is too large to read tämän PSD-tiedoston taso on liian suuri luettavaksi +@msg the PSD file's layers take more memory to read than allowed tämän PSD-tiedoston tasojen lukeminen vaatii enemmän muistia kuin sallitaan +@msg the layers can't be read ({e}): the file opened as its merged image tasoja ei voi lukea ({e}): tiedosto avattiin yhdistettynä kuvanaan @msg {depth}-bit PSD files in this colour mode can't be read tässä väritilassa olevia {depth}-bittisiä PSD-tiedostoja ei voi lukea @msg the PSD file is cut short tämä PSD-tiedosto on katkennut @msg the PSD file's header is damaged tämän PSD-tiedoston otsake on vaurioitunut @@ -5586,6 +5677,11 @@ mark-style Japanese Japanilainen Softness Pehmeys Ambient Light Ympäristövalo Light behind the object Valo objektin takana + Shadows Varjot + Distance from Object Etäisyys objektista + Shadow Bounds Varjon rajat + Behind Object Objektin takana + Below Object Objektin alla 3D Lighting Preset 3D-valaistuksen esiasetus Standard Vakio Diffuse Hajavalo @@ -5745,7 +5841,7 @@ mark-style Japanese Japanilainen @msg span must be "object" or "selection", got {v} span-arvon on oltava "object" tai "selection", saatiin {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" sijoittaa `gradient`-liukuvärin, ei värimallia @msg span: "selection" places a gradient: give `gradient` span: "selection" sijoittaa liukuvärin: anna `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" sijoittaa lineaarisen tai säteittäisen liukuvärin, ei vapaamuotoista +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" sijoittaa lineaarisen, säteittäisen, kartiomaisen tai vinoneliöliukuvärin, ei vapaamuotoista @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" sijoittaa itse liukuvärin: jätä pois `start` ja `end` (ne sijoittavat sen jo asiakirjan koordinaatteihin) @msg the Color Picker is not open värinvalitsin ei ole auki @msg the Simplify slider is not open Yksinkertaista-liukusäädin ei ole auki @@ -5981,6 +6077,7 @@ swatch Bright Violet Kirkas violetti Ruby Ruby Geometric Guides Geometriset apuviivat Geometric Patterns Geometriset kuviot + Grit Textures Rakeiset tekstuurit Ease In Hidas alku Ease Out Hidas loppu Ease In Out Hidas alku ja loppu @@ -6039,6 +6136,8 @@ axis Y Axis Y-akseli Version: {version} Versio: {version} Install “{name}” in place of the plug-in with the same ID? Asennetaanko ”{name}” samaa tunnusta käyttävän laajennuksen tilalle? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tämä tiedosto ei ole laajennus, joka oli aiemmin asennettu tällä tunnuksella. Se saa tälle tunnukselle säilytetyt asetukset ja välimuistin. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automaatio pyysi tämän laajennuksen asentamista. Valitse itse Objekti › Laajennukset › Asenna laajennus…, jos haluat asentaa sen. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automaatio pyysi tämän laajennuksen asentamista. Valitse itse Objekti › Laajennukset › Asenna laajennus…, jos haluat asentaa sen. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees ”{name}” on eri moduuli kuin laajennus, jonka tunnus on {_1}, ja se saisi sille säilytetyt asetukset ja välimuistin: asenna se asetuksella `replace: true`, kun käyttäjä hyväksyy File SHA-256: {hash} Tiedoston SHA-256: {hash} Read the objects it is given Lukea sille annetut objektit @@ -6084,6 +6183,11 @@ axis Y Axis Y-akseli @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) muistibudjetti (objekti {_1} tarvitsee {size} tavua syötettä, jäljellä {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektibudjetti (yli {MAX_OBJECTS} vain luku -objektia) +@msg instruction budget käskybudjetti +@msg time budget aikabudjetti +@msg memory budget (the selection is too large to hand over) muistibudjetti (valinta on liian suuri luovutettavaksi) +@msg output size ({what} is {len} bytes, limit {max}) tulosteen koko ({what}: {len} tavua, raja {max}) +@msg the plug-in's grant can't be removed from the plug-in store laajennuksen käyttöoikeutta ei voi poistaa laajennusvarastosta @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it käyttöoikeus `{shown}` on varattu myöhemmälle laajennus-API:lle; tämä isäntä ei myönnä sitä @msg unknown permission `{shown}` tuntematon käyttöoikeus `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants ”{name}” pyytää käyttöoikeuksia {asked}: ihmisen on hyväksyttävä ne työpöytäsovelluksessa, tai anna `grant` istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants @@ -6096,6 +6200,12 @@ axis Y Axis Y-akseli @msg command {name}: `label` must be 1-64 printable characters komento {name}: `label`-kentässä on oltava 1-64 tulostettavaa merkkiä @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter komento {name}: käytä 1-{MAX_COMMAND_ID} merkin tunnusta merkeistä a-z 0-9 _, joka alkaa kirjaimella @msg command {name}: {e} komento {name}: {e} +@msg manifest: {e} manifesti: {e} +@msg manifest: {e} at line {line} column {column} manifesti: {e} (rivi {line}, sarake {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands`-kohdan on oltava luettelo komennoista, joilla kullakin on `id` ja `label` +@msg command {name} must be an object with an `id` and a `label` komennon {name} on oltava objekti, jossa on `id` ja `label` +@msg missing field `{key}` kenttä `{key}` puuttuu +@msg duplicate field `{key}` kenttä `{key}` on kahdesti @msg only a filter or a live effect declares `commands` vain suodin tai live-tehoste määrittelee `commands`-kohdan @msg “{name}” › {label}: {e} ”{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed moduulilla ei ole `hash`-kentän SHA-256-arvoa: mitään ei asennettu @@ -6120,6 +6230,16 @@ axis Y Axis Y-akseli @msg message must be text message on oltava tekstiä @msg allowContinue must be true or false allowContinue on oltava true tai false @msg Batch cannot play an action with a stop Erä ei voi toistaa toimintoa, jossa on pysäytys + Insert Menu Item… Lisää valikkokohta… + Insert Menu Item Lisää valikkokohta + Menu Item: Valikkokohta: + No menu item matches. Mikään valikkokohta ei vastaa hakua. + Several menu items match. Choose one from the list. Useampi valikkokohta vastaa hakua. Valitse yksi luettelosta. + Items that open a dialog, and File, Window and Help menu items, are not listed. Valintaikkunan avaavia kohtia sekä Tiedosto-, Ikkuna- ja Ohje-valikkojen kohtia ei luetella. +@msg command must be text command on oltava tekstiä +@msg no menu item that can be inserted runs this command mikään lisättävissä oleva valikkokohta ei suorita tätä komentoa +@msg the action already has 10,000 steps toiminnossa on jo 10 000 vaihetta +@msg the action set would be larger than 8 MiB toimintosarja olisi suurempi kuin 8 MiB Playback Options Toistoasetukset Accelerated Nopeutettu Step by Step Vaihe kerrallaan @@ -6158,6 +6278,12 @@ axis Y Axis Y-akseli Crosshair Tähtäin Checkpoint Tarkastuskohta Inventory Icons Inventaarioikonit + Skill Icons Taitoikonit + Attack Hyökkäys + Defend Puolustus + Heal Parannus + Buff Buffi + Ult Ult Sword Miekka Shield Kilpi Potion Taikajuoma @@ -6222,7 +6348,23 @@ axis Y Axis Y-akseli Dash Trail Katkoviiva Speed Line Nopeusviiva Game Trails Pelijäljet + Energy Beams Energiasäteet + Laser Bolt Laserpultti + Plasma Arc Plasma-kaari + Charge Wave Latausaalto + Spark Trail Kipinävanne Calligraphic Nibs Kalligrafiakärjet + Bristle Brushes Harjassiveltimet + Fine Liner Ohut viiva + Pointed Flat Suippo litteä + Stubby Round Lyhyt pyöreä + Dry Scrub Kuiva hankaus + Soft Dome Pehmeä kupu + Filbert Kissankieli + Angled Round Vino pyöreä + Angled Flat Vino litteä + Fan Blender Sekoitusviuhka + Grass Fan Ruohoviuhka Pattern Borders Kuvioreunukset Scatter Shapes Sirontamuodot Save Brush Library… Tallenna sivellinkirjasto… @@ -6419,9 +6561,12 @@ anchor Points: Pisteet: @msg {label} must be a number {label} on oltava luku @msg {label} must be a number of at least 0.1 {label} on oltava vähintään 0,1 Advanced Character Formats Merkkien lisämuotoilut + Basic Paragraph Formats Kappaleiden perusmuotoilut + Composition Ladonta Horizontal Scale Vaakaskaalaus Vertical Scale Pystyskaalaus @msg {label} must be a number from {min} to {max} {label} on oltava luku {min} ja {max} väliltä +@msg {label} must be a whole number from {min} to {max} {label} on oltava kokonaisluku {min} ja {max} väliltä Character Color Merkin väri OpenType Features OpenType-ominaisuudet Stylistic Sets Tyylisarjat @@ -6429,6 +6574,10 @@ anchor Points: Pisteet: @msg features lists at most {max} tags features sisältää enintään {max} tunnistetta @msg unknown OpenType feature `{t}` tuntematon OpenType-ominaisuus `{t}` @msg {label} must be a number above 0 and at most {max} {label} on oltava luku, joka on yli 0 ja enintään {max} +@msg {label} must be at most {max} characters {label} saa olla enintään {max} merkkiä +@msg {label} must be one character {label} on oltava yksi merkki +@msg at most {max} tab stops enintään {max} sarkainkohtaa +@msg unknown align `{other}` tuntematon tasaus `{other}` @msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6590,6 +6739,12 @@ breakText Glyphs Merkit Delete the selected brushes? Poistetaanko valitut siveltimet? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Viivat käyttävät yhtä tai useampaa näistä siveltimistä. Irrotetaanko siveltimet näistä viivoista ja poistetaanko siveltimet? Remove Strokes Poista viivat + Place Brush Art Sijoita siveltimen kuvitus + Replace Brush Art Korvaa siveltimen kuvitus + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Viivat käyttävät tätä sivellintä. Käytetäänkö uutta kuvitusta näissä viivoissa, vai jätetäänkö ne ennalleen ja lisätään siveltimestä kopio, jossa on uusi kuvitus? + Apply to Strokes Käytä viivoihin + Leave Strokes Jätä viivat ennalleen +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` ei sisällä kuvitusta (kuvitus on vain sirote-, taide- ja kuviosiveltimissä) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Järjestelytyökalut Arrange in Grid… Järjestä ruudukkoon… @@ -6790,6 +6945,11 @@ breakText Glyphs Merkit @msg only an exporter or an importer declares `extensions` vain vienti- tai tuontilaajennus ilmoittaa `extensions` @msg an importer always gets an import's budget: leave `budget` out tuontilaajennus saa aina tuonnin budjetin: jätä `budget` pois +# Copy Troubleshooting Info + Copy Troubleshooting Info Kopioi vianmääritystiedot +@msg Copied the troubleshooting info Vianmääritystiedot kopioitiin +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report VectorCraftin edellinen istunto lakkasi vastaamasta ennen kuin se suljettiin. Ohje › Kopioi vianmääritystiedot kopioi tiedot virheraporttia varten + # Safe Mode Safe Mode… Vikasietotila… Safe Mode Vikasietotila @@ -6810,6 +6970,8 @@ breakText Glyphs Merkit # Align to Pixel Grid Align to Pixel Grid Tasaa pikseliruudukkoon + Align New Objects to Pixel Grid Tasaa uudet objektit pikseliruudukkoon + Not Aligned to Pixel Grid Ei tasattu pikseliruudukkoon @msg only paths and compound paths can be aligned to the pixel grid vain polut ja yhdistelmäpolut voi tasata pikseliruudukkoon @msg side is left or right, not `{s}` side on left tai right, ei `{s}` Ignore All Ohita kaikki @@ -6840,8 +7002,33 @@ breakText Glyphs Merkit @plural {n} line cut|{n} lines cut {n} rivi katkaistu|{n} riviä katkaistu @msg `first` and `last` must be numbers of lines the console holds, first before last `first` ja `last` on oltava konsolin säilyttämien rivien numeroita, `first` ennen arvoa `last` +# Learn panel + Learn Opi + Explore tutorials Tutustu opetusohjelmiin + For you Sinulle + Skills Taidot + Get started Aloitus + Quick skill guide Pikaopas taitoihin + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Lyhyitä käytännön opetusohjelmia tärkeimmistä työkaluista taidoittain ryhmiteltyinä. Valitse taito nähdäksesi sen opetusohjelmat. + List Tutorials Luettele opetusohjelmat + Show Tutorial Näytä opetusohjelma +@msg missing `tutorial` (see learn.list) `tutorial` puuttuu (ks. learn.list) +@msg unknown tutorial `{id}` (see learn.list) tuntematon opetusohjelma `{id}` (ks. learn.list) + # Deferred plug-in effects Refresh Deferred Effects Päivitä lykätyt tehosteet Deferred Effects Lykätyt tehosteet @msg no plug-in effect is deferred yhtään laajennustehostetta ei ole lykätty @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Avattiin, ja {n} laajennustehoste lykättiin. Tehoste › Päivitä lykätyt tehosteet suorittaa sen.|Avattiin, ja {n} laajennustehostetta lykättiin. Tehoste › Päivitä lykätyt tehosteet suorittaa ne. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Leikkaustyökalut + Stencil Bridges… Sapluunan sillat… + Stencil Bridges Sapluunan sillat + Shortest Crossing Lyhin ylitys + Direction Suunta +@msg The selected art has no islands to bridge Valitussa grafiikassa ei ole yhdistettäviä saarekkeita +@msg No bridge of this width fits across the selected art Näin leveä silta ei mahdu valitun grafiikan poikki +@msg Some islands could not be joined to the area around the art Joitakin saarekkeita ei voitu yhdistää grafiikkaa ympäröivään alueeseen +@msg `width` must be from {lo} to {hi} pt `width`-arvon on oltava {lo}–{hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` on oltava kokonaisluku 1–{MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index cb81c4902c..0b834ee258 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -263,6 +263,7 @@ font-technology Variable Variables Asset Export Settings Paramètres d’exportation de ressources Assets Ressources Assign Attribuer + Assign Profile Attribuer un profil Assign Profile… Attribuer un profil… Assign: Attribuer : Attach to Active Plane Associer au plan actif @@ -702,6 +703,15 @@ font-technology Variable Variables Created: Création : Crop Recadrer Crop Image Recadrer l’image + Image Tools Outils d’image + Remove Background… Supprimer l’arrière-plan… + Remove Background Supprimer l’arrière-plan + Background Arrière-plan + Edge Color Couleur du bord + Picked Colors Couleurs choisies + Corner Color Couleur des angles + Contiguous Contigu + Each Channel Chaque canal Edit Path Modifier le tracé Mask Masque Crop Marks Traits de coupe @@ -1138,6 +1148,8 @@ font-technology Variable Variables Extrude & Bevel… Extrusion et biseautage… 3D (Classic) 3D (classique) Extrude & Bevel (Classic)… Extrusion et biseautage (classique)… + Revolve (Classic)… Révolution (classique)… + Rotate (Classic)… Rotation (classique)… Surface Surface Wireframe Fil de fer No Shading Sans ombrage @@ -1437,6 +1449,14 @@ font-technology Variable Variables Hair Space Espace ultrafine Hand Tool Outil Main Hand-Drawn Dessiné à la main + Painted and Sketched Peint et esquissé + Washed Blue Bleu lavé + Bristle Ochre Ocre à la brosse + Pastel Heather Bruyère pastel + Charcoal Shade Ombre au fusain + Ink Contour Contour encré + Wet Ink Encre humide + Fine Pen Plume fine Handles Poignées Hard Light Lumière crue Hard Mix Mélange maximal @@ -1653,6 +1673,7 @@ font-technology Variable Variables Include Linked Files Inclure les fichiers liés Include Metadata Inclure les métadonnées Include non-printing layers Inclure les calques non imprimables + Write pages longer than 200 in at full size in points Écrire les pages de plus de 200 in en taille réelle, en points Include SVG Code Inclure le code SVG Include Swatches for Tints Inclure les nuances des teintes Inflate… Gonfler… @@ -2326,12 +2347,23 @@ font-technology Variable Variables Open… Ouvrir… Optical Optique Optical Margin Alignment Alignement optique des marges + Dynamic Text Texte dynamique + Dynamic Text Presets Paramètres prédéfinis du texte dynamique + Arch Voûte +@msg select point type or type on a path sélectionnez du texte de point ou du texte curviligne +@msg type on a path in a thread cannot use Dynamic Text: {frames} le texte curviligne d’un texte lié ne peut pas utiliser le texte dynamique : {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} un texte curviligne sur un tracé ouvert ou un tracé transparent ne peut pas être centré en haut ou en bas : {open} +@msg type on a path with no length or no height cannot be centered: {flat} un texte curviligne sur un tracé sans longueur ou sans hauteur ne peut pas être centré : {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} le texte curviligne d’un texte lié ne peut pas être centré en haut ou en bas : {frames} +@msg select type on a closed path sélectionnez un texte curviligne sur un tracé fermé Optimize for fast web view Optimiser pour un affichage web rapide Optimized Optimisé Options Options Options for Selection… Options de la sélection… Options: Options : Options… Options… + Organic Fades Fondus organiques + Holographic Holographiques or more spaces with a tab espaces ou plus par une tabulation Order: Ordre : Ordinals Ordinaux @@ -2523,6 +2555,7 @@ font-technology Variable Variables Presets: Paramètres prédéfinis : Press Appuyez sur Preview Aperçu + Preview: Aperçu : Preview All Layers Aperçu de tous les calques Preview in Browser Aperçu dans le navigateur Preview in Browser needs the desktop app (the web downloads files instead) L’aperçu dans le navigateur nécessite l’application de bureau (la version web télécharge les fichiers à la place) @@ -2601,6 +2634,8 @@ digits Malayalam Malayalam Radial Radial Radial Glows Halos radiaux Radial Gradient Dégradé radial + Conic Gradient Dégradé conique + Diamond Gradient Dégradé en losange Radius 1 Rayon 1 Radius 2 Rayon 2 Radius1 Rayon1 @@ -2613,6 +2648,8 @@ digits Malayalam Malayalam Range: Plage : Raster Effects Effets de pixellisation Raster File Format: Format du fichier pixellisé : + Include Placed Images Inclure les images importées + Include Fill Hatches Inclure les hachures des fonds Raster Sample Size: Taille de l’échantillon pixellisé : Raster/Vector Balance: Équilibre pixellisé/vectoriel : Rasterize Pixelliser @@ -2794,6 +2831,10 @@ digits Malayalam Malayalam Replace Font Remplacer la police Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Remplacez-le par un autre fichier ou ignorez-le : ses images continueront d’afficher l’aperçu enregistré avec le document. Replace Spine Remplacer la dorsale + Create Spine Créer une dorsale + Create Spine: Créer une dorsale : + Always Toujours + Never Jamais Replace Symbol Remplacer le symbole Reset Transformation Réinitialiser la transformation Replace With Font Remplacer par la police @@ -2872,6 +2913,9 @@ digits Malayalam Malayalam Rise… Élévation… Roman Baseline Ligne de base romaine Roman Hanging Punctuation Ponctuation romaine hors justification + Korean Line Break Anywhere Saut de ligne coréen n’importe où + East Asian Composition Settings Paramètres de composition d’Asie orientale + Korean Composition Settings Paramètres de composition coréenne Rotate Rotation Rotate 90° CW Rotation de 90° horaire Rotate Tool Outil Rotation @@ -3155,6 +3199,15 @@ digits Malayalam Malayalam Stun Pulse Étourdissement Stealth Fade Furtivité Shield Buff Bouclier + Textures Textures + Fine Grain Grain fin + Canvas Weave Toile tissée + Burlap Sack Sac de jute + Cracked Glaze Glaçure craquelée + Mosaic Floor Sol en mosaïque + Quilted Squares Carrés matelassés + Leaded Glass Vitrail au plomb + Damp Paper Papier humide Shape Forme Shape Builder Concepteur de forme Shape Builder Regions Zones du Concepteur de forme @@ -3217,6 +3270,7 @@ digits Malayalam Malayalam Show Modified Afficher les éléments modifiés Show Note Afficher la note Show Options Afficher les options + Show Recent Colors Afficher les couleurs récentes Show Original Path Afficher le tracé d’origine Open this dialog with these settings next time Ouvrir cette boîte de dialogue avec ces réglages la prochaine fois Auto-Simplify Simplifier automatiquement @@ -3521,6 +3575,8 @@ digits Malayalam Malayalam Scale at Center Mettre à l’échelle depuis le centre Up/Down: Haut/bas : Left/Right: Gauche/droite : + Tate-chu-yoko Up/Down Tate-chu-yoko haut/bas + Tate-chu-yoko Left/Right Tate-chu-yoko gauche/droite Temperature Température Temperature/Tint… Température/teinte… Template Modèle @@ -3590,6 +3646,8 @@ digits Malayalam Malayalam Toolbar: Single/Double Column Barre d’outils : une/deux colonnes Toolbar: Add Tool Barre d’outils : ajouter un outil Toolbar: Remove Tool Barre d’outils : retirer un outil + Add Tool… Ajouter un outil… + Remove Tool Retirer un outil Toolbar: Reset Barre d’outils : réinitialiser Toolbars Barres d’outils Tools Outils @@ -3660,6 +3718,8 @@ digits Malayalam Malayalam Type on a Path Texte curviligne Type on a Path Options Options de texte curviligne Type on a Path Options… Options de texte curviligne… + Center on Top Centrer en haut + Center on Bottom Centrer en bas Type on a Path Tool Outil Texte curviligne Type Orientation Orientation du texte Type stays text, and every stroke is a line with its lineweight and dashes. Le texte reste du texte, et chaque contour devient une ligne avec son épaisseur et ses tirets. @@ -3853,6 +3913,7 @@ digits Malayalam Malayalam Windows Windows Working CMYK CMJN de travail Working CMYK (don't tag) CMJN de travail (sans balise) + Working RGB (don't tag) RVB de travail (sans balise) Workspace Espace de travail Workspace {i} Espace de travail {i} Wrinkle Tool Outil Fronces @@ -4034,6 +4095,13 @@ axis Both Les deux Dock Panel Ancrer le panneau Dock to Top Ancrer en haut Dock to Bottom Ancrer en bas + Control Bar Options Options de la barre de contrôle + Tool Options Options de l’outil + Object Options Options de l’objet + Image Options Options de l’image + Vertical Alignment Alignement vertical + Align and Distribute Aligner et répartir + Document Options Options du document Dock Control Bar Ancrer la barre de contrôle Drag to float the toolbar Faire glisser pour rendre la barre d’outils flottante Drag to the window's left or right edge to dock Faire glisser vers le bord gauche ou droit de la fenêtre pour ancrer @@ -4186,10 +4254,13 @@ axis Both Les deux @msg `groupColors` must be an array `groupColors` doit être un tableau @msg `library` is a library id or name (see {list}) `library` est l’identifiant ou le nom d’une bibliothèque (voir {list}) @msg `mode` applies to freeform gradients `mode` s’applique aux dégradés de forme libre +@msg a negative `aspect` applies to conic gradients un `aspect` négatif s’applique aux dégradés coniques +@msg `focal` applies to radial gradients `focal` s’applique aux dégradés radiaux @msg `preserve` must be an object `preserve` doit être un objet @msg `globalAdjust` must be an object `globalAdjust` doit être un objet @msg `sampleSize` must be 1, 3 or 5 `sampleSize` doit valoir 1, 3 ou 5 @msg `stops` must be an array `stops` doit être un tableau +@msg `{key}` must be an array `{key}` doit être un tableau @msg `svg` must be an object of SVG options (see document.formats) `svg` doit être un objet d’options SVG (voir document.formats) @msg `{_1}` is no save command `{_1}` n’est pas une commande d’enregistrement @msg `{area}` is no recovery area name `{area}` n’est pas un nom de zone de récupération @@ -4203,6 +4274,7 @@ axis Both Les deux @msg `{key}` must be a number, not {v} `{key}` doit être un nombre, pas {v} @msg {key} must be Unix seconds (an integer) or null {key} doit être un temps Unix en secondes (un entier) ou null @msg `{key}` must be a string `{key}` doit être une chaîne +@msg `{key}` must be a profile name or null `{key}` doit être un nom de profil ou null @msg `{key}` must be a whole number `{key}` doit être un nombre entier @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` doit être un nombre entier compris entre {min} et {max} (reçu : {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` doit être compris entre {min} et {max} (reçu : {x}) @@ -4354,6 +4426,7 @@ axis Both Les deux @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la page du plan de travail {n} mesure {size}, plus que la limite de page PDF de 14 400 pt (200 in) : elle est écrite avec une UserUnit de {unit}, donc les applications qui ignorent UserUnit l’affichent autant de fois plus petite @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la page du plan de travail {n} mesure {size}, plus que la limite de page PDF de 14 400 pt (200 in) : les pages {label} sont écrites sans UserUnit, en points, et les applications qui respectent la limite coupent la page à 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 n’a pas d’UserUnit, dont une page de plus de 14 400 pt (200 in) a besoin pour garder sa taille : le fichier est écrit en PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 n’a pas d’UserUnit, dont une page de plus de 14 400 pt (200 in) a besoin pour rester dans la limite de page de PDF/A-2, 14 400 unités : le fichier est écrit en PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la page du plan de travail {n} mesure {size}, trop longue et étroite pour les côtés de page PDF de 3 à 14 400 unités : elle est écrite avec une UserUnit de {unit}, qui garde le petit côté à 3 unités ou plus, et les apps qui respectent la limite coupent le grand côté à 14 400 unités @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard les fichiers {label} acceptent des nombres réels jusqu’à {max}, et la page du plan de travail {n}, longue de {side} pt, en demande de plus grands : choisissez PDF 1.6 ou ultérieur sans norme PDF/X, ou un plan de travail plus petit @msg invalid PDF setting: {0} réglage PDF non valide : {0} @@ -4503,6 +4576,8 @@ axis Both Les deux @msg not a stored central record ce n’est pas un enregistrement central stocké @msg not a valid plug-in module: {0} ce n’est pas un module de plug-in valide : {0} @msg not an EMF or WMF file ce n’est pas un fichier EMF ou WMF +@msg not an HP-GL file ce n’est pas un fichier HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` doit être une liste de 1 à 255 couleurs #rrggbb @msg not found introuvable @msg not in pattern editing mode pas en mode d’édition de motif @msg finish editing the pattern first terminez d’abord la modification du motif @@ -4582,6 +4657,14 @@ axis Both Les deux @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 cette vectorisation créerait plus de {max} points d’ancrage, plus que le document ne peut afficher de façon fluide : augmentez Bruit, réduisez Tracés ou Couleurs, ou choisissez un paramètre prédéfini moins fidèle @msg select an envelope sélectionnez une enveloppe @msg select an image sélectionnez une image +@msg `background` must be edges, corners or colors `background` doit valoir edges, corners ou colors +@msg `match` must be distance or channels `match` doit valoir distance ou channels +@msg `{key}` must be from 0 to 100 `{key}` doit être compris entre 0 et 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` doit contenir de 1 à 16 couleurs, chacune en hexadécimal (#rrggbb ou #rgb) ou sous la forme black, white, red, green ou blue +@msg the linked image shows its preview: embed or relink it first l’image liée affiche son aperçu : incorporez-la ou rétablissez d’abord le lien +@msg a CMYK image has no transparency to set une image CMJN n’a pas de transparence à définir +@msg every pixel matches the background: no image would be left chaque pixel correspond à l’arrière-plan : il ne resterait aucune image +@msg an image of {w} × {h} pixels is too large to change une image de {w} × {h} pixels est trop grande pour être modifiée @msg select an object in perspective sélectionnez un objet en perspective @msg select artwork (or a colour group) to recolor sélectionnez l’illustration (ou un groupe de couleurs) dont redéfinir les couleurs @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloration terminée ; sans changement : {locked} et {hidden} @@ -4688,7 +4771,7 @@ axis Both Les deux @msg unknown format format inconnu @msg unknown format `{f}` (Save writes {_1}) format inconnu `{f}` (Enregistrer écrit {_1}) @msg unknown freeform mode `{m}` (points, lines) mode de forme libre inconnu `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) type de dégradé inconnu `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) type de dégradé inconnu `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` mise en évidence inconnue `{h}` @msg unknown option `{path}.{k}` option inconnue `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) surimpressions inconnues `{o}` (preserve, simulate ou discard) @@ -4932,6 +5015,8 @@ axis Both Les deux @msg invalid object id {value}: expected a non-negative integer identifiant d’objet {value} non valide (un entier positif ou nul est attendu) @msg `{key}` entry {index} is {value}, not a non-negative integer object id l’entrée {index} de `{key}` vaut {value}, pas un identifiant d’objet (entier positif ou nul) @msg no such object id {value} aucun objet ne porte l’identifiant {value} +@msg id {value} is a ruler guide, not an object l’identifiant {value} est celui d’un repère, pas d’un objet +@msg a ruler guide goes only directly in a layer or sublayer un repère ne peut se trouver que directement dans un calque ou un sous-calque @msg id {value} is a layer, not an object l’identifiant {value} désigne un calque, pas un objet @msg id {value} is a layer, not an object; move layers with layer.move l’identifiant {value} désigne un calque, pas un objet ; déplacez les calques avec layer.move @msg automation filesystem access is not granted: read authority is absent: {path} l’automatisation n’a pas accès au système de fichiers : aucune autorisation de lecture : {path} @@ -4961,7 +5046,13 @@ axis Both Les deux @msg the HEIC or HEIF file holds a kind of image that can't be read le fichier HEIC ou HEIF contient un type d'image qui ne peut pas être lu @msg HEIC and HEIF images can't be opened in this build les images HEIC et HEIF ne peuvent pas être ouvertes dans cette version @msg the PSD image is too large to read ({_1} × {_2} pixels) l'image PSD est trop grande pour être lue ({_1} × {_2} pixels) -@msg zipped 32-bit PSD image data with prediction can't be read les données d'image PSD 32 bits compressées en ZIP avec prédiction ne peuvent pas être lues +@msg zipped 1-bit PSD image data with prediction can't be read les données d'image PSD 1 bit compressées en ZIP avec prédiction ne peuvent pas être lues +@msg the PSD file's layer data uses an unknown compression ({m}) les données de calque du fichier PSD utilisent une compression inconnue ({m}) +@msg the PSD file's layer records are damaged les enregistrements de calques du fichier PSD sont endommagés +@msg the PSD file's layer groups are nested too deeply les groupes de calques du fichier PSD sont imbriqués trop profondément +@msg a layer of the PSD file is too large to read un calque du fichier PSD est trop grand pour être lu +@msg the PSD file's layers take more memory to read than allowed les calques du fichier PSD demandent plus de mémoire que permis pour être lus +@msg the layers can't be read ({e}): the file opened as its merged image les calques ne peuvent pas être lus ({e}) : le fichier a été ouvert comme son image fusionnée @msg {depth}-bit PSD files in this colour mode can't be read les fichiers PSD {depth} bits dans ce mode colorimétrique ne peuvent pas être lus @msg the PSD file is cut short le fichier PSD est tronqué @msg the PSD file's header is damaged l'en-tête du fichier PSD est endommagé @@ -5700,6 +5791,11 @@ theme Appearance Apparence Softness Douceur Ambient Light Lumière ambiante Light behind the object Lumière derrière l'objet + Shadows Ombres + Distance from Object Distance de l'objet + Shadow Bounds Limites de l'ombre + Behind Object Derrière l'objet + Below Object Sous l'objet 3D Lighting Preset Préréglage d’éclairage 3D Standard Standard Diffuse Diffus @@ -5763,7 +5859,7 @@ theme Appearance Apparence @msg span must be "object" or "selection", got {v} span doit être "object" ou "selection", pas {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" place un `gradient`, pas une nuance @msg span: "selection" places a gradient: give `gradient` span: "selection" place un dégradé : indiquez `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" place un dégradé linéaire ou radial, pas un dégradé de forme libre +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" place un dégradé linéaire, radial, conique ou en losange, pas un dégradé de forme libre @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" place le dégradé lui-même : omettez `start` et `end` (ils le placent déjà en coordonnées du document) Make Image Dynamic Rendre l'image dynamique Import Data Sets… Importer des jeux de données… @@ -5946,6 +6042,7 @@ theme Appearance Apparence Ruby Ruby Geometric Guides Repères géométriques Geometric Patterns Motifs géométriques + Grit Textures Textures granuleuses Ease In Accélération progressive Ease Out Décélération progressive Ease In Out Accélération et décélération @@ -6004,6 +6101,8 @@ axis Y Axis Axe Y Version: {version} Version : {version} Install “{name}” in place of the plug-in with the same ID? Installer « {name} » à la place du module externe qui a le même ID ? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ce fichier n’est pas le module externe installé auparavant avec cet ID. Il reçoit les réglages et le cache conservés pour cet ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Une automatisation a demandé l’installation de ce module externe. Pour l’installer, choisissez Objet › Modules externes › Installer un module externe… vous-même. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Une automatisation a demandé l’installation de ce module externe. Pour l’installer, choisissez Objet › Modules externes › Installer un module externe… vous-même. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees « {name} » est un autre module que le module externe d’ID {_1} et recevrait les réglages et le cache conservés pour celui-ci : installez-le avec `replace: true` une fois que l’utilisateur l’accepte File SHA-256: {hash} SHA-256 du fichier : {hash} Read the objects it is given Lire les objets qui lui sont transmis @@ -6050,6 +6149,11 @@ axis Y Axis Axe Y @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget d’objets (plus de {MAX_OBJECTS} objets en lecture seule) +@msg instruction budget budget d’instructions +@msg time budget budget de temps +@msg memory budget (the selection is too large to hand over) budget mémoire (la sélection est trop grande pour être transmise) +@msg output size ({what} is {len} bytes, limit {max}) taille de sortie ({what} fait {len} octets, limite {max}) +@msg the plug-in's grant can't be removed from the plug-in store l’autorisation du plug-in ne peut pas être retirée du magasin de plug-ins @msg unknown permission `{shown}` autorisation inconnue `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants « {name} » demande les autorisations {asked} : une personne doit les approuver dans l’application de bureau, ou passez `grant` dans une session démarrée avec --allow-plugin-grants @msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` et `allowHeavy` ne prennent effet que dans une session démarrée avec --allow-plugin-grants : approuvez le module externe dans l’application de bureau @@ -6061,6 +6165,12 @@ axis Y Axis Axe Y @msg command {name}: `label` must be 1-64 printable characters commande {name} : `label` doit compter 1-64 caractères imprimables @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter commande {name} : utilisez un id de 1-{MAX_COMMAND_ID} caractères parmi a-z 0-9 _ commençant par une lettre @msg command {name}: {e} commande {name} : {e} +@msg manifest: {e} manifeste : {e} +@msg manifest: {e} at line {line} column {column} manifeste : {e} (ligne {line}, colonne {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` doit être une liste de commandes, chacune avec `id` et `label` +@msg command {name} must be an object with an `id` and a `label` la commande {name} doit être un objet avec `id` et `label` +@msg missing field `{key}` champ `{key}` manquant +@msg duplicate field `{key}` champ `{key}` en double @msg only a filter or a live effect declares `commands` seul un filtre ou un effet dynamique déclare `commands` @msg “{name}” › {label}: {e} « {name} » › {label} : {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed le module n’a pas le SHA-256 indiqué par `hash` : rien n’a été installé @@ -6085,6 +6195,16 @@ axis Y Axis Axe Y @msg message must be text message doit être du texte @msg allowContinue must be true or false allowContinue doit valoir true ou false @msg Batch cannot play an action with a stop Le traitement par lots ne peut pas exécuter un script comportant un arrêt + Insert Menu Item… Insérer une commande de menu… + Insert Menu Item Insérer une commande de menu + Menu Item: Commande de menu : + No menu item matches. Aucune commande de menu ne correspond. + Several menu items match. Choose one from the list. Plusieurs commandes de menu correspondent. Choisissez-en une dans la liste. + Items that open a dialog, and File, Window and Help menu items, are not listed. Les commandes qui ouvrent une boîte de dialogue et celles des menus Fichier, Fenêtre et Aide ne sont pas listées. +@msg command must be text command doit être du texte +@msg no menu item that can be inserted runs this command aucune commande de menu insérable n’exécute cette commande +@msg the action already has 10,000 steps le script compte déjà 10 000 étapes +@msg the action set would be larger than 8 MiB le jeu de scripts dépasserait 8 Mio Playback Options Options d’exécution Accelerated Accélérée Step by Step Pas à pas @@ -6123,6 +6243,12 @@ axis Y Axis Axe Y Crosshair Réticule Checkpoint Point de contrôle Inventory Icons Icônes d’inventaire + Skill Icons Icônes de compétences + Attack Attaque + Defend Défense + Heal Soin + Buff Bonus + Ult Ult Sword Épée Shield Bouclier Potion Potion @@ -6187,7 +6313,23 @@ axis Y Axis Axe Y Dash Trail Traînée tiretée Speed Line Ligne de vitesse Game Trails Traînées de jeu + Energy Beams Faisceaux d'énergie + Laser Bolt Trait laser + Plasma Arc Arc de plasma + Charge Wave Vague de charge + Spark Trail Traînée d'étincelles Calligraphic Nibs Plumes calligraphiques + Bristle Brushes Pinceaux à soies + Fine Liner Traceur fin + Pointed Flat Plat pointu + Stubby Round Rond court + Dry Scrub Frottis sec + Soft Dome Dôme doux + Filbert Langue de chat + Angled Round Rond biseauté + Angled Flat Plat biseauté + Fan Blender Éventail estompeur + Grass Fan Éventail à herbe Pattern Borders Bordures de motif Scatter Shapes Formes de dispersion Save Brush Library… Enregistrer la bibliothèque de formes… @@ -6384,9 +6526,12 @@ anchor Points: Points : @msg {label} must be a number {label} doit être un nombre @msg {label} must be a number of at least 0.1 {label} doit être un nombre d’au moins 0,1 Advanced Character Formats Formats de caractère avancés + Basic Paragraph Formats Formats de paragraphe de base + Composition Composition Horizontal Scale Mise à l’échelle horizontale Vertical Scale Échelle verticale @msg {label} must be a number from {min} to {max} {label} doit être un nombre compris entre {min} et {max} +@msg {label} must be a whole number from {min} to {max} {label} doit être un nombre entier compris entre {min} et {max} Character Color Couleur des caractères OpenType Features Fonctions OpenType Stylistic Sets Jeux stylistiques @@ -6394,6 +6539,10 @@ anchor Points: Points : @msg features lists at most {max} tags features contient au plus {max} balises @msg unknown OpenType feature `{t}` fonction OpenType inconnue `{t}` @msg {label} must be a number above 0 and at most {max} {label} doit être un nombre supérieur à 0 et au plus égal à {max} +@msg {label} must be at most {max} characters {label} doit compter au plus {max} caractères +@msg {label} must be one character {label} doit être un seul caractère +@msg at most {max} tab stops au plus {max} taquets de tabulation +@msg unknown align `{other}` alignement inconnu `{other}` @msg no character style `{name}` Style de caractère `{name}` introuvable # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6555,6 +6704,12 @@ breakText Glyphs Glyphes Delete the selected brushes? Supprimer les formes sélectionnées ? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Des contours utilisent une ou plusieurs de ces formes. Retirer les formes de ces contours et supprimer les formes ? Remove Strokes Supprimer les contours + Place Brush Art Placer l’illustration de la forme + Replace Brush Art Remplacer l’illustration de la forme + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Des contours utilisent cette forme. Appliquer la nouvelle illustration à ces contours, ou les laisser tels quels et ajouter une copie de la forme avec la nouvelle illustration ? + Apply to Strokes Appliquer aux contours + Leave Strokes Conserver les contours +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` n’a pas d’illustration (seules les formes diffuses, artistiques et de motif en ont) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Outils de disposition Arrange in Grid… Disposer en grille… @@ -6750,6 +6905,11 @@ breakText Glyphs Glyphes @msg only an exporter or an importer declares `extensions` seul un module externe d’exportation ou d’importation déclare `extensions` @msg an importer always gets an import's budget: leave `budget` out un module externe d’importation reçoit toujours le budget d’une importation : omettez `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Copier les informations de dépannage +@msg Copied the troubleshooting info Informations de dépannage copiées +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report La dernière session de VectorCraft a cessé de répondre avant de se fermer. Aide › Copier les informations de dépannage copie les détails pour un rapport de bogue + # Safe Mode Safe Mode… Mode sans échec… Safe Mode Mode sans échec @@ -6770,6 +6930,8 @@ breakText Glyphs Glyphes # Align to Pixel Grid Align to Pixel Grid Aligner sur la grille de pixels + Align New Objects to Pixel Grid Aligner les nouveaux objets sur la grille de pixels + Not Aligned to Pixel Grid Non aligné sur la grille de pixels @msg only paths and compound paths can be aligned to the pixel grid seuls les tracés et les tracés transparents peuvent être alignés sur la grille de pixels @msg side is left or right, not `{s}` side vaut left ou right, pas `{s}` Ignore All Tout ignorer @@ -6800,8 +6962,33 @@ breakText Glyphs Glyphes @plural {n} line cut|{n} lines cut {n} ligne coupée|{n} lignes coupées @msg `first` and `last` must be numbers of lines the console holds, first before last `first` et `last` doivent être des numéros de lignes que la console contient, `first` avant `last` +# Learn panel + Learn Apprendre + Explore tutorials Découvrir les tutoriels + For you Pour vous + Skills Compétences + Get started Prise en main + Quick skill guide Guide rapide des compétences + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Courts tutoriels pratiques sur les outils essentiels, regroupés par compétence. Choisissez une compétence pour voir ses tutoriels. + List Tutorials Lister les tutoriels + Show Tutorial Afficher le tutoriel +@msg missing `tutorial` (see learn.list) `tutorial` manquant (voir learn.list) +@msg unknown tutorial `{id}` (see learn.list) tutoriel inconnu `{id}` (voir learn.list) + # Deferred plug-in effects Refresh Deferred Effects Actualiser les effets différés Deferred Effects Effets différés @msg no plug-in effect is deferred aucun effet de plug-in n’est différé @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Ouvert avec {n} effet de plug-in différé. Effet › Actualiser les effets différés l’exécute.|Ouvert avec {n} effets de plug-in différés. Effet › Actualiser les effets différés les exécute. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Outils de découpe + Stencil Bridges… Ponts de pochoir… + Stencil Bridges Ponts de pochoir + Shortest Crossing Traversée la plus courte + Direction Direction +@msg The selected art has no islands to bridge L’illustration sélectionnée n’a aucun îlot à relier +@msg No bridge of this width fits across the selected art Aucun pont de cette largeur ne tient en travers de l’illustration sélectionnée +@msg Some islands could not be joined to the area around the art Certains îlots n’ont pas pu être reliés à la zone autour de l’illustration +@msg `width` must be from {lo} to {hi} pt `width` doit être compris entre {lo} et {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` doit être un nombre entier compris entre 1 et {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 296f18e805..8f66a1b354 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -263,6 +263,8 @@ Adjustment समायोजन Advanced उन्नत Advanced Character Formats उन्नत कैरेक्टर फ़ॉर्मैट + Basic Paragraph Formats बुनियादी पैराग्राफ़ फ़ॉर्मैट + Composition संयोजन Advanced Options उन्नत ऑप्शन्स After First: शुरू के बाद: Align संरेखित करें @@ -427,6 +429,11 @@ antiAlias Sharp शार्प Dash Trail डैश ट्रेल Speed Line स्पीड लाइन Game Trails गेम ट्रेल्स + Energy Beams ऊर्जा किरणें + Laser Bolt लेज़र बोल्ट + Plasma Arc प्लाज़्मा चाप + Charge Wave चार्ज तरंग + Spark Trail चिंगारी पथ Art using a deleted global swatch keeps its colour. हटाए गए ग्लोबल स्वॉच वाला आर्टवर्क अपना रंग बनाए रखता है। Artboard आर्टबोर्ड Artboard {n} of {total} {total} में से आर्टबोर्ड {n} @@ -527,6 +534,12 @@ antiAlias Sharp शार्प Crosshair क्रॉसहेयर Checkpoint चेकपॉइंट Inventory Icons इन्वेंटरी आइकन + Skill Icons कौशल आइकन + Attack आक्रमण + Defend रक्षा + Heal उपचार + Buff बफ़ + Ult अल्ट Sword तलवार Shield ढाल Potion औषधि @@ -678,6 +691,17 @@ antiAlias Sharp शार्प Calligraphic Brush कैलिग्राफिक ब्रश Calligraphic Brush Options कैलिग्राफिक ब्रश ऑप्शन्स Calligraphic Nibs कैलिग्राफिक निब्स + Bristle Brushes ब्रिसल ब्रश संग्रह + Fine Liner बारीक लाइनर + Pointed Flat नुकीला फ्लैट + Stubby Round छोटा गोल + Dry Scrub सूखी रगड़ + Soft Dome मुलायम गुंबद + Filbert फिल्बर्ट + Angled Round तिरछा गोल + Angled Flat तिरछा फ्लैट + Fan Blender मिश्रण पंखा + Grass Fan घास पंखा Can't export “{name}”. "{name}" निर्यात नहीं कर सकते। Can't open “{name}”. "{name}" नहीं खोल सकते हैं। Can't print these settings: see the Summary इन सेटिंग्स को मुद्रित नहीं कर सकते: सारांश देखें @@ -1086,6 +1110,15 @@ antiAlias Sharp शार्प Croatian क्रोएशियाई Crop क्रॉप करें Crop Image फसल की इमेज + Image Tools इमेज टूल + Remove Background… पृष्ठभूमि हटाएँ… + Remove Background पृष्ठभूमि हटाएँ + Background पृष्ठभूमि + Edge Color किनारे का रंग + Picked Colors चुने गए रंग + Corner Color कोनों का रंग + Contiguous सन्निहित + Each Channel प्रत्येक चैनल Crop Marks क्रॉप मार्क Crop To करने के लिए फसल Cross क्रॉस @@ -1337,6 +1370,13 @@ antiAlias Sharp शार्प Dock Panel पैनल डॉक करें Dock to Top ऊपर डॉक करें Dock to Bottom नीचे डॉक करें + Control Bar Options नियंत्रण बार ऑप्शन्स + Tool Options टूल ऑप्शन्स + Object Options ऑब्जेक्ट ऑप्शन्स + Image Options इमेज ऑप्शन्स + Vertical Alignment वर्टिकल अलाइनमेंट + Align and Distribute संरेखित और वितरित करें + Document Options डॉक्यूमेंट ऑप्शन्स Dock Control Bar नियंत्रण बार डॉक करें Document डॉक्यूमेंट Document Color Mode डॉक्यूमेंट रंग मोड @@ -1716,6 +1756,8 @@ antiAlias Sharp शार्प Extrude & Bevel… एक्सट्रूडेड और बेवेल… 3D (Classic) 3D (क्लासिक) Extrude & Bevel (Classic)… एक्सट्रूडेड और बेवेल (क्लासिक)… + Revolve (Classic)… रिवॉल्व (क्लासिक)… + Rotate (Classic)… घुमाव (क्लासिक)… Surface सतह Wireframe वायरफ़्रेम No Shading कोई शेडिंग नहीं @@ -2044,6 +2086,7 @@ antiAlias Sharp शार्प Gridline every ग्रिडलाइन हर Gridline every: ग्रिडलाइन हर: Grids In Back ग्रिड में वापस + Grit Textures दानेदार टेक्सचर Group समूह Group Overlapping Objects समूह ओवरलैपिंग ऑब्जेक्ट Group Selection समूह सिलेक्शन @@ -2071,6 +2114,14 @@ antiAlias Sharp शार्प Hand हैंड Hand Tool हैंड टूल Hand-Drawn हाथ-ड्रन + Painted and Sketched पेंट और स्केच + Washed Blue धुला नीला + Bristle Ochre ब्रश गेरू + Pastel Heather पेस्टल बैंगनी + Charcoal Shade चारकोल छाया + Ink Contour स्याही रूपरेखा + Wet Ink गीली स्याही + Fine Pen बारीक पेन Handles हैंडल्स Hard कठोर Hard Light हार्ड लाइट @@ -2257,6 +2308,7 @@ antiAlias Sharp शार्प Include Linked Files लिंक्ड फ़ाइलें शामिल करें Include Metadata मेटाडाटा शामिल Include non-printing layers गैर-प्रिंटिंग लेयर्स को शामिल करें + Write pages longer than 200 in at full size in points 200 in से लंबे पेज पूरे आकार में, पॉइंट में लिखें Include Objects On Canvas कैनवास पर ऑब्जेक्ट्स शामिल करें Include SVG Code SVG कोड शामिल करें Include Swatches for Tints टिंट्स के लिए स्वॉचेस शामिल करें @@ -2437,6 +2489,8 @@ antiAlias Sharp शार्प Left-to-Right Paragraph Direction बाएँ-से-दाएँ पैराग्राफ़ दिशा Left: बाएँ: Left/Right: बाएं / दाएं: + Tate-chu-yoko Up/Down ताते-चू-योको ऊपर/नीचे + Tate-chu-yoko Left/Right ताते-चू-योको बाएं/दाएं Legacy .ai Options पुराने .ai फ़ॉर्मैट के ऑप्शन्स Legacy (version 7) पुराना फ़ॉर्मैट (संस्करण 7) Legacy Macintosh RGB (Gamma 1.8) पुराना Macintosh RGB (गामा 1.8) @@ -2464,6 +2518,11 @@ antiAlias Sharp शार्प Ligatures are off while the text is tracked. टेक्स्ट पर ट्रैकिंग लागू होने पर लिगेचर ऑफ़ रहते हैं। Light लाइट Light behind the object ऑब्जेक्ट के पीछे प्रकाश + Shadows छायाएँ + Distance from Object ऑब्जेक्ट से दूरी + Shadow Bounds छाया सीमाएँ + Behind Object ऑब्जेक्ट के पीछे + Below Object ऑब्जेक्ट के नीचे Light Blue हल्का नीला Light Direction लाइट की दिशा Light Gray हल्का ग्रे @@ -3125,12 +3184,23 @@ antiAlias Sharp शार्प OpenType Features ओपन टाइप सुविधाएँ Optical ऑप्टिकल Optical Margin Alignment ऑप्टिकल मार्जिन संरेखण + Dynamic Text डायनैमिक टेक्स्ट + Dynamic Text Presets डायनैमिक टेक्स्ट प्रीसेट + Arch मेहराब +@msg select point type or type on a path पॉइंट टाइप या पाथ पर टाइप चुनें +@msg type on a path in a thread cannot use Dynamic Text: {frames} थ्रेडेड टेक्स्ट में पाथ पर टाइप डायनैमिक टेक्स्ट का उपयोग नहीं कर सकता: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} खुले पाथ या कंपाउंड पाथ पर टाइप को ऊपर या नीचे केंद्रित नहीं किया जा सकता: {open} +@msg type on a path with no length or no height cannot be centered: {flat} बिना लंबाई या बिना ऊँचाई वाले पाथ पर टाइप केंद्रित नहीं किया जा सकता: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} थ्रेडेड टेक्स्ट में पाथ पर टाइप को ऊपर या नीचे केंद्रित नहीं किया जा सकता: {frames} +@msg select type on a closed path बंद पाथ पर टाइप चुनें Optimize for fast web view तेजी से वेब दृश्य के लिए ऑप्टिमाइज़ Optimized ऑप्टिमाइज़्ड Options ऑप्शन्स Options for Selection… सिलेक्शन के लिए ऑप्शन्स… Options: ऑप्शन्स: Options… ऑप्शन्स… + Organic Fades ऑर्गेनिक फ़ेड + Holographic होलोग्राफ़िक or more spaces with a tab या एक टैब के साथ अधिक रिक्त स्थान Orange नारंगी Order: आदेश: @@ -3368,6 +3438,16 @@ antiAlias Sharp शार्प @msg message must be text message टेक्स्ट होना चाहिए @msg allowContinue must be true or false allowContinue true या false होना चाहिए @msg Batch cannot play an action with a stop बैच स्टॉप वाला एक्शन नहीं चला सकता + Insert Menu Item… मेनू आइटम जोड़ें… + Insert Menu Item मेनू आइटम जोड़ें + Menu Item: मेनू आइटम: + No menu item matches. कोई मेनू आइटम मेल नहीं खाता। + Several menu items match. Choose one from the list. कई मेनू आइटम मेल खाते हैं। सूची से एक चुनें। + Items that open a dialog, and File, Window and Help menu items, are not listed. डायलॉग खोलने वाले आइटम और फ़ाइल, विंडो और सहायता मेनू के आइटम सूचीबद्ध नहीं हैं। +@msg command must be text command टेक्स्ट होना चाहिए +@msg no menu item that can be inserted runs this command जोड़ा जा सकने वाला कोई मेनू आइटम यह कमांड नहीं चलाता +@msg the action already has 10,000 steps एक्शन में पहले से 10,000 कदम हैं +@msg the action set would be larger than 8 MiB एक्शन सेट 8 MiB से बड़ा हो जाएगा Playback Options प्लेबैक ऑप्शन्स Playback Options… प्लेबैक ऑप्शन्स… Plug-in Info प्लगइन जानकारी @@ -3449,6 +3529,7 @@ antiAlias Sharp शार्प Press Quality प्रेस गुणवत्ता Pressure दबाव Preview प्रीव्यू + Preview: प्रीव्यू: Preview (1 inch on the page) प्रीव्यू (1 इंच पृष्ठ पर) Preview All Layers सभी लेयर्स का प्रीव्यू करें Preview in Browser ब्राउज़र में प्रीव्यू @@ -3532,6 +3613,8 @@ antiAlias Sharp शार्प Radial Dividers: रेडियल विभाजक: Radial Glows रेडियल चमक Radial Gradient रेडियल ग्रेडिएंट + Conic Gradient शंक्वाकार ग्रेडिएंट + Diamond Gradient डायमंड ग्रेडिएंट Radial Repeat रेडियल दोहराव Radius त्रिज्या Radius 1 त्रिज्या 1 @@ -3550,6 +3633,8 @@ antiAlias Sharp शार्प Range: रेंज: Raster Effects रीस्टर इफ़ेक्ट Raster File Format: रास्टर फ़ाइल फ़ॉर्मैट: + Include Placed Images रखी गई छवियाँ शामिल करें + Include Fill Hatches फ़िल हैच शामिल करें Raster Sample Size: रास्टर सैंपल साइज़: Raster/Vector Balance: रास्टर/वेक्टर बैलेंस: Rasterize रास्टराइज़ करें @@ -3712,6 +3797,12 @@ antiAlias Sharp शार्प Remove Selected Assets सिलेक्टेड परिसंपत्तियों को हटा दें Remove Selected Entry सिलेक्टेड प्रविष्टि निकालें Remove Strokes स्ट्रोक हटाएँ + Place Brush Art ब्रश आर्टवर्क रखें + Replace Brush Art ब्रश आर्टवर्क बदलें + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? स्ट्रोक्स इस ब्रश का उपयोग कर रहे हैं। नया आर्टवर्क उन स्ट्रोक्स पर लागू करें, या उन्हें जैसा है वैसा छोड़कर नए आर्टवर्क वाले ब्रश की एक कॉपी जोड़ें? + Apply to Strokes स्ट्रोक्स पर लागू करें + Leave Strokes स्ट्रोक्स जैसे हैं वैसे छोड़ें +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` में कोई आर्टवर्क नहीं है (आर्टवर्क केवल स्कैटर, आर्ट और पैटर्न ब्रश में होता है) Remove the shortcut शॉर्टकट निकालें Remove Threading थ्रेडिंग निकालें Remove White Overprint व्हाइट ओवरप्रिंट निकालें @@ -3755,6 +3846,10 @@ antiAlias Sharp शार्प Replace Missing Fonts अनुपलब्ध फ़ॉन्ट रिप्लेस करें Replace Missing Fonts… अनुपलब्ध फ़ॉन्ट रिप्लेस करें… Replace Spine स्पाइन रिप्लेस करें + Create Spine स्पाइन बनाएँ + Create Spine: स्पाइन बनाएँ: + Always हमेशा + Never कभी नहीं Replace Symbol सिंबल रिप्लेस करें Reset Transformation रूपांतरण रीसेट करें Replace With Font इस फ़ॉन्ट से रिप्लेस करें @@ -3885,6 +3980,9 @@ antiAlias Sharp शार्प Roman रोमन Roman Baseline रोमन बेसलाइन Roman Hanging Punctuation रोमन हैंगिंग विराम चिह्न + Korean Line Break Anywhere कोरियाई लाइन ब्रेक कहीं भी + East Asian Composition Settings पूर्वी एशियाई संरचना सेटिंग्स + Korean Composition Settings कोरियाई संरचना सेटिंग्स Rotate घुमाएँ Rotate 90° CW 90° सीडब्ल्यू Rotate Tool रोटेट टूल @@ -4274,6 +4372,15 @@ antiAlias Sharp शार्प Stun Pulse स्तब्ध Stealth Fade छिपना Shield Buff ढाल + Textures बनावटें + Fine Grain महीन दाना + Canvas Weave कैनवास बुनावट + Burlap Sack टाट की बोरी + Cracked Glaze दरकी ग्लेज़ + Mosaic Floor मोज़ेक फ़र्श + Quilted Squares रज़ाईदार वर्ग + Leaded Glass सीसा जड़ा काँच + Damp Paper नम काग़ज़ Shaft: दस्ता: Shape शेप Shape Builder शेप बिल्डर @@ -4365,6 +4472,7 @@ antiAlias Sharp शार्प Show Modified संशोधित दिखाएँ Show Note नोट दिखाएं Show Options ऑप्शन्स दिखाएँ + Show Recent Colors हाल के रंग दिखाएँ Show Original Path मूल पाथ दिखाएं Show Package पैकेज करें दिखाएँ Show Panel शो पैनल @@ -4898,6 +5006,8 @@ antiAlias Sharp शार्प Toolbar: Add Tool टूलबार: ऐड टूल Toolbar: Advanced / Basic टूलबार: उन्नत / बुनियादी Toolbar: Remove Tool टूलबार: टूल निकालें + Add Tool… टूल जोड़ें… + Remove Tool टूल निकालें Toolbar: Reset टूलबार: रीसेट करें Toolbar: Show Controls टूलबार: शो कंट्रोल Toolbar: Single/Double Column टूलबार: सिंगल / डबल कॉलम @@ -5000,6 +5110,8 @@ antiAlias Sharp शार्प Type on a Path पाथ पर टाइप Type on a Path Options पाथ पर टाइप ऑप्शन्स Type on a Path Options… पाथ पर टाइप ऑप्शन्स… + Center on Top ऊपर केंद्रित करें + Center on Bottom नीचे केंद्रित करें Type on a Path Tool पाथ पर टाइप टूल Type Optimized टाइप ऑप्टिमाइज़ Type Orientation प्रकार अभिविन्यास @@ -5266,6 +5378,7 @@ antiAlias Sharp शार्प Words Longer Than: से ज्यादा शब्द: Working CMYK वर्किंग CMYK Working CMYK (don't tag) कार्य CMYK (टैग नहीं) + Working RGB (don't tag) कार्य RGB (टैग नहीं) Working RGB वर्किंग RGB Workspace वर्कस्पेस Workspace {i} वर्कस्पेस {i} @@ -5308,6 +5421,8 @@ antiAlias Sharp शार्प Version: {version} संस्करण: {version} Install “{name}” in place of the plug-in with the same ID? समान ID वाले प्लग-इन की जगह “{name}” इंस्टॉल करें? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. यह फ़ाइल इस ID के साथ पहले इंस्टॉल किया गया प्लग-इन नहीं है। इसे उस ID के लिए रखी गई सेटिंग्स और कैश मिलते हैं। + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. एक ऑटोमेशन ने इस प्लग-इन को इंस्टॉल करने के लिए कहा। इसे इंस्टॉल करने के लिए, स्वयं ऑब्जेक्ट › प्लग-इन्स › प्लग-इन इंस्टॉल करें… चुनें। +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. एक ऑटोमेशन ने इस प्लग-इन को इंस्टॉल करने के लिए कहा। इसे इंस्टॉल करने के लिए, स्वयं ऑब्जेक्ट › प्लग-इन्स › प्लग-इन इंस्टॉल करें… चुनें। @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}” आईडी {_1} वाले प्लग-इन से अलग मॉड्यूल है और उसके लिए रखी गई सेटिंग्स और कैश पा लेगा: उपयोगकर्ता की सहमति मिलने पर इसे `replace: true` से इंस्टॉल करें File SHA-256: {hash} फ़ाइल SHA-256: {hash} Read the objects it is given उसे दिए गए ऑब्जेक्ट्स पढ़ना @@ -5353,6 +5468,7 @@ antiAlias Sharp शार्प @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है @msg memory budget (object {_1} needs {size} bytes of input, {left} left) मेमोरी बजट (ऑब्जेक्ट {_1} को इनपुट के {size} बाइट चाहिए, {left} शेष हैं) @msg object budget (more than {MAX_OBJECTS} read-only objects) ऑब्जेक्ट बजट ({MAX_OBJECTS} से अधिक केवल-पठन ऑब्जेक्ट) +@msg the plug-in's grant can't be removed from the plug-in store प्लग-इन की अनुमति प्लग-इन स्टोर से हटाई नहीं जा सकती @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it अनुमति `{shown}` बाद के प्लग-इन API के लिए आरक्षित है; यह होस्ट इसे नहीं देता @msg unknown permission `{shown}` अज्ञात अनुमति `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” अनुमतियां {asked} मांगता है: इन्हें डेस्कटॉप ऐप में किसी व्यक्ति को स्वीकृत करना होगा, या --allow-plugin-grants से शुरू किए गए सत्र में `grant` दें @@ -5365,6 +5481,11 @@ antiAlias Sharp शार्प @msg command {name}: `label` must be 1-64 printable characters कमांड {name}: `label` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter कमांड {name}: a-z 0-9 _ के 1-{MAX_COMMAND_ID} वर्णों वाली ऐसी id इस्तेमाल करें जो अक्षर से शुरू हो @msg command {name}: {e} कमांड {name}: {e} +@msg manifest: {e} at line {line} column {column} प्रकटन: {e} (लाइन {line}, कॉलम {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` कमांड की एक सूची होनी चाहिए, हर एक में `id` और `label` हो +@msg command {name} must be an object with an `id` and a `label` कमांड {name} एक ऑब्जेक्ट होना चाहिए जिसमें `id` और `label` हों +@msg missing field `{key}` फ़ील्ड `{key}` नहीं है +@msg duplicate field `{key}` फ़ील्ड `{key}` दो बार है @msg only a filter or a live effect declares `commands` केवल फ़िल्टर या लाइव इफ़ेक्ट ही `commands` घोषित करता है @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed मॉड्यूल का SHA-256 वह नहीं है जो `hash` बताता है: कुछ भी इंस्टॉल नहीं हुआ @@ -5462,9 +5583,13 @@ antiAlias Sharp शार्प @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 at most {max} characters {label} में अधिकतम {max} वर्ण होने चाहिए +@msg {label} must be one character {label} एक वर्ण होना चाहिए +@msg at most {max} tab stops अधिकतम {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 whole 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} ने खाली परिणाम का उत्पादन किया @@ -5563,7 +5688,7 @@ antiAlias Sharp शार्प @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 asset ids (see assets.list) `{key}` को परिसंपत्ति ids की एक सरणी होना चाहिए (assets.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} होना चाहिए @@ -5635,7 +5760,7 @@ antiAlias Sharp शार्प @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 `asset` is the asset id (see assets.list) `asset` परिसंपत्ति आईडी है (assets.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` को संख्या होना चाहिए @@ -5758,6 +5883,8 @@ antiAlias Sharp शार्प @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 a negative `aspect` applies to conic gradients ऋणात्मक `aspect` शंक्वाकार ग्रेडिएंट्स पर लागू होता है +@msg `focal` applies to radial gradients `focal` रेडियल ग्रेडिएंट्स पर लागू होता है @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" होना चाहिए @@ -5814,6 +5941,7 @@ antiAlias Sharp शार्प @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 `{key}` must be an array `{key}` एक सारणी होना चाहिए @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` स्ट्रोक पर लागू होता है (stroke: true) @@ -6155,7 +6283,7 @@ antiAlias Sharp शार्प @msg closed must be a boolean closed: बंद होना चाहिए एक boolean @msg closing needs three anchors closing: बंद करने की जरूरत है तीन एंकर @msg collapsed must be true or false collapsed को true या false होना चाहिए -@msg color.profile: no RGB or CMYK profile is called “{profile}” Color.profile: कोई RGB या CMYK प्रोफ़ाइल को "{profile}" कहा जाता है। +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: "{profile}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है @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" जैसा रंग नहीं है @@ -6321,7 +6449,7 @@ antiAlias Sharp शार्प @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 EPS Save writes all artwork: use document.export for 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 प्रति के लिए हर नंबर का नाम लिया जाता है @@ -6357,7 +6485,7 @@ antiAlias Sharp शार्प @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 fit must be none|autoHeight|shrinkText|block, got {id} fit को none|autoHeight|shrinkText|block होना चाहिए, {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} @@ -6483,11 +6611,11 @@ antiAlias Sharp शार्प @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 docks a panel in the icon column: use window.panel.dock icon पैनल को आइकन कॉलम में डॉक करता है: window.panel.dock का उपयोग करें @msg icon must be true or false icon को true या false होना चाहिए @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 {value} is a layer, not an object; move layers with layer.move id {value} एक लेयर है, ऑब्जेक्ट नहीं; लेयर्स को layer.move से स्थानांतरित करें @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 होना चाहिए @@ -6542,6 +6670,7 @@ antiAlias Sharp शार्प @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller आर्टबोर्ड {n} का पेज {size} है, जो PDF की 14,400 pt (200 in) की पेज सीमा से लंबा है: इसे {unit} के UserUnit के साथ लिखा जाता है, इसलिए UserUnit को अनदेखा करने वाले ऐप इसे उतने गुना छोटा दिखाते हैं @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in आर्टबोर्ड {n} का पेज {size} है, जो PDF की 14,400 pt (200 in) की पेज सीमा से लंबा है: {label} पेज बिना UserUnit के, पॉइंट में लिखे जाते हैं, और सीमा मानने वाले ऐप पेज को 200 in पर काट देते हैं @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 में UserUnit नहीं है, जिसकी 14,400 pt (200 in) से लंबे पेज को अपना आकार बनाए रखने के लिए ज़रूरत होती है: फ़ाइल PDF 1.6 के रूप में लिखी जाती है +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 में UserUnit नहीं है, जिसकी 14,400 pt (200 in) से लंबे पेज को PDF/A-2 की 14,400 इकाइयों की पेज सीमा के भीतर रहने के लिए ज़रूरत होती है: फ़ाइल PDF 1.6 के रूप में लिखी जाती है @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units आर्टबोर्ड {n} का पेज {size} है, जो PDF की 3 से 14,400 इकाई की पेज भुजाओं के लिए बहुत लंबा और संकरा है: इसे {unit} की UserUnit के साथ लिखा जाता है, जो छोटी भुजा को 3 इकाई या अधिक पर रखती है, और सीमा का पालन करने वाले ऐप लंबी भुजा को 14,400 इकाई पर काट देते हैं @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} फ़ाइलें {max} तक की वास्तविक संख्याएँ रखती हैं, और आर्टबोर्ड {n} का {side} pt लंबा पेज इससे बड़ी संख्याएँ माँगता है: बिना PDF/X मानक के PDF 1.6 या बाद का चुनें, या छोटा आर्टबोर्ड @msg invalid point अमानवीय बिंदु @@ -6596,7 +6725,7 @@ antiAlias Sharp शार्प @msg kerning must be a number, "auto", or "optical" kerning एक संख्या, "auto", या "optical" होना चाहिए @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 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind 1, 2 या 3 होना चाहिए, या प्रीसेट `name` दें (perspective.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", "neutral" या एक बोल, न {v} होना चाहिए @msg lang must be one of {_1} lang: लैंग को {_1} में से एक होना चाहिए @@ -6661,7 +6790,7 @@ antiAlias Sharp शार्प @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` (see plugin.list) अनुपलब्ध `id` (plugin.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) @@ -6776,7 +6905,7 @@ antiAlias Sharp शार्प @msg no artboards named नामित कोई आर्टबोर्ड नहीं @msg no artwork कोई आर्टवर्क नहीं @msg no asset {id} कोई परिसंपत्ति {id} -@msg no asset {id} (see assets.list) कोई परिसंपत्ति {id} (Ession.list) नहीं है। +@msg no asset {id} (see assets.list) कोई परिसंपत्ति {id} नहीं है (assets.list देखें) @msg no assets to export निर्यात करने के लिए कोई संपत्ति नहीं @msg no assets yet: collect art for export first (assets.add) अभी तक कोई संपत्ति नहीं: पहले निर्यात के लिए कला इकट्ठा (assets.add) @msg no blend options कोई मिश्रण ऑप्शन्स नहीं @@ -6873,7 +7002,7 @@ antiAlias Sharp शार्प @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 `{b}` (see perspective.presets.list) `{b}` नाम का कोई पर्सपेक्टिव ग्रिड प्रीसेट नहीं है (perspective.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} स्थापित नहीं है @@ -6926,7 +7055,7 @@ antiAlias Sharp शार्प @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 {n} in the image (see slice.list) इमेज में कोई स्लाइस {n} नहीं है (slice.list देखें) @msg no slice selected सिलेक्टेड कोई स्लाइस नहीं @msg no source art कोई स्रोत कला @msg no stop {i} (the gradient has {n}) नहीं रोक {i} (ग्रेडेंट {n} है) @@ -6936,7 +7065,7 @@ antiAlias Sharp शार्प @msg no such action step ऐसी कोई कार्रवाई नहीं @msg no such anchor ऐसा कोई एंकर नहीं @msg no such artboard ऐसा कोई आर्टबोर्ड नहीं -@msg no such assets (see assets.list) ऐसी कोई संपत्ति नहीं (देखें परिसंपत्तियां)। +@msg no such assets (see assets.list) ऐसी कोई परिसंपत्ति नहीं है (assets.list देखें) @msg no such color ऐसा कोई रंग नहीं @msg no such document ऐसा कोई डॉक्यूमेंट नहीं @msg no such frame anchor, or the frame would reach past the canvas इस तरह के फ्रेम एंकर नहीं, या फ्रेम कैनवास तक पहुंच जाएगा @@ -6944,6 +7073,8 @@ antiAlias Sharp शार्प @msg no such layer or object ऐसी कोई लेयर या ऑब्जेक्ट नहीं @msg no such object {0} ऐसी कोई ऑब्जेक्ट नहीं {0} @msg no such object id {value} ऐसी कोई ऑब्जेक्ट नहीं id {value} +@msg id {value} is a ruler guide, not an object id {value} एक गाइड है, ऑब्जेक्ट नहीं +@msg a ruler guide goes only directly in a layer or sublayer गाइड केवल सीधे किसी लेयर या सबलेयर में हो सकता है @msg no such objects ऐसी कोई ऑब्जेक्ट नहीं @msg no such path anchor, or the path would reach past the canvas इस तरह के कोई पाथ एंकर नहीं, या पाथ कैनवास तक पहुंच जाएगा @msg no such perspective grid preset ऐसा कोई पर्सपेक्टिव ग्रिड पूर्व निर्धारित नहीं है @@ -7032,6 +7163,8 @@ antiAlias Sharp शार्प @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out “{name}” लोड किया गया: {n} चरण छोड़ा गया|“{name}” लोड किया गया: {n} चरण छोड़े गए @msg not an action set file एक एक्शन सेट फ़ाइल नहीं @msg not an EMF or WMF file नहीं एक EMF या WMF फ़ाइल +@msg not an HP-GL file HP-GL फ़ाइल नहीं है +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` को 1 से 255 #rrggbb रंगों की ऐरे होना चाहिए @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 देखें) @@ -7114,7 +7247,7 @@ antiAlias Sharp शार्प @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 belong to window.panel.float and window.panel.dock onto, above, below, icon और column स्थान window.panel.float और 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 अपनी लिंक्ड फ़ाइलों को देखने के लिए एक डॉक्यूमेंट ओपन करें @@ -7128,10 +7261,10 @@ antiAlias Sharp शार्प @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.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} फ़ाइलें CMYK हैं, और "{name}" एक RGB प्रोफ़ाइल है +@msg output.destination: {e} output.destination: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: "{name}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है +@msg output.inks: no ink is set to print output.inks: प्रिंट करने के लिए कोई स्याही सेट नहीं है @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} आउटपुट इंटेंट अपनी प्रोफ़ाइल एम्बेड करता है @@ -7323,6 +7456,14 @@ antiAlias Sharp शार्प @msg select a text object एक टेक्स्ट ऑब्जेक्ट चुनें @msg select an envelope एक लिफाफे सिलेक्ट करें @msg select an image एक इमेज चुनें +@msg `background` must be edges, corners or colors `background` edges, corners या colors होना चाहिए +@msg `match` must be distance or channels `match` distance या channels होना चाहिए +@msg `{key}` must be from 0 to 100 `{key}` 0 से 100 तक होना चाहिए +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` में 1 से 16 रंग होने चाहिए, हर एक हेक्स (#rrggbb या #rgb) में या black, white, red, green या blue के रूप में +@msg the linked image shows its preview: embed or relink it first लिंक्ड इमेज अपना पूर्वावलोकन दिखा रही है: पहले इसे एम्बेड करें या फिर से लिंक करें +@msg a CMYK image has no transparency to set CMYK इमेज में सेट करने के लिए कोई पारदर्शिता नहीं है +@msg every pixel matches the background: no image would be left हर पिक्सेल पृष्ठभूमि से मेल खाता है: कोई इमेज नहीं बचेगी +@msg an image of {w} × {h} pixels is too large to change {w} × {h} पिक्सेल की इमेज बदलने के लिए बहुत बड़ी है @msg select an image (or an Image Trace group) एक इमेज सिलेक्ट करें (या एक इमेज ट्रेस समूह) @msg select an Image Trace object एक इमेज ट्रेस ऑब्जेक्ट चुनें @msg select an image, or pass id एक इमेज सिलेक्ट करें, या आईडी पास करें @@ -7435,7 +7576,7 @@ antiAlias Sharp शार्प @msg span must be "object" or "selection", got {v} span: स्पैन को "object" या "selection" होना चाहिए, {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 span: "selection" एक रैखिक या रेडियल ग्रेडिएंट रखता है, फ्रीफॉर्म ग्रेडिएंट नहीं +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" एक रैखिक, रेडियल, शंक्वाकार या डायमंड ग्रेडिएंट रखता है, फ्रीफॉर्म ग्रेडिएंट नहीं @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 स्प्लिट इनो ग्रिड: ग्रिड के लिए काफी बड़े पाथ सिलेक्ट करें @@ -7467,7 +7608,7 @@ antiAlias Sharp शार्प @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 textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: किसी इमेज फ़ाइल का {path} या {name, dataBase64} दें, या effect.list द्वारा दिया गया टेक्सचर दें @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} स्लाइस से अधिक बनाता है @@ -7854,7 +7995,7 @@ antiAlias Sharp शार्प @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 gradient kind `{k}` (linear, radial, conic, diamond, freeform) अज्ञात ग्रेडिएंट `{k}` (रैखिक, रेडियल, शंक्वाकार, डायमंड, फ्रीफॉर्म) @msg unknown graph type `{t}` अज्ञात ग्राफ प्रकार `{t}` @msg unknown grid colours `{name}` (one of {_1}) अज्ञात ग्रिड रंग `{name}` ({_1} में से एक) @msg unknown gridType `{t}` अज्ञात gridType `{t}` @@ -7984,7 +8125,13 @@ antiAlias Sharp शार्प @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 zipped 1-bit PSD image data with prediction can't be read भविष्यवाणी के साथ zipped 1-bit PSD इमेज डेटा पढ़ा नहीं जा सकता +@msg the PSD file's layer data uses an unknown compression ({m}) PSD फ़ाइल का लेयर डेटा एक अज्ञात संपीड़न ({m}) का उपयोग करता है +@msg the PSD file's layer records are damaged PSD फ़ाइल के लेयर रिकॉर्ड क्षतिग्रस्त हैं +@msg the PSD file's layer groups are nested too deeply PSD फ़ाइल के लेयर समूह बहुत गहराई तक नेस्ट किए गए हैं +@msg a layer of the PSD file is too large to read PSD फ़ाइल की एक लेयर पढ़ने के लिए बहुत बड़ी है +@msg the PSD file's layers take more memory to read than allowed PSD फ़ाइल की लेयर पढ़ने के लिए अनुमति से अधिक मेमोरी चाहिए +@msg the layers can't be read ({e}): the file opened as its merged image लेयर पढ़ी नहीं जा सकतीं ({e}): फ़ाइल अपनी मर्ज की गई इमेज के रूप में खुली @msg zone must be a string zone: क्षेत्र एक स्ट्रिंग होना चाहिए @msg zone must be tab, center, left, right, top or bottom zone को tab, center, left, right, top या bottom होना चाहिए @msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone: जोन को एक एंकर की आवश्यकता होती है: एंकर के साथ एक पैनल के बगल में, या साइड (स्टार्ट या एंड) के साथ एक नए डॉक कॉलम में @@ -8172,6 +8319,11 @@ swatch Yellow पीला swatch Yellow Green पीला हरा theme Appearance अपीयरेंस +# Copy Troubleshooting Info + Copy Troubleshooting Info समस्या निवारण जानकारी कॉपी करें +@msg Copied the troubleshooting info समस्या निवारण जानकारी कॉपी की गई +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report VectorCraft के पिछले सत्र ने बंद होने से पहले प्रतिक्रिया देना बंद कर दिया था। सहायता ›समस्या निवारण जानकारी कॉपी करें बग रिपोर्ट के लिए विवरण कॉपी करता है + # Safe Mode Safe Mode… सुरक्षित मोड… Safe Mode सुरक्षित मोड @@ -8192,6 +8344,8 @@ theme Appearance अपीयरेंस # Align to Pixel Grid Align to Pixel Grid पिक्सेल ग्रिड से संरेखित करें + Align New Objects to Pixel Grid नए ऑब्जेक्ट्स को पिक्सेल ग्रिड से संरेखित करें + Not Aligned to Pixel Grid पिक्सेल ग्रिड से असंरेखित @msg only paths and compound paths can be aligned to the pixel grid केवल पाथ और कंपाउंड पाथ को पिक्सेल ग्रिड से संरेखित किया जा सकता है @msg the name `{name}` isn't UTF-8 and was read as {label}: if it looks wrong, open the file with another legacyNameEncoding नाम `{name}` UTF-8 नहीं है और इसे {label} के रूप में पढ़ा गया: यदि यह गलत दिखे, तो फ़ाइल को किसी अन्य legacyNameEncoding से खोलें @msg the name `{name}` isn't UTF-8, and parts of it aren't valid {label} either: open the file with another legacyNameEncoding नाम `{name}` UTF-8 नहीं है, और इसके कुछ हिस्से {label} में भी मान्य नहीं हैं: फ़ाइल को किसी अन्य legacyNameEncoding से खोलें @@ -8246,8 +8400,33 @@ theme Appearance अपीयरेंस @plural {n} line cut|{n} lines cut {n} पंक्ति काटी गई|{n} पंक्तियाँ काटी गईं @msg `first` and `last` must be numbers of lines the console holds, first before last `first` और `last` कंसोल में रखी पंक्तियों की संख्याएँ होनी चाहिए, `first` पहले और `last` बाद में +# Learn panel + Learn सीखें + Explore tutorials ट्यूटोरियल देखें + For you आपके लिए + Skills कौशल + Get started शुरू करें + Quick skill guide त्वरित कौशल गाइड + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. आवश्यक टूल के लिए छोटे व्यावहारिक ट्यूटोरियल, कौशल के अनुसार समूहित। किसी कौशल के ट्यूटोरियल देखने के लिए उसे चुनें। + List Tutorials ट्यूटोरियल की सूची + Show Tutorial ट्यूटोरियल दिखाएँ +@msg missing `tutorial` (see learn.list) लापता `tutorial` (learn.list देखें) +@msg unknown tutorial `{id}` (see learn.list) अज्ञात ट्यूटोरियल `{id}` (learn.list देखें) + # Deferred plug-in effects Refresh Deferred Effects स्थगित इफ़ेक्ट्स रिफ्रेश करें Deferred Effects स्थगित इफ़ेक्ट्स @msg no plug-in effect is deferred कोई प्लग-इन इफ़ेक्ट स्थगित नहीं है @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. {n} प्लग-इन इफ़ेक्ट स्थगित रखकर खोला गया। इफ़ेक्ट › स्थगित इफ़ेक्ट्स रिफ्रेश करें इसे चलाता है।|{n} प्लग-इन इफ़ेक्ट्स स्थगित रखकर खोला गया। इफ़ेक्ट › स्थगित इफ़ेक्ट्स रिफ्रेश करें इन्हें चलाता है। + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools कटिंग टूल्स + Stencil Bridges… स्टेंसिल ब्रिज… + Stencil Bridges स्टेंसिल ब्रिज + Shortest Crossing सबसे छोटा क्रॉसिंग + Direction दिशा +@msg The selected art has no islands to bridge चुने गए आर्टवर्क में ब्रिज से जोड़ने के लिए कोई आइलैंड नहीं है +@msg No bridge of this width fits across the selected art इस चौड़ाई का कोई ब्रिज चुने गए आर्टवर्क के पार नहीं आता +@msg Some islands could not be joined to the area around the art कुछ आइलैंड आर्टवर्क के आसपास के क्षेत्र से नहीं जोड़े जा सके +@msg `width` must be from {lo} to {hi} pt `width` {lo} से {hi} pt तक होना चाहिए +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 से {MAX_BRIDGES_PER_ISLAND} तक पूरी संख्या होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 34b6be0ab7..73b65e1ca5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -360,6 +360,7 @@ font-technology Variable Változó Asset Export Settings Elemexportálási beállítások Assets Elemek Assign Hozzárendelés + Assign Profile Profil hozzárendelése Assign Profile… Profil hozzárendelése… Assign: Hozzárendelés: Attach to Active Plane Csatolás az aktív síkhoz @@ -901,6 +902,15 @@ font-technology Variable Változó CRLF (Windows) CRLF (Windows) Crop Körülvágás Crop Image Kép körülvágása + Image Tools Képeszközök + Remove Background… Háttér eltávolítása… + Remove Background Háttér eltávolítása + Background Háttér + Edge Color Szélszín + Picked Colors Kiválasztott színek + Corner Color Sarokszín + Contiguous Összefüggő + Each Channel Minden csatorna Edit Path Útvonal szerkesztése Crop Marks Vágójelek Crop To Körülvágás @@ -1098,6 +1108,13 @@ font-technology Variable Változó Dock Panel Panel dokkolása Dock to Top Dokkolás felülre Dock to Bottom Dokkolás alulra + Control Bar Options Vezérlősáv beállításai + Tool Options Eszközbeállítások + Object Options Objektumbeállítások + Image Options Képbeállítások + Vertical Alignment Függőleges igazítás + Align and Distribute Igazítás és elosztás + Document Options Dokumentumbeállítások Dock Control Bar Vezérlősáv dokkolása Document Dokumentum Document Color Mode Dokumentum színmódja @@ -1427,6 +1444,8 @@ font-technology Variable Változó Extrude & Bevel… Kihúzás és élletörés… 3D (Classic) 3D (klasszikus) Extrude & Bevel (Classic)… Kihúzás és élletörés (klasszikus)… + Revolve (Classic)… Forgatás tengely körül (klasszikus)… + Rotate (Classic)… Elforgatás (klasszikus)… Surface Felület Wireframe Drótváz No Shading Nincs árnyékolás @@ -1830,6 +1849,14 @@ file-filter Templates Sablonok Hand Kéz Hand Tool Kéz Hand-Drawn Kézzel rajzolt + Painted and Sketched Festett és vázlatos + Washed Blue Kimosott kék + Bristle Ochre Sörteokker + Pastel Heather Pasztell hanga + Charcoal Shade Szénárnyék + Ink Contour Tuskontúr + Wet Ink Nedves tus + Fine Pen Finom toll Handles Fogantyúk Hard Szigorú Hard Light Kemény fény @@ -2069,6 +2096,7 @@ file-filter Templates Sablonok Include Linked Files Csatolt fájlok hozzáadása Include Metadata Metaadatok hozzáadása Include non-printing layers Nem nyomtatandó rétegek hozzáadása + Write pages longer than 200 in at full size in points 200 in-nél hosszabb oldalak írása teljes méretben, pontban Include SVG Code SVG-kód hozzáadása Include Swatches for Tints Tónusok színmintáinak felvétele Include tagged source profiles Címkézett forrásprofilok beágyazása @@ -2821,6 +2849,15 @@ file-filter Templates Sablonok Open… Megnyitás… Optical Optikai Optical Margin Alignment Optikai margóigazítás + Dynamic Text Dinamikus szöveg + Dynamic Text Presets Dinamikus szöveg előbeállításai + Arch Boltív +@msg select point type or type on a path jelöljön ki pontszöveget vagy útvonalszöveget +@msg type on a path in a thread cannot use Dynamic Text: {frames} a láncolt szövegben lévő útvonalszöveg nem használhat dinamikus szöveget: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} nyitott vagy összetett útvonalon lévő útvonalszöveg nem igazítható középre felül vagy alul: {open} +@msg type on a path with no length or no height cannot be centered: {flat} a hossz vagy magasság nélküli útvonalon lévő útvonalszöveg nem igazítható középre: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} a láncolt szövegben lévő útvonalszöveg nem igazítható középre felül vagy alul: {frames} +@msg select type on a closed path jelöljön ki zárt útvonalon lévő útvonalszöveget Optimize for fast web view Optimalizálás gyors webes megtekintéshez Optimized Optimalizált Options Beállítások @@ -3072,6 +3109,7 @@ diagnostics ui felület Press keys… Nyomd le a billentyűket… Pressure Nyomás Preview Előnézet + Preview: Előnézet: Preview All Layers Összes réteg előnézetben Preview in Browser Előnézet böngészőben Preview in Browser needs the desktop app (the web downloads files instead) Az Előnézet böngészőben az asztali alkalmazásban érhető el (a webes változat helyette letölti a fájlokat) @@ -3150,7 +3188,11 @@ mark-style Japanese Japán Radial Blur Körkörös elmosás Radial Blur… Körkörös elmosás… Radial Glows Körkörös ragyogások + Organic Fades Organikus áttűnések + Holographic Holografikus Radial Gradient Körkörös színátmenet + Conic Gradient Kúpos színátmenet + Diamond Gradient Rombusz színátmenet Radial Repeat Körkörös ismétlés Radius Sugár Radius 1 Sugár 1 @@ -3166,6 +3208,8 @@ mark-style Japanese Japán Range: Tartomány: Raster Effects Raszteres effektusok Raster File Format: Raszteres fájlformátum: + Include Placed Images Elhelyezett képek hozzáadása + Include Fill Hatches Kitöltések sraffozásainak hozzáadása Raster Sample Size: Raszteres mintaméret: Raster/Vector Balance: Raszter–vektor arány: Rasterize Raszterizálás @@ -3335,6 +3379,10 @@ mark-style Japanese Japán Replace Font Betűtípus cseréje Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Cseréld le egy másik fájlra, vagy hagyd ki: a képei a dokumentummal mentett előnézetet mutatják tovább. Replace Spine Gerinc cseréje + Create Spine Gerinc létrehozása + Create Spine: Gerinc létrehozása: + Always Mindig + Never Soha Replace Symbol Szimbólum cseréje Reset Transformation Átalakítás visszaállítása Replace With Font Helyettesítő betűtípus @@ -3448,6 +3496,9 @@ mark-style Japanese Japán Roman Latin Roman Baseline Latin alapvonal Roman Hanging Punctuation Latin függő írásjelek + Korean Line Break Anywhere Koreai sortörés bárhol + East Asian Composition Settings Kelet-ázsiai szedési beállítások + Korean Composition Settings Koreai szedési beállítások Rotate Elforgatás Rotate 90° CW Forgatás 90°-kal jobbra Rotate Tool Elforgatás @@ -3778,6 +3829,15 @@ mark-style Japanese Japán Stun Pulse Kábítás Stealth Fade Lopakodás Shield Buff Pajzs + Textures Textúrák + Fine Grain Finom szemcse + Canvas Weave Vászonszövés + Burlap Sack Jutazsák + Cracked Glaze Repedezett máz + Mosaic Floor Mozaikpadló + Quilted Squares Steppelt négyzetek + Leaded Glass Ólomüveg + Damp Paper Nedves papír Shape Alakzat Shape Builder Alakzatépítő Shape Builder Regions Alakzatépítő területei @@ -3852,6 +3912,7 @@ mark-style Japanese Japán Show Modified Módosultak megjelenítése Show Note Megjegyzés megjelenítése Show Options Beállítások megjelenítése + Show Recent Colors Legutóbbi színek megjelenítése Show Original Path Eredeti útvonal megjelenítése Open this dialog with these settings next time Legközelebb ez a párbeszédablak nyíljon meg ezekkel a beállításokkal Auto-Simplify Automatikus egyszerűsítés @@ -4183,6 +4244,8 @@ mark-style Japanese Japán Scale at Center Méretezés középről Up/Down: Fel/le: Left/Right: Balra/jobbra: + Tate-chu-yoko Up/Down Tate-chu-yoko fel/le + Tate-chu-yoko Left/Right Tate-chu-yoko balra/jobbra Technical Drawing Műszaki rajz Temperature Színhőmérséklet Temperature/Tint… Színhőmérséklet/tónus… @@ -4283,6 +4346,8 @@ mark-style Japanese Japán Toolbar: Add Tool Eszköztár: eszköz hozzáadása Toolbar: Advanced / Basic Eszköztár: speciális / alap Toolbar: Remove Tool Eszköztár: eszköz eltávolítása + Add Tool… Eszköz hozzáadása… + Remove Tool Eszköz eltávolítása Toolbar: Reset Eszköztár: visszaállítás Toolbar: Single/Double Column Eszköztár: egy/két oszlop Toolbars Eszköztárak @@ -4379,6 +4444,8 @@ mark-style Japanese Japán Type on a Path Útvonalszöveg Type on a Path Options Útvonalszöveg beállításai Type on a Path Options… Útvonalszöveg beállításai… + Center on Top Középre igazítás felül + Center on Bottom Középre igazítás alul Type on a Path Tool Útvonalszöveg Type Optimized Szövegre optimalizált Type Orientation Szöveg iránya @@ -4589,6 +4656,7 @@ mark-style Japanese Japán Windows Windows Working CMYK Munka-CMYK Working CMYK (don't tag) Munka-CMYK (címke nélkül) + Working RGB (don't tag) Munka-RGB (címke nélkül) Working RGB Munka-RGB Workspace Munkaterület Workspace {i} Munkaterület {i} @@ -4705,10 +4773,13 @@ imageTrace Outline Körvonal @msg `colors` must be an array of colors, not {v} `colors`: színek tömbje kell, ez nem az: {v} @msg `library` is a library id or name (see {list}) a `library` könyvtárazonosító vagy -név lehet (lásd: {list}) @msg `mode` applies to freeform gradients a `mode` a szabad formájú színátmenetekre vonatkozik +@msg a negative `aspect` applies to conic gradients a negatív `aspect` a kúpos színátmenetekre vonatkozik +@msg `focal` applies to radial gradients a `focal` a sugaras színátmenetekre vonatkozik @msg `preserve` must be an object `preserve`: objektum kell @msg `globalAdjust` must be an object `globalAdjust`: objektum kell @msg `sampleSize` must be 1, 3 or 5 `sampleSize`: 1, 3 vagy 5 kell @msg `stops` must be an array `stops`: tömb kell +@msg `{key}` must be an array `{key}`: tömb kell @msg `svg` must be an object of SVG options (see document.formats) `svg`: SVG-beállításokat tartalmazó objektum kell (lásd: document.formats) @msg `to` must be "corner" or "smooth" `to`: "corner" vagy "smooth" kell @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference`: "emBox", "capHeight", "xHeight" vagy "icfBox" kell @@ -4724,6 +4795,7 @@ imageTrace Outline Körvonal @msg `{key}` must be a number, not {v} `{key}`: szám kell, ez nem az: {v} @msg {key} must be Unix seconds (an integer) or null {key}: Unix-idő kell másodpercben (egész szám) vagy null @msg `{key}` must be a string `{key}`: szöveg kell +@msg `{key}` must be a profile name or null `{key}`: profilnév vagy null kell @msg `{key}` must be a whole number `{key}`: egész szám kell @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}`: {min} és {max} közötti egész szám kell (kapott érték: {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}`: {min} és {max} közötti érték kell (kapott érték: {x}) @@ -5005,6 +5077,7 @@ imageTrace Outline Körvonal @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller a(z) {n}. rajztábla oldala {size}, hosszabb a PDF 14 400 pt-os (200 in) oldalkorlátjánál: {unit} UserUnit értékkel íródik, így a UserUnit-ot figyelmen kívül hagyó alkalmazások ennyiszer kisebbnek mutatják @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in a(z) {n}. rajztábla oldala {size}, hosszabb a PDF 14 400 pt-os (200 in) oldalkorlátjánál: a(z) {label} oldalak UserUnit nélkül, pontokban íródnak, és a korlátot betartó alkalmazások 200 in-re vágják az oldalt @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 a PDF 1.5-ben nincs UserUnit, amelyre egy 14 400 pt-nál (200 in) hosszabb oldalnak szüksége van a mérete megtartásához: a fájl PDF 1.6-ként íródik +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 a PDF 1.4-ben nincs UserUnit, amelyre egy 14 400 pt-nál (200 in) hosszabb oldalnak szüksége van, hogy a PDF/A-2 14 400 egységes oldalkorlátján belül maradjon: a fájl PDF 1.6-ként íródik @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units a(z) {n}. rajztábla oldala {size}, túl hosszú és keskeny a PDF 3 és 14 400 egység közötti oldalaihoz: {unit} UserUnit értékkel íródik, amely a rövid oldalt legalább 3 egységen tartja, és a korlátot betartó alkalmazások a hosszú oldalt 14 400 egységre vágják @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard a(z) {label} fájlok legfeljebb {max} értékű valós számokat tárolnak, a(z) {n}. rajztábla {side} pt hosszú oldalához pedig nagyobbak kellenek: válassza a PDF 1.6-os vagy újabb verziót PDF/X szabvány nélkül, vagy egy kisebb rajztáblát @msg invalid restored panel group érvénytelen visszaállított panelcsoport @@ -5199,6 +5272,8 @@ imageTrace Outline Körvonal @msg not a VectorCraft shortcut set (missing `overrides`) nem VectorCraft-billentyűparancskészlet (hiányzik: `overrides`) @msg not a blend nem összemosás @msg not an EMF or WMF file nem EMF- vagy WMF-fájl +@msg not an HP-GL file nem HP-GL-fájl +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens`: 1–255 #rrggbb szín tömbje kell @msg not found nem található @msg not in pattern editing mode nem mintázatszerkesztő módban vagy @msg finish editing the pattern first előbb fejezd be a mintázat szerkesztését @@ -5222,6 +5297,8 @@ imageTrace Outline Körvonal @msg invalid object id {value}: expected a non-negative integer érvénytelen objektumazonosító: {value} (nemnegatív egész szám kell) @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}` {index} indexű eleme {value}, nem objektumazonosító (nemnegatív egész szám kell) @msg no such object id {value} nincs ilyen objektumazonosító: {value} +@msg id {value} is a ruler guide, not an object ez az azonosító segédvonalé, nem objektumé: {value} +@msg a ruler guide goes only directly in a layer or sublayer segédvonal csak közvetlenül rétegben vagy alrétegben lehet @msg id {value} is a layer, not an object a(z) {value} azonosító egy réteg, nem objektum @msg id {value} is a layer, not an object; move layers with layer.move a(z) {value} azonosító egy réteg, nem objektum; a rétegeket a layer.move paranccsal helyezheti át @msg object {0} cannot have children ennek az objektumnak nem lehetnek gyermekei: {0} @@ -5342,6 +5419,14 @@ imageTrace Outline Körvonal @msg a symbol can't hold an instance of itself egy szimbólum nem tartalmazhatja a saját példányát @msg select an envelope jelölj ki egy burkolót @msg select an image jelölj ki egy képet +@msg `background` must be edges, corners or colors a `background` értéke edges, corners vagy colors lehet +@msg `match` must be distance or channels a `match` értéke distance vagy channels lehet +@msg `{key}` must be from 0 to 100 a `{key}` értéke 0 és 100 között lehet +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue a `colors` 1–16 színt sorolhat fel, mindegyiket hexadecimálisan (#rrggbb vagy #rgb) vagy black, white, red, green vagy blue alakban +@msg the linked image shows its preview: embed or relink it first a csatolt kép az előnézetét mutatja: előbb ágyazd be vagy csatold újra +@msg a CMYK image has no transparency to set a CMYK képnek nincs beállítható átlátszósága +@msg every pixel matches the background: no image would be left minden képpont egyezik a háttérrel: nem maradna kép +@msg an image of {w} × {h} pixels is too large to change egy {w} × {h} pixeles kép túl nagy a módosításhoz @msg select an Image Trace object jelölj ki egy képvektorizálási objektumot @msg select an object in perspective jelölj ki egy perspektivikus objektumot @msg select artwork (or a colour group) to recolor jelölj ki átszínezendő grafikát (vagy színcsoportot) @@ -5510,7 +5595,7 @@ imageTrace Outline Körvonal @msg unknown format ismeretlen formátum @msg unknown format `{f}` (Save writes {_1}) ismeretlen formátum: `{f}` (a Mentés ezeket írja: {_1}) @msg unknown freeform mode `{m}` (points, lines) ismeretlen szabad formájú mód: `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) ismeretlen színátmenet-fajta: `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) ismeretlen színátmenet-fajta: `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` ismeretlen kiemelés: `{h}` @msg unknown option `{path}.{k}` ismeretlen beállítás: `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ismeretlen felülnyomás-kezelés: `{o}` (preserve, simulate vagy discard) @@ -5561,7 +5646,13 @@ imageTrace Outline Körvonal @msg x and y must be provided together az x és az y csak együtt adható meg @msg x and y must both be numbers az x és az y is szám kell legyen @msg Your unsaved changes are kept in this browser: reload the page to get them back. A nem mentett módosításaidat ez a böngésző megőrizte: töltsd újra az oldalt a visszakapásukhoz. -@msg zipped 32-bit PSD image data with prediction can't be read a predikcióval tömörített 32 bites PSD-képadatok nem olvashatók +@msg zipped 1-bit PSD image data with prediction can't be read a predikcióval tömörített 1 bites PSD-képadatok nem olvashatók +@msg the PSD file's layer data uses an unknown compression ({m}) a PSD-fájl rétegadatai ismeretlen tömörítést használnak ({m}) +@msg the PSD file's layer records are damaged a PSD-fájl rétegrekordjai sérültek +@msg the PSD file's layer groups are nested too deeply a PSD-fájl rétegcsoportjai túl mélyen vannak egymásba ágyazva +@msg a layer of the PSD file is too large to read a PSD-fájl egyik rétege túl nagy a beolvasáshoz +@msg the PSD file's layers take more memory to read than allowed a PSD-fájl rétegeinek beolvasása több memóriát igényel a megengedettnél +@msg the layers can't be read ({e}): the file opened as its merged image a rétegek nem olvashatók ({e}): a fájl az egyesített képeként nyílt meg @msg zone must be a string a zone értéke szöveg lehet @msg zone must be tab, center, left, right, top or bottom a zone értéke tab, center, left, right, top vagy bottom lehet @msg {_1} failed: {e} sikertelen: {_1}: {e} @@ -5687,6 +5778,11 @@ imageTrace Outline Körvonal Softness Lágyság Ambient Light Környezeti fény Light behind the object Fény az objektum mögött + Shadows Árnyékok + Distance from Object Távolság az objektumtól + Shadow Bounds Árnyék határai + Behind Object Az objektum mögött + Below Object Az objektum alatt 3D Lighting Preset 3D világítási készlet Standard Normál Diffuse Szórt @@ -5751,7 +5847,7 @@ imageTrace Outline Körvonal @msg span must be "object" or "selection", got {v} a span értéke "object" vagy "selection" lehet, nem {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" egy `gradient` értéket helyez el, nem színmintát @msg span: "selection" places a gradient: give `gradient` span: "selection" színátmenetet helyez el: adja meg a `gradient` értéket -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" lineáris vagy sugaras színátmenetet helyez el, nem szabad formájút +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" lineáris, sugaras, kúpos vagy rombusz színátmenetet helyez el, nem szabad formájút @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" magát a színátmenetet helyezi el: hagyja el a `start` és `end` értéket (ezek már a dokumentum koordinátáiban helyezik el) Make Image Dynamic Kép dinamikussá tétele Import Data Sets… Adatkészletek importálása… @@ -5934,6 +6030,7 @@ imageTrace Outline Körvonal Ruby Ruby Geometric Guides Geometriai segédvonalak Geometric Patterns Geometriai mintázatok + Grit Textures Szemcsés textúrák Ease In Lassú kezdés Ease Out Lassú befejezés Ease In Out Lassú kezdés és befejezés @@ -5992,6 +6089,8 @@ axis Y Axis Y tengely Version: {version} Verzió: {version} Install “{name}” in place of the plug-in with the same ID? Telepíted a(z) „{name}” bővítményt az azonos azonosítójú bővítmény helyére? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ez a fájl nem az a bővítmény, amely korábban ezzel az azonosítóval volt telepítve. Megkapja az ehhez az azonosítóhoz tárolt beállításokat és gyorsítótárat. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Egy automatizálás kérte ennek a bővítménynek a telepítését. A telepítéshez válaszd ki te magad az Objektum › Bővítmények › Bővítmény telepítése… parancsot. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Egy automatizálás kérte ennek a bővítménynek a telepítését. A telepítéshez válaszd ki te magad az Objektum › Bővítmények › Bővítmény telepítése… parancsot. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees a(z) „{name}” más modul, mint a(z) {_1} azonosítójú bővítmény, és megkapná az ahhoz tárolt beállításokat és gyorsítótárat: telepítsd a `replace: true` megadásával, miután a felhasználó beleegyezett File SHA-256: {hash} A fájl SHA-256 értéke: {hash} Read the objects it is given Olvashatja a kapott objektumokat @@ -6037,6 +6136,11 @@ axis Y Axis Y tengely @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges @msg memory budget (object {_1} needs {size} bytes of input, {left} left) memóriakeret (a(z) {_1} objektumnak {size} bájt bemenet kell, {left} maradt) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektumkeret (több mint {MAX_OBJECTS} csak olvasható objektum) +@msg instruction budget utasításkeret +@msg time budget időkeret +@msg memory budget (the selection is too large to hand over) memóriakeret (a kijelölés túl nagy az átadáshoz) +@msg output size ({what} is {len} bytes, limit {max}) kimenet mérete ({what}: {len} bájt, korlát {max}) +@msg the plug-in's grant can't be removed from the plug-in store a bővítmény engedélye nem távolítható el a bővítménytárból @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a(z) `{shown}` engedély egy későbbi bővítmény-API számára van fenntartva; ez a gazdaprogram nem adja meg @msg unknown permission `{shown}` ismeretlen engedély: `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants a(z) „{name}” a következő engedélyeket kéri: {asked}; egy személynek jóvá kell hagynia őket az asztali alkalmazásban, vagy add meg a `grant` értéket egy --allow-plugin-grants kapcsolóval indított munkamenetben @@ -6049,6 +6153,12 @@ axis Y Axis Y tengely @msg command {name}: `label` must be 1-64 printable characters {name} parancs: a `label` 1-64 nyomtatható karakter legyen @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} parancs: használj 1-{MAX_COMMAND_ID} karakteres, a-z 0-9 _ karakterekből álló, betűvel kezdődő azonosítót @msg command {name}: {e} {name} parancs: {e} +@msg manifest: {e} leíró: {e} +@msg manifest: {e} at line {line} column {column} leíró: {e} ({line}. sor, {column}. oszlop) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands`: parancsok listája kell, mindegyikben `id` és `label` értékkel +@msg command {name} must be an object with an `id` and a `label` a(z) {name} parancs csak `id` és `label` mezőt tartalmazó objektum lehet +@msg missing field `{key}` hiányzó mező: `{key}` +@msg duplicate field `{key}` ismétlődő mező: `{key}` @msg only a filter or a live effect declares `commands` `commands` értéket csak szűrő vagy élő effektus deklarálhat @msg “{name}” › {label}: {e} „{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed a modul SHA-256 értéke nem az, amit a `hash` megad: semmi sem lett telepítve @@ -6073,6 +6183,16 @@ axis Y Axis Y tengely @msg message must be text message: szöveg kell @msg allowContinue must be true or false allowContinue: true vagy false kell @msg Batch cannot play an action with a stop A kötegelt feldolgozás nem játszhat le megállást tartalmazó műveletet + Insert Menu Item… Menüelem beszúrása… + Insert Menu Item Menüelem beszúrása + Menu Item: Menüelem: + No menu item matches. Egy menüelem sem egyezik. + Several menu items match. Choose one from the list. Több menüelem is egyezik. Válasszon egyet a listából. + Items that open a dialog, and File, Window and Help menu items, are not listed. A párbeszédablakot megnyitó elemek, valamint a Fájl, az Ablak és a Súgó menü elemei nem szerepelnek a listában. +@msg command must be text command: szöveg kell +@msg no menu item that can be inserted runs this command egyetlen beszúrható menüelem sem futtatja ezt a parancsot +@msg the action already has 10,000 steps a műveletnek már 10 000 lépése van +@msg the action set would be larger than 8 MiB a műveletkészlet nagyobb lenne 8 MiB-nál Playback Options Lejátszási beállítások Accelerated Gyorsított Step by Step Lépésenként @@ -6111,6 +6231,12 @@ axis Y Axis Y tengely Crosshair Célkereszt Checkpoint Ellenőrzőpont Inventory Icons Leltári ikonok + Skill Icons Képességikonok + Attack Támadás + Defend Védelem + Heal Gyógyítás + Buff Erősítés + Ult Ult Sword Kard Shield Pajzs Potion Bájital @@ -6175,7 +6301,23 @@ axis Y Axis Y tengely Dash Trail Szaggatott nyom Speed Line Sebességvonal Game Trails Játéknyomok + Energy Beams Energianyalábok + Laser Bolt Lézervillám + Plasma Arc Plazmaív + Charge Wave Töltéshullám + Spark Trail Szikracsík Calligraphic Nibs Kalligrafikus tollhegyek + Bristle Brushes Sörteecsetek + Fine Liner Finom kontúr + Pointed Flat Hegyes lapos + Stubby Round Rövid kerek + Dry Scrub Száraz dörzsölés + Soft Dome Lágy kupola + Filbert Macskanyelv + Angled Round Ferde kerek + Angled Flat Ferde lapos + Fan Blender Elmosó legyező + Grass Fan Fűlegyező Pattern Borders Mintázatszegélyek Scatter Shapes Szórt alakzatok Save Brush Library… Ecsetkönyvtár mentése… @@ -6373,9 +6515,12 @@ anchor Points: Pontok: @msg {label} must be a number {label}: szám kell @msg {label} must be a number of at least 0.1 {label} legalább 0,1 értékű szám kell legyen Advanced Character Formats Speciális karakterformátumok + Basic Paragraph Formats Alapvető bekezdésformátumok + Composition Szedés Horizontal Scale Vízszintes méretezés Vertical Scale Függőleges méretezés @msg {label} must be a number from {min} to {max} {label} {min} és {max} közötti szám kell legyen +@msg {label} must be a whole number from {min} to {max} {label} {min} és {max} közötti egész szám kell legyen Character Color Karakterszín OpenType Features OpenType-funkciók Stylistic Sets Stíluskészletek @@ -6383,6 +6528,10 @@ anchor Points: Pontok: @msg features lists at most {max} tags a features legfeljebb {max} címkét tartalmazhat @msg unknown OpenType feature `{t}` ismeretlen OpenType-funkció: `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0-nál nagyobb és legfeljebb {max} értékű szám kell legyen +@msg {label} must be at most {max} characters {label} legfeljebb {max} karakter lehet +@msg {label} must be one character {label} pontosan egy karakter kell legyen +@msg at most {max} tab stops legfeljebb {max} tabulátor +@msg unknown align `{other}` ismeretlen igazítás: `{other}` @msg no character style `{name}` A(z) `{name}` karakterstílus nem található # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6544,6 +6693,12 @@ breakText Glyphs Glifák Delete the selected brushes? Törlöd a kijelölt ecseteket? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Körvonalak használnak egyet vagy többet ezek közül az ecsetek közül. Leveszed az ecseteket ezekről a körvonalakról, és törlöd az ecseteket? Remove Strokes Körvonalak eltávolítása + Place Brush Art Ecsetgrafika elhelyezése + Replace Brush Art Ecsetgrafika cseréje + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Körvonalak használják ezt az ecsetet. Alkalmazod az új grafikát ezekre a körvonalakra, vagy változatlanul hagyod őket, és hozzáadod az ecset egy másolatát az új grafikával? + Apply to Strokes Alkalmazás a körvonalakra + Leave Strokes Körvonalak megtartása +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` ecsetnek nincs grafikája (csak a szóró-, a grafikus és a mintázatecseteknek van) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Elrendezőeszközök Arrange in Grid… Elrendezés rácsba… @@ -6739,6 +6894,11 @@ breakText Glyphs Glifák @msg only an exporter or an importer declares `extensions` csak exportáló vagy importáló bővítmény adhat meg `extensions` értéket @msg an importer always gets an import's budget: leave `budget` out az importáló bővítmény mindig egy importálás keretét kapja: hagyja el a `budget` kulcsot +# Copy Troubleshooting Info + Copy Troubleshooting Info Hibaelhárítási adatok másolása +@msg Copied the troubleshooting info Hibaelhárítási adatok másolva +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report A VectorCraft legutóbbi munkamenete nem válaszolt, mielőtt bezárult. A Súgó › Hibaelhárítási adatok másolása kimásolja a részleteket egy hibajelentéshez + # Safe Mode Safe Mode… Csökkentett mód… Safe Mode Csökkentett mód @@ -6759,6 +6919,8 @@ breakText Glyphs Glifák # Align to Pixel Grid Align to Pixel Grid Igazítás a pixelrácshoz + Align New Objects to Pixel Grid Új objektumok igazítása a pixelrácshoz + Not Aligned to Pixel Grid Pixelrácshoz nem igazított @msg only paths and compound paths can be aligned to the pixel grid csak útvonalak és összetett útvonalak igazíthatók a pixelrácshoz @msg side is left or right, not `{s}` a side értéke left vagy right lehet, nem `{s}` Ignore All Az összes kihagyása @@ -6789,8 +6951,33 @@ breakText Glyphs Glifák @plural {n} line cut|{n} lines cut {n} sor levágva @msg `first` and `last` must be numbers of lines the console holds, first before last A `first` és a `last` a konzolban tárolt sorok számai legyenek, a `first` a `last` előtt +# Learn panel + Learn Tanulás + Explore tutorials Oktatóanyagok felfedezése + For you Önnek + Skills Készségek + Get started Első lépések + Quick skill guide Gyors készségkalauz + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Rövid gyakorlati oktatóanyagok az alapvető eszközökhöz, készségek szerint csoportosítva. Válasszon egy készséget az oktatóanyagai megtekintéséhez. + List Tutorials Oktatóanyagok listázása + Show Tutorial Oktatóanyag megjelenítése +@msg missing `tutorial` (see learn.list) hiányzik: `tutorial` (lásd: learn.list) +@msg unknown tutorial `{id}` (see learn.list) ismeretlen oktatóanyag: `{id}` (lásd: learn.list) + # Deferred plug-in effects Refresh Deferred Effects Elhalasztott effektusok frissítése Deferred Effects Elhalasztott effektusok @msg no plug-in effect is deferred nincs elhalasztott bővítményeffektus @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Megnyitva, elhalasztott bővítményeffektusok: {n}. Az Effektus › Elhalasztott effektusok frissítése futtatja őket. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Vágóeszközök + Stencil Bridges… Sablonhidak… + Stencil Bridges Sablonhidak + Shortest Crossing Legrövidebb átkelés + Direction Irány +@msg The selected art has no islands to bridge A kijelölt grafikán nincsenek összekötendő szigetek +@msg No bridge of this width fits across the selected art Ilyen széles híd nem fér el a kijelölt grafikán +@msg Some islands could not be joined to the area around the art Egyes szigeteket nem sikerült összekötni a grafikát körülvevő területtel +@msg `width` must be from {lo} to {hi} pt A `width` értéke {lo} és {hi} pt között lehet +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`: 1 és {MAX_BRIDGES_PER_ISLAND} közötti egész szám kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 16854b5bb7..59761c7fcf 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -106,6 +106,7 @@ PDF Presets… Preset PDF… Perspective Grid Presets… Preset kisi perspektif… Color Settings… Pengaturan warna… + Assign Profile Tetapkan profil Assign Profile… Tetapkan profil… Keyboard Shortcuts… Pintasan papan tik… Import Shortcut Set Impor set pintasan @@ -189,6 +190,15 @@ Expand… Perluas… Expand Appearance Perluas tampilan Crop Image Pangkas gambar + Image Tools Alat Gambar + Remove Background… Hapus latar belakang… + Remove Background Hapus latar belakang + Background Latar belakang + Edge Color Warna tepi + Picked Colors Warna pilihan + Corner Color Warna sudut + Contiguous Bersambung + Each Channel Setiap kanal Edit Path Edit jalur Mask Masker Rasterize… Rasterisasi… @@ -238,6 +248,10 @@ Blend Options… Opsi blend… Expand Perluas Replace Spine Ganti spine + Create Spine Buat spine + Create Spine: Buat spine: + Always Selalu + Never Tidak pernah Reverse Spine Balikkan spine Reverse Front to Back Balikkan depan ke belakang Envelope Distort Distorsi amplop @@ -352,6 +366,8 @@ Stair Step Undakan tangga Gravity Gravitasi Type on a Path Options… Opsi teks pada jalur… + Center on Top Pusatkan di atas + Center on Bottom Pusatkan di bawah Threaded Text Teks beruntun Create Buat Release Selection Lepaskan seleksi @@ -367,6 +383,9 @@ Smart Punctuation… Tanda baca cerdas… Create Outlines Buat garis luar Optical Margin Alignment Perataan margin optik + Dynamic Text Teks dinamis + Dynamic Text Presets Preset teks dinamis + Arch Pelengkung Fill with Placeholder Text Isi dengan teks placeholder Insert Inline Symbol Sisipkan simbol sebaris Show Hidden Characters Tampilkan karakter tersembunyi @@ -437,6 +456,8 @@ Extrude & Bevel… Ekstrusi & bevel… 3D (Classic) 3D (klasik) Extrude & Bevel (Classic)… Ekstrusi & bevel (klasik)… + Revolve (Classic)… Revolusi (klasik)… + Rotate (Classic)… Putar (klasik)… Surface Permukaan Wireframe Kerangka kawat No Shading Tanpa pengarsiran @@ -507,6 +528,7 @@ Gaussian Blur… Kabur Gaussian… View Tampilan Preview Pratinjau + Preview: Pratinjau: Overprint Preview Pratinjau overprint Pixel Preview Pratinjau piksel Trim View Tampilan terpangkas @@ -729,8 +751,25 @@ Stun Pulse Pingsan Stealth Fade Menghilang Shield Buff Perisai + Textures Tekstur + Fine Grain Butiran Halus + Canvas Weave Anyaman Kanvas + Burlap Sack Karung Goni + Cracked Glaze Glasir Retak + Mosaic Floor Lantai Mosaik + Quilted Squares Kotak Quilt + Leaded Glass Kaca Patri + Damp Paper Kertas Basah Outlines and Rules Garis luar dan garis Hand-Drawn Gambar tangan + Painted and Sketched Lukisan dan sketsa + Washed Blue Biru luntur + Bristle Ochre Oker kuas kering + Pastel Heather Ungu pastel + Charcoal Shade Bayangan arang + Ink Contour Kontur tinta + Wet Ink Tinta basah + Fine Pen Pena halus Gradient Finishes Finishing gradien Shape Effects Efek bentuk Blends and Transparency Blend dan transparansi @@ -750,6 +789,8 @@ Spectrum Gradients Gradien spektrum Sky Gradients Gradien langit Neutral Gradients Gradien netral + Organic Fades Pudar organik + Holographic Holografik Duotone Gradients Gradien duotone Radial Glows Pendar radial Save Swatch Library… Simpan pustaka sampel warna… @@ -808,6 +849,13 @@ Dock Panel Tambatkan panel Dock to Top Tambatkan ke atas Dock to Bottom Tambatkan ke bawah + Control Bar Options Opsi bilah kontrol + Tool Options Opsi alat + Object Options Opsi objek + Image Options Opsi gambar + Vertical Alignment Perataan vertikal + Align and Distribute Sejajarkan dan distribusikan + Document Options Opsi dokumen Dock Control Bar Tambatkan bilah kontrol Float Tool Group Mengambangkan grup alat Services Layanan @@ -1082,6 +1130,8 @@ lighting Light Cahaya Toolbar: Single/Double Column Bilah alat: kolom tunggal/ganda Toolbar: Add Tool Bilah alat: tambahkan alat Toolbar: Remove Tool Bilah alat: hapus alat + Add Tool… Tambahkan alat… + Remove Tool Hapus alat Toolbar: Reset Bilah alat: setel ulang Two Point Perspective Preset 1 Preset perspektif dua titik 1 Two Point Perspective Preset 2 Preset perspektif dua titik 2 @@ -1461,6 +1511,7 @@ digits Malayalam Malayalam Roman Baseline Baseline Romawi Select a text object to edit its character attributes. Pilih objek teks untuk mengedit atribut karakternya. Show Options Tampilkan opsi + Show Recent Colors Tampilkan warna terbaru Small Caps Kapital kecil Small Caps (on the roadmap) Kapital kecil (masih dalam roadmap) Standard Vertical Roman Alignment Perataan Romawi vertikal standar @@ -1488,6 +1539,8 @@ digits Malayalam Malayalam Scale at Center Skalakan dari tengah Up/Down: Atas/bawah: Left/Right: Kiri/kanan: + Tate-chu-yoko Up/Down Tate-chu-yoko atas/bawah + Tate-chu-yoko Left/Right Tate-chu-yoko kiri/kanan Underline Garis bawah Vertical Scale % Skala vertikal % Axis Sumbu @@ -1590,6 +1643,8 @@ digits Malayalam Malayalam No gradient swatches Tidak ada swatch gradien Points: clicks add free points Titik: klik menambahkan titik bebas Radial Gradient Gradien radial + Conic Gradient Gradien kerucut + Diamond Gradient Gradien wajik Reset to White, Black Setel ulang ke putih, hitam Reverse Gradient Balikkan gradien Save to Swatches Simpan ke swatch @@ -1770,6 +1825,9 @@ digits Malayalam Malayalam Right Indent Indentasi kanan Right-to-Left Paragraph Direction Arah paragraf kanan ke kiri Roman Hanging Punctuation Tanda baca gantung Romawi + Korean Line Break Anywhere Putus baris Korea di mana saja + East Asian Composition Settings Pengaturan komposisi Asia Timur + Korean Composition Settings Pengaturan komposisi Korea Select a text object to edit its paragraph attributes. Pilih objek teks untuk mengedit atribut paragrafnya. Single-line Composer Komposer satu baris Toggle Line Composer Alihkan komposer baris @@ -1856,6 +1914,7 @@ digits Malayalam Malayalam Simulate Paper Simulasikan kertas Use Black Point Compensation Gunakan kompensasi titik hitam Working CMYK (don't tag) CMYK kerja (tanpa tag) + Working RGB (don't tag) RGB kerja (tanpa tag) {name} (spot) {name} (spot) Add to Profiles… Tambahkan ke profil… Align Stroke to Center Ratakan stroke ke tengah @@ -2155,6 +2214,8 @@ digits Malayalam Malayalam Export Selected Art Only Ekspor hanya karya seni terpilih Number of Colors: Jumlah warna: Raster File Format: Format file raster: + Include Placed Images Sertakan gambar yang ditempatkan + Include Fill Hatches Sertakan arsiran isian True colour needs version 2004 or later: the nearest of 256 colours is written. Warna sejati memerlukan versi 2004 atau lebih baru: yang ditulis adalah warna terdekat dari 256 warna. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Teks menjadi garis luar, dan stroke yang tidak dapat digambar oleh garis CAD menjadi bentuk terisi. Type stays text, and every stroke is a line with its lineweight and dashes. Teks tetap berupa teks, dan setiap stroke menjadi garis dengan ketebalan dan pola putus-putusnya. @@ -2698,6 +2759,7 @@ antiAlias Sharp Tajam General › Thumbnails Umum › Miniatur Grayscale images Gambar skala abu-abu Include non-printing layers Sertakan lapisan non-cetak + Write pages longer than 200 in at full size in points Tulis halaman yang lebih panjang dari 200 in dalam ukuran penuh, dalam poin Left: Kiri: Mark as trapped Tandai sebagai ter-trap Marks and Bleeds Tanda dan bleed @@ -4183,6 +4245,8 @@ imageTrace Outline Kontur @msg `gradient` must be an object `gradient` harus berupa objek @msg `library` is a library id or name (see {list}) `library` adalah id atau nama pustaka (lihat {list}) @msg `mode` applies to freeform gradients `mode` berlaku untuk gradien bentuk bebas +@msg a negative `aspect` applies to conic gradients `aspect` negatif berlaku untuk gradien kerucut +@msg `focal` applies to radial gradients `focal` berlaku untuk gradien radial @msg `sampleSize` must be 1, 3 or 5 `sampleSize` harus 1, 3, atau 5 @msg `stops` must be an array `stops` harus berupa larik @msg `svg` must be an object of SVG options (see document.formats) `svg` harus berupa objek opsi SVG (lihat document.formats) @@ -4451,6 +4515,8 @@ imageTrace Outline Kontur @msg not a stored central record bukan rekaman pusat yang tersimpan @msg not a valid plug-in module: {0} bukan modul plug-in yang valid: {0} @msg not an EMF or WMF file bukan berkas EMF atau WMF +@msg not an HP-GL file bukan berkas HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` harus berupa array berisi 1 sampai 255 warna #rrggbb @msg not found tidak ditemukan @msg not in pattern editing mode tidak dalam mode pengeditan pola @msg finish editing the pattern first selesaikan pengeditan pola terlebih dahulu @@ -4618,7 +4684,7 @@ imageTrace Outline Kontur @msg unknown format format tidak dikenal @msg unknown format `{f}` (Save writes {_1}) format `{f}` tidak dikenal (Simpan menulis {_1}) @msg unknown freeform mode `{m}` (points, lines) mode bentuk bebas `{m}` tidak dikenal (titik, garis) -@msg unknown gradient kind `{k}` (linear, radial, freeform) jenis gradien `{k}` tidak dikenal (linear, radial, bentuk bebas) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) jenis gradien `{k}` tidak dikenal (linear, radial, kerucut, wajik, bentuk bebas) @msg unknown highlight `{h}` sorotan `{h}` tidak dikenal @msg unknown option `{path}.{k}` opsi `{path}.{k}` tidak dikenal @msg unknown overprints `{o}` (preserve, simulate or discard) overprint `{o}` tidak dikenal (pertahankan, simulasikan, atau buang) @@ -4802,6 +4868,8 @@ imageTrace Outline Kontur @msg invalid object id {value}: expected a non-negative integer id objek {value} tidak valid: harus berupa bilangan bulat non-negatif @msg `{key}` entry {index} is {value}, not a non-negative integer object id entri {index} dari `{key}` adalah {value}, bukan id objek (bilangan bulat non-negatif) @msg no such object id {value} tidak ada objek dengan id {value} +@msg id {value} is a ruler guide, not an object id {value} adalah panduan, bukan objek +@msg a ruler guide goes only directly in a layer or sublayer panduan hanya dapat berada langsung di lapisan atau sublapisan @msg automation filesystem access is not granted: read authority is absent: {path} akses sistem berkas otomatisasi tidak diberikan: otoritas baca tidak ada: {path} @msg automation filesystem access is not granted: write authority is absent: {path} akses sistem berkas otomatisasi tidak diberikan: otoritas tulis tidak ada: {path} @msg automation path rejected: outside the read root {root}: {path} jalur otomatisasi ditolak: di luar akar baca {root}: {path} @@ -4818,7 +4886,13 @@ imageTrace Outline Kontur @msg the PSD file has an unknown colour mode ({m}) berkas PSD memiliki mode warna yang tidak dikenal ({m}) @msg the PSD file's image data uses an unknown compression ({m}) data gambar berkas PSD menggunakan kompresi yang tidak dikenal ({m}) @msg the PSD image is too large to read ({_1} × {_2} pixels) gambar PSD terlalu besar untuk dibaca ({_1} × {_2} piksel) -@msg zipped 32-bit PSD image data with prediction can't be read data gambar PSD 32-bit terkompresi zip dengan prediksi tidak dapat dibaca +@msg zipped 1-bit PSD image data with prediction can't be read data gambar PSD 1-bit terkompresi zip dengan prediksi tidak dapat dibaca +@msg the PSD file's layer data uses an unknown compression ({m}) data lapisan berkas PSD menggunakan kompresi yang tidak dikenal ({m}) +@msg the PSD file's layer records are damaged catatan lapisan berkas PSD rusak +@msg the PSD file's layer groups are nested too deeply grup lapisan berkas PSD bersarang terlalu dalam +@msg a layer of the PSD file is too large to read sebuah lapisan berkas PSD terlalu besar untuk dibaca +@msg the PSD file's layers take more memory to read than allowed lapisan berkas PSD memerlukan lebih banyak memori untuk dibaca daripada yang diizinkan +@msg the layers can't be read ({e}): the file opened as its merged image lapisan tidak dapat dibaca ({e}): berkas dibuka sebagai gambar gabungannya @msg {depth}-bit PSD files in this colour mode can't be read berkas PSD {depth}-bit dalam mode warna ini tidak dapat dibaca @msg the PSD file is cut short berkas PSD terpotong @msg the PSD file's header is damaged header berkas PSD rusak @@ -5226,6 +5300,11 @@ mark-style Japanese Jepang Softness Kelembutan Ambient Light Cahaya ambient Light behind the object Cahaya di belakang objek + Shadows Bayangan + Distance from Object Jarak dari objek + Shadow Bounds Batas bayangan + Behind Object Di belakang objek + Below Object Di bawah objek 3D Lighting Preset Preset Pencahayaan 3D Standard Standar Diffuse Difus @@ -5369,7 +5448,7 @@ mark-style Japanese Jepang @msg span must be "object" or "selection", got {v} span harus "object" atau "selection", diterima {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" menempatkan `gradient`, bukan swatch @msg span: "selection" places a gradient: give `gradient` span: "selection" menempatkan gradien: berikan `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" menempatkan gradien linear atau radial, bukan gradien bebas +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" menempatkan gradien linear, radial, kerucut, atau wajik, bukan gradien bebas @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" menempatkan gradien itu sendiri: jangan sertakan `start` dan `end` (keduanya sudah menempatkannya dalam koordinat dokumen) Make Image Dynamic Jadikan gambar dinamis Import Data Sets… Impor himpunan data… @@ -5797,6 +5876,7 @@ swatch Bright Violet Violet cerah Ruby Ruby Geometric Guides Panduan Geometris Geometric Patterns Pola Geometris + Grit Textures Tekstur Butiran Ease In Awal Lambat Ease Out Akhir Lambat Ease In Out Awal dan Akhir Lambat @@ -5850,6 +5930,7 @@ axis Y Axis Sumbu Y Version: {version} Versi: {version} Install “{name}” in place of the plug-in with the same ID? Instal “{name}” sebagai pengganti plug-in dengan ID yang sama? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. File ini bukan plug-in yang sebelumnya diinstal dengan ID ini. File ini mendapatkan pengaturan dan cache yang disimpan untuk ID tersebut. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Otomatisasi meminta untuk menginstal plug-in ini. Untuk menginstalnya, pilih Objek › Plug-in › Instal plug-in… sendiri. File SHA-256: {hash} SHA-256 file: {hash} Read the objects it is given Membaca objek yang diberikan kepadanya Change, add and delete objects in the document Mengubah, menambah, dan menghapus objek dalam dokumen @@ -5882,6 +5963,16 @@ axis Y Axis Sumbu Y @msg message must be text message harus berupa teks @msg allowContinue must be true or false allowContinue harus true atau false @msg Batch cannot play an action with a stop Batch tidak dapat memutar tindakan dengan titik henti + Insert Menu Item… Sisipkan item menu… + Insert Menu Item Sisipkan item menu + Menu Item: Item menu: + No menu item matches. Tidak ada item menu yang cocok. + Several menu items match. Choose one from the list. Beberapa item menu cocok. Pilih salah satu dari daftar. + Items that open a dialog, and File, Window and Help menu items, are not listed. Item yang membuka dialog, serta item menu Berkas, Jendela, dan Bantuan, tidak dicantumkan. +@msg command must be text command harus berupa teks +@msg no menu item that can be inserted runs this command tidak ada item menu yang dapat disisipkan yang menjalankan perintah ini +@msg the action already has 10,000 steps tindakan sudah memiliki 10.000 langkah +@msg the action set would be larger than 8 MiB set tindakan akan lebih besar dari 8 MiB Playback Options Opsi pemutaran Accelerated Dipercepat Step by Step Langkah demi langkah @@ -5915,6 +6006,12 @@ axis Y Axis Sumbu Y Crosshair Bidik silang Checkpoint Pos pemeriksaan Inventory Icons Ikon Inventaris + Skill Icons Ikon Keahlian + Attack Serang + Defend Bertahan + Heal Pulihkan + Buff Buff + Ult Ult Sword Pedang Shield Perisai Potion Ramuan @@ -5973,7 +6070,23 @@ axis Y Axis Sumbu Y Dash Trail Jejak putus-putus Speed Line Garis kecepatan Game Trails Jejak game + Energy Beams Sinar Energi + Laser Bolt Bolt Laser + Plasma Arc Busur Plasma + Charge Wave Gelombang Muatan + Spark Trail Jejak Percikan Calligraphic Nibs Pena kaligrafi + Bristle Brushes Kuas-kuas bristle + Fine Liner Garis halus + Pointed Flat Pipih runcing + Stubby Round Bulat pendek + Dry Scrub Gosok kering + Soft Dome Kubah lembut + Filbert Pipih oval + Angled Round Bulat miring + Angled Flat Pipih miring + Fan Blender Kipas pembaur + Grass Fan Kipas rumput Pattern Borders Bingkai pola Scatter Shapes Bentuk sebar Save Brush Library… Simpan pustaka kuas… @@ -6317,6 +6430,12 @@ breakText Glyphs Glif Delete the selected brushes? Hapus kuas yang dipilih? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Stroke menggunakan satu atau beberapa kuas ini. Lepaskan kuas dari stroke tersebut dan hapus kuasnya? Remove Strokes Hapus Stroke + Place Brush Art Tempatkan karya seni kuas + Replace Brush Art Ganti karya seni kuas + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Stroke menggunakan kuas ini. Terapkan karya seni baru ke stroke tersebut, atau biarkan apa adanya dan tambahkan salinan kuas dengan karya seni baru? + Apply to Strokes Terapkan ke Stroke + Leave Strokes Biarkan Stroke +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` tidak memiliki karya seni (hanya kuas sebar, kuas seni, dan kuas pola yang memilikinya) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alat penyusunan Arrange in Grid… Susun dalam grid… @@ -6499,6 +6618,11 @@ breakText Glyphs Glif No importer plug-ins installed Tidak ada plug-in impor yang terinstal Read files you open in its format and make documents from them Membaca file yang Anda buka dalam formatnya dan membuat dokumen darinya +# Copy Troubleshooting Info + Copy Troubleshooting Info Salin info pemecahan masalah +@msg Copied the troubleshooting info Berhasil menyalin info pemecahan masalah +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Sesi terakhir VectorCraft berhenti merespons sebelum ditutup. Bantuan › Salin info pemecahan masalah menyalin detailnya untuk laporan bug + # Safe Mode Safe Mode… Mode aman… Safe Mode Mode aman @@ -6519,6 +6643,8 @@ breakText Glyphs Glif # Align to Pixel Grid Align to Pixel Grid Sejajarkan ke grid piksel + Align New Objects to Pixel Grid Sejajarkan objek baru ke grid piksel + Not Aligned to Pixel Grid Tidak sejajar ke grid piksel @msg side is left or right, not `{s}` side adalah left atau right, bukan `{s}` Edit Custom Dictionary Edit kamus kustom Entry: Entri: @@ -6544,6 +6670,26 @@ breakText Glyphs Glif @plural {n} earlier line dropped|{n} earlier lines dropped {n} baris lama dibuang @plural {n} line cut|{n} lines cut {n} baris dipotong +# Learn panel + Learn Belajar + Explore tutorials Jelajahi tutorial + For you Untuk Anda + Skills Keterampilan + Get started Memulai + Quick skill guide Panduan cepat keterampilan + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Tutorial praktik singkat untuk alat-alat utama, dikelompokkan menurut keterampilan. Pilih keterampilan untuk melihat tutorialnya. + List Tutorials Daftar tutorial + Show Tutorial Tampilkan tutorial +@msg missing `tutorial` (see learn.list) `tutorial` tidak ada (lihat learn.list) +@msg unknown tutorial `{id}` (see learn.list) tutorial `{id}` tidak dikenal (lihat learn.list) + # Deferred plug-in effects Refresh Deferred Effects Segarkan efek yang ditunda Deferred Effects Efek yang ditunda + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Alat pemotongan + Stencil Bridges… Jembatan Stensil… + Stencil Bridges Jembatan Stensil + Shortest Crossing Persilangan terpendek + Direction Arah diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6a8f3d7253..8ad07b5fbf 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -262,6 +262,7 @@ font-technology Variable Variabili Asset Export Settings Impostazioni esportazione risorse Assets Risorse Assign Assegna + Assign Profile Assegna profilo Assign Profile… Assegna profilo… Assign: Assegna: Attach to Active Plane Associa al piano attivo @@ -700,6 +701,15 @@ font-technology Variable Variabili Created: Creato: Crop Ritaglia Crop Image Ritaglia immagine + Image Tools Strumenti immagine + Remove Background… Rimuovi sfondo… + Remove Background Rimuovi sfondo + Background Sfondo + Edge Color Colore del bordo + Picked Colors Colori scelti + Corner Color Colore degli angoli + Contiguous Contiguo + Each Channel Ogni canale Edit Path Modifica tracciato Mask Maschera Crop Marks Segni di ritaglio @@ -819,6 +829,14 @@ font-technology Variable Variabili Disable Auto Add/Delete Disattiva aggiunta/eliminazione automatica Disable Opacity Mask Disattiva maschera di opacità Discard Scarta + Preserve Mantieni + TIFF (Black & White) TIFF (bianco e nero) + TIFF (8-bit Color) TIFF (colore a 8 bit) + High Resolution Alta risoluzione + Medium Resolution Media risoluzione + Low Resolution Bassa risoluzione + Language Level 2 Livello di linguaggio 2 + Language Level 3 Livello di linguaggio 3 Discard Empty Type Scarta testo vuoto Discard Recovered Documents Scarta documenti recuperati Discard White Overprint in Output Scarta sovrastampa del bianco nell'output @@ -1144,6 +1162,8 @@ font-technology Variable Variabili Extrude & Bevel… Estrusione e smusso… 3D (Classic) 3D (classico) Extrude & Bevel (Classic)… Estrusione e smusso (classico)… + Revolve (Classic)… Rivoluzione (classico)… + Rotate (Classic)… Ruota (classico)… Surface Superficie Wireframe Reticolo No Shading Nessuna ombreggiatura @@ -1456,6 +1476,14 @@ file-filter Templates Modelli Hair Space Spazio sottilissimo Hand Tool Strumento Mano Hand-Drawn Disegnato a mano + Painted and Sketched Dipinto e schizzato + Washed Blue Blu slavato + Bristle Ochre Ocra a setole + Pastel Heather Erica pastello + Charcoal Shade Ombra a carboncino + Ink Contour Contorno a china + Wet Ink China bagnata + Fine Pen Pennino fine Handles Maniglie Hard Light Luce intensa Hard Mix Miscela intensa @@ -1686,6 +1714,7 @@ file-filter Templates Modelli Include Linked Files Includi file collegati Include Metadata Includi metadati Include non-printing layers Includi livelli non stampabili + Write pages longer than 200 in at full size in points Scrivi le pagine più lunghe di 200 in a grandezza reale, in punti Include SVG Code Includi codice SVG Include Swatches for Tints Includi campioni per tinte Inflate… Gonfia… @@ -2364,12 +2393,23 @@ file-filter Templates Modelli Open… Apri… Optical Ottica Optical Margin Alignment Allineamento ottico dei margini + Dynamic Text Testo dinamico + Dynamic Text Presets Predefiniti testo dinamico + Arch Volta +@msg select point type or type on a path seleziona testo per punti o testo su tracciato +@msg type on a path in a thread cannot use Dynamic Text: {frames} il testo su tracciato in un testo concatenato non può usare il testo dinamico: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} il testo su un tracciato aperto o composto non può essere centrato in alto o in basso: {open} +@msg type on a path with no length or no height cannot be centered: {flat} il testo su un tracciato senza lunghezza o senza altezza non può essere centrato: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} il testo su tracciato in un testo concatenato non può essere centrato in alto o in basso: {frames} +@msg select type on a closed path seleziona del testo su un tracciato chiuso Optimize for fast web view Ottimizza per visualizzazione web veloce Optimized Ottimizzato Options Opzioni Options for Selection… Opzioni per la selezione… Options: Opzioni: Options… Opzioni… + Organic Fades Dissolvenze organiche + Holographic Olografici or more spaces with a tab o più spazi con una tabulazione Order: Ordine: Ordinals Ordinali @@ -2563,6 +2603,7 @@ diagnostics ui interfaccia Presets: Preset: Press Premi Preview Anteprima + Preview: Anteprima: Preview All Layers Anteprima di tutti i livelli Preview in Browser Anteprima nel browser Preview in Browser needs the desktop app (the web downloads files instead) Anteprima nel browser richiede l'app desktop (la versione web scarica invece i file) @@ -2643,6 +2684,8 @@ digits Malayalam Malayalam Radial Radiale Radial Glows Bagliori radiali Radial Gradient Sfumatura radiale + Conic Gradient Sfumatura conica + Diamond Gradient Sfumatura a rombo Radius 1 Raggio 1 Radius 2 Raggio 2 Radius1 Raggio1 @@ -2655,6 +2698,8 @@ digits Malayalam Malayalam Range: Intervallo: Raster Effects Effetti raster Raster File Format: Formato file raster: + Include Placed Images Includi immagini inserite + Include Fill Hatches Includi tratteggi dei riempimenti Raster Sample Size: Dimensione campione raster: Raster/Vector Balance: Bilanciamento raster/vettoriale: Rasterize Rasterizza @@ -2836,6 +2881,10 @@ digits Malayalam Malayalam Replace Font Sostituisci font Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Sostituiscilo con un altro file oppure ignoralo: le sue immagini continueranno a mostrare l'anteprima salvata con il documento. Replace Spine Sostituisci dorsale + Create Spine Crea dorsale + Create Spine: Crea dorsale: + Always Sempre + Never Mai Replace Symbol Sostituisci simbolo Reset Transformation Reimposta trasformazione Replace With Font Sostituisci con font @@ -2915,6 +2964,9 @@ digits Malayalam Malayalam Rise… Ascesa… Roman Baseline Linea di base romana Roman Hanging Punctuation Punteggiatura sporgente romana + Korean Line Break Anywhere Interruzione di riga coreana ovunque + East Asian Composition Settings Impostazioni di composizione dell’Asia orientale + Korean Composition Settings Impostazioni di composizione coreana Rotate Ruota Rotate 90° CW Ruota di 90° in senso orario Rotate Tool Strumento Ruota @@ -3200,6 +3252,15 @@ digits Malayalam Malayalam Stun Pulse Stordimento Stealth Fade Furtività Shield Buff Scudo + Textures Texture + Fine Grain Grana fine + Canvas Weave Trama di tela + Burlap Sack Sacco di iuta + Cracked Glaze Smalto craquelé + Mosaic Floor Pavimento a mosaico + Quilted Squares Quadrati trapuntati + Leaded Glass Vetro piombato + Damp Paper Carta umida Shape Forma Shape Builder Generatore forme Shape Builder Regions Aree del Generatore forme @@ -3262,6 +3323,7 @@ digits Malayalam Malayalam Show Modified Mostra modificati Show Note Mostra nota Show Options Mostra opzioni + Show Recent Colors Mostra colori recenti Show Original Path Mostra tracciato originale Open this dialog with these settings next time Apri questa finestra di dialogo con queste impostazioni la prossima volta Auto-Simplify Semplifica automaticamente @@ -3566,6 +3628,8 @@ digits Malayalam Malayalam Scale at Center Ridimensiona dal centro Up/Down: Su/giù: Left/Right: Sinistra/destra: + Tate-chu-yoko Up/Down Tate-chu-yoko su/giù + Tate-chu-yoko Left/Right Tate-chu-yoko sinistra/destra Temperature Temperatura Temperature/Tint… Temperatura/tinta… Template Modello @@ -3636,6 +3700,8 @@ digits Malayalam Malayalam Toolbar: Single/Double Column Barra degli strumenti: colonna singola/doppia Toolbar: Add Tool Barra degli strumenti: aggiungi strumento Toolbar: Remove Tool Barra degli strumenti: rimuovi strumento + Add Tool… Aggiungi strumento… + Remove Tool Rimuovi strumento Toolbar: Reset Barra degli strumenti: ripristina Toolbars Barre degli strumenti Tools Strumenti @@ -3707,6 +3773,8 @@ digits Malayalam Malayalam Type on a Path Testo su tracciato Type on a Path Options Opzioni testo su tracciato Type on a Path Options… Opzioni testo su tracciato… + Center on Top Centra in alto + Center on Bottom Centra in basso Type on a Path Tool Strumento Testo su tracciato Type Orientation Orientamento testo Type stays text, and every stroke is a line with its lineweight and dashes. Il testo resta testo e ogni traccia diventa una linea con il suo spessore e i suoi tratteggi. @@ -3900,6 +3968,7 @@ digits Malayalam Malayalam Windows Windows Working CMYK CMYK di lavoro Working CMYK (don't tag) CMYK di lavoro (senza tag) + Working RGB (don't tag) RGB di lavoro (senza tag) Workspace Area di lavoro Workspace {i} Area di lavoro {i} Wrinkle Tool Strumento Grinza @@ -4088,6 +4157,13 @@ axis Both Entrambi Dock Panel Ancora pannello Dock to Top Ancora in alto Dock to Bottom Ancora in basso + Control Bar Options Opzioni barra di controllo + Tool Options Opzioni strumento + Object Options Opzioni oggetto + Image Options Opzioni immagine + Vertical Alignment Allineamento verticale + Align and Distribute Allinea e distribuisci + Document Options Opzioni documento Dock Control Bar Ancora barra di controllo Drag to float the toolbar Trascina per rendere mobile la barra degli strumenti Drag to the window's left or right edge to dock Trascina sul bordo sinistro o destro della finestra per ancorare @@ -4240,10 +4316,13 @@ axis Both Entrambi @msg `groupColors` must be an array `groupColors` deve essere un array @msg `library` is a library id or name (see {list}) `library` è l'id o il nome di una libreria (vedi {list}) @msg `mode` applies to freeform gradients `mode` si applica alle sfumature a forma libera +@msg a negative `aspect` applies to conic gradients un `aspect` negativo si applica alle sfumature coniche +@msg `focal` applies to radial gradients `focal` si applica alle sfumature radiali @msg `preserve` must be an object `preserve` deve essere un oggetto @msg `globalAdjust` must be an object `globalAdjust` deve essere un oggetto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` deve essere 1, 3 o 5 @msg `stops` must be an array `stops` deve essere un array +@msg `{key}` must be an array `{key}` deve essere un array @msg `svg` must be an object of SVG options (see document.formats) `svg` deve essere un oggetto di opzioni SVG (vedi document.formats) @msg `{_1}` is no save command `{_1}` non è un comando di salvataggio @msg `{area}` is no recovery area name `{area}` non è il nome di un'area di recupero @@ -4257,6 +4336,7 @@ axis Both Entrambi @msg `{key}` must be a number, not {v} `{key}` deve essere un numero, non {v} @msg {key} must be Unix seconds (an integer) or null {key} deve essere un tempo Unix in secondi (un intero) o null @msg `{key}` must be a string `{key}` deve essere una stringa +@msg `{key}` must be a profile name or null `{key}` deve essere un nome di profilo o null @msg `{key}` must be a whole number `{key}` deve essere un numero intero @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` deve essere un numero intero tra {min} e {max} (ricevuto {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` deve essere compreso tra {min} e {max} (ricevuto {x}) @@ -4409,6 +4489,7 @@ axis Both Entrambi @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la pagina della tavola da disegno {n} misura {size}, più del limite di pagina PDF di 14.400 pt (200 in): viene scritta con una UserUnit di {unit}, quindi le app che ignorano UserUnit la mostrano altrettante volte più piccola @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la pagina della tavola da disegno {n} misura {size}, più del limite di pagina PDF di 14.400 pt (200 in): le pagine {label} vengono scritte senza UserUnit, in punti, e le app che rispettano il limite tagliano la pagina a 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 non ha UserUnit, che serve a una pagina più lunga di 14.400 pt (200 in) per mantenere le sue dimensioni: il file viene scritto come PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 non ha UserUnit, che serve a una pagina più lunga di 14.400 pt (200 in) per restare entro il limite di pagina di PDF/A-2, di 14.400 unità: il file viene scritto come PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la pagina della tavola da disegno {n} misura {size}, troppo lunga e stretta per i lati di pagina PDF da 3 a 14.400 unità: viene scritta con una UserUnit di {unit}, che tiene il lato corto a 3 unità o più, e le app che rispettano il limite tagliano il lato lungo a 14.400 unità @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard i file {label} accettano numeri reali fino a {max}, e la pagina della tavola da disegno {n}, lunga {side} pt, ne richiede di più grandi: scegli PDF 1.6 o successivo senza standard PDF/X, oppure una tavola da disegno più piccola @msg invalid image data for `{0}` dati immagine non validi per `{0}` @@ -4557,6 +4638,8 @@ axis Both Entrambi @msg not a stored central record non è un record centrale archiviato @msg not a valid plug-in module: {0} non è un modulo plug-in valido: {0} @msg not an EMF or WMF file non è un file EMF o WMF +@msg not an HP-GL file non è un file HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` deve essere un elenco da 1 a 255 colori #rrggbb @msg not found non trovato @msg not in pattern editing mode non sei in modalità modifica motivo @msg finish editing the pattern first termina prima la modifica del motivo @@ -4636,6 +4719,14 @@ axis Both Entrambi @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 questo ricalco creerebbe più di {max} punti di ancoraggio, più di quanti il documento possa mostrare in modo fluido: aumenta Disturbo, riduci Tracciati o Colori, oppure scegli un preset a fedeltà inferiore @msg select an envelope seleziona un involucro @msg select an image seleziona un'immagine +@msg `background` must be edges, corners or colors `background` deve essere edges, corners o colors +@msg `match` must be distance or channels `match` deve essere distance o channels +@msg `{key}` must be from 0 to 100 `{key}` deve essere compreso tra 0 e 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` deve elencare da 1 a 16 colori, ciascuno in esadecimale (#rrggbb o #rgb) o come black, white, red, green o blue +@msg the linked image shows its preview: embed or relink it first l’immagine collegata mostra la sua anteprima: incorporala o ricollegala prima +@msg a CMYK image has no transparency to set un'immagine CMYK non ha trasparenza da impostare +@msg every pixel matches the background: no image would be left ogni pixel corrisponde allo sfondo: non resterebbe alcuna immagine +@msg an image of {w} × {h} pixels is too large to change un'immagine di {w} × {h} pixel è troppo grande per essere modificata @msg select an object in perspective seleziona un oggetto in prospettiva @msg select artwork (or a colour group) to recolor seleziona la grafica (o un gruppo colori) da ricolorare @msg Recolor completed; {locked} and {hidden} were left unchanged Ricolorazione completata; senza modifiche: {locked} e {hidden} @@ -4742,7 +4833,7 @@ axis Both Entrambi @msg unknown format formato sconosciuto @msg unknown format `{f}` (Save writes {_1}) formato sconosciuto `{f}` (Salva scrive {_1}) @msg unknown freeform mode `{m}` (points, lines) modalità a forma libera sconosciuta `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) tipo di sfumatura sconosciuto `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) tipo di sfumatura sconosciuto `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` evidenziazione sconosciuta `{h}` @msg unknown option `{path}.{k}` opzione sconosciuta `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) valore di sovrastampa sconosciuto `{o}` (preserve, simulate o discard) @@ -4968,6 +5059,8 @@ axis Both Entrambi @msg invalid object id {value}: expected a non-negative integer ID oggetto {value} non valido: è richiesto un intero non negativo @msg `{key}` entry {index} is {value}, not a non-negative integer object id la voce {index} di `{key}` è {value}, non un ID oggetto (intero non negativo) @msg no such object id {value} nessun oggetto con ID {value} +@msg id {value} is a ruler guide, not an object l’ID {value} è di una guida, non di un oggetto +@msg a ruler guide goes only directly in a layer or sublayer una guida può stare solo direttamente in un livello o sottolivello @msg id {value} is a layer, not an object l’ID {value} è un livello, non un oggetto @msg id {value} is a layer, not an object; move layers with layer.move l’ID {value} è un livello, non un oggetto; sposta i livelli con layer.move @msg automation filesystem access is not granted: read authority is absent: {path} l'automazione non ha accesso al file system: manca l'autorizzazione di lettura: {path} @@ -4997,7 +5090,13 @@ axis Both Entrambi @msg the HEIC or HEIF file holds a kind of image that can't be read il file HEIC o HEIF contiene un tipo di immagine che non può essere letto @msg HEIC and HEIF images can't be opened in this build le immagini HEIC e HEIF non possono essere aperte in questa build @msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel) -@msg zipped 32-bit PSD image data with prediction can't be read i dati immagine PSD a 32 bit compressi ZIP con previsione non possono essere letti +@msg zipped 1-bit PSD image data with prediction can't be read i dati immagine PSD a 1 bit compressi ZIP con previsione non possono essere letti +@msg the PSD file's layer data uses an unknown compression ({m}) i dati dei livelli del file PSD usano una compressione sconosciuta ({m}) +@msg the PSD file's layer records are damaged i record dei livelli del file PSD sono danneggiati +@msg the PSD file's layer groups are nested too deeply i gruppi di livelli del file PSD sono annidati troppo in profondità +@msg a layer of the PSD file is too large to read un livello del file PSD è troppo grande per essere letto +@msg the PSD file's layers take more memory to read than allowed i livelli del file PSD richiedono più memoria del consentito per essere letti +@msg the layers can't be read ({e}): the file opened as its merged image i livelli non possono essere letti ({e}): il file è stato aperto come immagine unita @msg {depth}-bit PSD files in this colour mode can't be read i file PSD a {depth} bit in questo metodo colore non possono essere letti @msg the PSD file is cut short il file PSD è troncato @msg the PSD file's header is damaged l'intestazione del file PSD è danneggiata @@ -5314,6 +5413,11 @@ lighting Light Luce Softness Morbidezza Ambient Light Luce ambientale Light behind the object Luce dietro l'oggetto + Shadows Ombre + Distance from Object Distanza dall'oggetto + Shadow Bounds Limiti dell'ombra + Behind Object Dietro l'oggetto + Below Object Sotto l'oggetto 3D Lighting Preset Predefinito illuminazione 3D Standard Standard Diffuse Diffusa @@ -5381,7 +5485,7 @@ lighting Light Luce @msg span must be "object" or "selection", got {v} span deve essere "object" o "selection", non {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" posiziona un `gradient`, non un campione @msg span: "selection" places a gradient: give `gradient` span: "selection" posiziona una sfumatura: indica `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" posiziona una sfumatura lineare o radiale, non una sfumatura a forma libera +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" posiziona una sfumatura lineare, radiale, conica o a rombo, non una sfumatura a forma libera @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" posiziona la sfumatura stessa: ometti `start` e `end` (la posizionano già in coordinate del documento) Make Image Dynamic Rendi immagine dinamica Import Data Sets… Importa set di dati… @@ -5566,6 +5670,7 @@ lighting Light Luce Ruby Ruby Geometric Guides Guide geometriche Geometric Patterns Motivi geometrici + Grit Textures Texture granulose Ease In Inizio graduale Ease Out Fine graduale Ease In Out Inizio e fine graduali @@ -5626,6 +5731,8 @@ axis Y Axis Asse Y Version: {version} Versione: {version} Install “{name}” in place of the plug-in with the same ID? Installare “{name}” al posto del plug-in con lo stesso ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Questo file non è il plug-in installato prima con questo ID. Riceve le impostazioni e la cache conservate per quell’ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Un’automazione ha chiesto di installare questo plug-in. Per installarlo, scegli Oggetto › Plug-in › Installa plug-in… di persona. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Un’automazione ha chiesto di installare questo plug-in. Per installarlo, scegli Oggetto › Plug-in › Installa plug-in… di persona. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}” è un modulo diverso dal plug-in con ID {_1} e riceverebbe le impostazioni e la cache conservate per esso: installalo con `replace: true` quando l’utente acconsente File SHA-256: {hash} SHA-256 del file: {hash} Read the objects it is given Leggere gli oggetti che riceve @@ -5671,6 +5778,11 @@ axis Y Axis Asse Y @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget di memoria (l’oggetto {_1} richiede {size} byte di input, ne restano {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget di oggetti (più di {MAX_OBJECTS} oggetti di sola lettura) +@msg instruction budget budget di istruzioni +@msg time budget budget di tempo +@msg memory budget (the selection is too large to hand over) budget di memoria (la selezione è troppo grande per essere passata) +@msg output size ({what} is {len} bytes, limit {max}) dimensione dell’output ({what} è di {len} byte, limite {max}) +@msg the plug-in's grant can't be removed from the plug-in store il permesso del plug-in non può essere rimosso dall’archivio dei plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it l’autorizzazione `{shown}` è riservata a un’API dei plug-in successiva; questo host non la concede @msg unknown permission `{shown}` autorizzazione sconosciuta `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” chiede le autorizzazioni {asked}: una persona deve approvarle nell’app desktop, oppure passa `grant` in una sessione avviata con --allow-plugin-grants @@ -5683,6 +5795,12 @@ axis Y Axis Asse Y @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve avere 1-64 caratteri stampabili @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id di 1-{MAX_COMMAND_ID} caratteri tra a-z 0-9 _ che inizi con una lettera @msg command {name}: {e} comando {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} (riga {line}, colonna {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` deve essere un elenco di comandi, ciascuno con `id` e `label` +@msg command {name} must be an object with an `id` and a `label` il comando {name} deve essere un oggetto con `id` e `label` +@msg missing field `{key}` campo `{key}` mancante +@msg duplicate field `{key}` campo `{key}` duplicato @msg only a filter or a live effect declares `commands` solo un filtro o un effetto dinamico dichiara `commands` @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed il modulo non ha lo SHA-256 indicato da `hash`: non è stato installato nulla @@ -5707,6 +5825,16 @@ axis Y Axis Asse Y @msg message must be text message deve essere testo @msg allowContinue must be true or false allowContinue deve essere true o false @msg Batch cannot play an action with a stop L'elaborazione batch non può eseguire un'azione con un'interruzione + Insert Menu Item… Inserisci voce di menu… + Insert Menu Item Inserisci voce di menu + Menu Item: Voce di menu: + No menu item matches. Nessuna voce di menu corrisponde. + Several menu items match. Choose one from the list. Corrispondono più voci di menu. Sceglierne una dall’elenco. + Items that open a dialog, and File, Window and Help menu items, are not listed. Le voci che aprono una finestra di dialogo e le voci dei menu File, Finestra e Aiuto non sono elencate. +@msg command must be text command deve essere testo +@msg no menu item that can be inserted runs this command nessuna voce di menu inseribile esegue questo comando +@msg the action already has 10,000 steps l’azione ha già 10.000 passaggi +@msg the action set would be larger than 8 MiB il set di azioni supererebbe 8 MiB Playback Options Opzioni di riproduzione Accelerated Accelerata Step by Step Passo per passo @@ -5745,6 +5873,12 @@ axis Y Axis Asse Y Crosshair Mirino Checkpoint Punto di controllo Inventory Icons Icone inventario + Skill Icons Icone abilità + Attack Attacco + Defend Difesa + Heal Cura + Buff Potenziamento + Ult Ult Sword Spada Shield Scudo Potion Pozione @@ -5809,7 +5943,23 @@ axis Y Axis Asse Y Dash Trail Scia tratteggiata Speed Line Linea di velocità Game Trails Scia di gioco + Energy Beams Raggi di energia + Laser Bolt Dardo laser + Plasma Arc Arco al plasma + Charge Wave Onda di carica + Spark Trail Scia di scintille Calligraphic Nibs Pennini calligrafici + Bristle Brushes Pennelli a setole + Fine Liner Tratto fine + Pointed Flat Piatto appuntito + Stubby Round Tondo corto + Dry Scrub Strofinato secco + Soft Dome Cupola morbida + Filbert Lingua di gatto + Angled Round Tondo obliquo + Angled Flat Piatto obliquo + Fan Blender Ventaglio sfumino + Grass Fan Ventaglio per erba Pattern Borders Bordi a motivo Scatter Shapes Forme a dispersione Save Brush Library… Salva libreria pennelli… @@ -6009,9 +6159,12 @@ anchor Points: Punti: @msg {label} must be a number {label} deve essere un numero @msg {label} must be a number of at least 0.1 {label} deve essere un numero di almeno 0,1 Advanced Character Formats Formati carattere avanzati + Basic Paragraph Formats Formati paragrafo di base + Composition Composizione Horizontal Scale Scala orizzontale Vertical Scale Scala verticale @msg {label} must be a number from {min} to {max} {label} deve essere un numero da {min} a {max} +@msg {label} must be a whole number from {min} to {max} {label} deve essere un numero intero da {min} a {max} Character Color Colore carattere OpenType Features Funzioni OpenType Stylistic Sets Set stilistici @@ -6019,6 +6172,10 @@ anchor Points: Punti: @msg features lists at most {max} tags features contiene al massimo {max} tag @msg unknown OpenType feature `{t}` funzione OpenType sconosciuta `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve essere un numero maggiore di 0 e al massimo {max} +@msg {label} must be at most {max} characters {label} deve avere al massimo {max} caratteri +@msg {label} must be one character {label} deve essere un solo carattere +@msg at most {max} tab stops al massimo {max} tabulazioni +@msg unknown align `{other}` allineamento sconosciuto `{other}` @msg no character style `{name}` Stile di carattere `{name}` non trovato # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6181,6 +6338,12 @@ breakText Glyphs Glifi Delete the selected brushes? Eliminare i pennelli selezionati? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Alcune tracce usano uno o più di questi pennelli. Rimuovere i pennelli da queste tracce ed eliminare i pennelli? Remove Strokes Rimuovi tracce + Place Brush Art Inserisci grafica del pennello + Replace Brush Art Sostituisci grafica del pennello + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Alcune tracce usano questo pennello. Applicare la nuova grafica a queste tracce, o lasciarle come sono e aggiungere una copia del pennello con la nuova grafica? + Apply to Strokes Applica alle tracce + Leave Strokes Lascia le tracce +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` non ha una grafica (ce l’hanno solo i pennelli a dispersione, artistici e motivo) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Strumenti di disposizione Arrange in Grid… Disponi in griglia… @@ -6376,6 +6539,11 @@ breakText Glyphs Glifi @msg only an exporter or an importer declares `extensions` solo un plug-in di esportazione o di importazione dichiara `extensions` @msg an importer always gets an import's budget: leave `budget` out un plug-in di importazione riceve sempre il budget di un’importazione: ometti `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Copia informazioni per la risoluzione dei problemi +@msg Copied the troubleshooting info Informazioni per la risoluzione dei problemi copiate +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report L’ultima sessione di VectorCraft ha smesso di rispondere prima di chiudersi. Aiuto › Copia informazioni per la risoluzione dei problemi copia i dettagli per una segnalazione di bug + # Safe Mode Safe Mode… Modalità provvisoria… Safe Mode Modalità provvisoria @@ -6396,6 +6564,8 @@ breakText Glyphs Glifi # Align to Pixel Grid Align to Pixel Grid Allinea alla griglia pixel + Align New Objects to Pixel Grid Allinea nuovi oggetti alla griglia pixel + Not Aligned to Pixel Grid Non allineato alla griglia pixel @msg only paths and compound paths can be aligned to the pixel grid solo i tracciati e i tracciati composti possono essere allineati alla griglia pixel @msg side is left or right, not `{s}` side è left o right, non `{s}` Ignore All Ignora tutto @@ -6426,8 +6596,33 @@ breakText Glyphs Glifi @plural {n} line cut|{n} lines cut {n} riga tagliata|{n} righe tagliate @msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devono essere numeri di righe presenti nella console, `first` prima di `last` +# Learn panel + Learn Impara + Explore tutorials Esplora i tutorial + For you Per te + Skills Competenze + Get started Per iniziare + Quick skill guide Guida rapida alle competenze + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Brevi tutorial pratici sugli strumenti essenziali, raggruppati per competenza. Scegli una competenza per vederne i tutorial. + List Tutorials Elenca tutorial + Show Tutorial Mostra tutorial +@msg missing `tutorial` (see learn.list) manca `tutorial` (vedi learn.list) +@msg unknown tutorial `{id}` (see learn.list) tutorial sconosciuto `{id}` (vedi learn.list) + # Deferred plug-in effects Refresh Deferred Effects Aggiorna effetti rimandati Deferred Effects Effetti rimandati @msg no plug-in effect is deferred nessun effetto plug-in è rimandato @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Aperto con {n} effetto plug-in rimandato. Effetto › Aggiorna effetti rimandati lo esegue.|Aperto con {n} effetti plug-in rimandati. Effetto › Aggiorna effetti rimandati li esegue. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Strumenti di taglio + Stencil Bridges… Ponti per stencil… + Stencil Bridges Ponti per stencil + Shortest Crossing Attraversamento più breve + Direction Direzione +@msg The selected art has no islands to bridge La grafica selezionata non ha isole da collegare +@msg No bridge of this width fits across the selected art Nessun ponte di questa larghezza entra nella grafica selezionata +@msg Some islands could not be joined to the area around the art Non è stato possibile collegare alcune isole all’area intorno alla grafica +@msg `width` must be from {lo} to {hi} pt `width` deve essere compreso tra {lo} e {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve essere un numero intero compreso tra 1 e {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index aabe534b69..b658080d59 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -186,6 +186,7 @@ digits Malayalam マラヤーラム数字 PDF Presets… PDF プリセット… Perspective Grid Presets… 遠近グリッドプリセット… Color Settings… カラー設定… + Assign Profile プロファイルの指定 Assign Profile… プロファイルの指定… Keyboard Shortcuts… キーボードショートカット… Preferences… 環境設定… @@ -231,6 +232,15 @@ digits Malayalam マラヤーラム数字 Expand… 分割・拡張… Expand Appearance アピアランスを分割 Crop Image 画像の切り抜き + Image Tools 画像ツール + Remove Background… 背景を削除… + Remove Background 背景を削除 + Background 背景 + Edge Color 端の色 + Picked Colors 選択したカラー + Corner Color 角の色 + Contiguous 隣接 + Each Channel 各チャンネル Edit Path パスを編集 Mask マスク Rasterize… ラスタライズ… @@ -280,6 +290,10 @@ digits Malayalam マラヤーラム数字 Blend Options… ブレンドオプション… Expand 拡張 Replace Spine スパインを置き換え + Create Spine スパインを作成 + Create Spine: スパインを作成: + Always 常に + Never しない Reverse Spine スパインを反転 Reverse Front to Back 前後を反転 Envelope Distort エンベロープ @@ -409,6 +423,8 @@ digits Malayalam マラヤーラム数字 Stair Step 階段 Gravity 引力 Type on a Path Options… パス上文字オプション… + Center on Top 上端に中央揃え + Center on Bottom 下端に中央揃え Threaded Text スレッドテキストオプション Create 作成 Release Selection 選択部分をリリース @@ -434,6 +450,15 @@ digits Malayalam マラヤーラム数字 Smart Punctuation… 欧文用字形の自動置換… Create Outlines アウトラインを作成 Optical Margin Alignment 最適なマージン揃え + Dynamic Text ダイナミックテキスト + Dynamic Text Presets ダイナミックテキストプリセット + Arch アーチ +@msg select point type or type on a path ポイント文字またはパス上文字を選択してください +@msg type on a path in a thread cannot use Dynamic Text: {frames} スレッドテキスト内のパス上文字にはダイナミックテキストを使用できません: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} オープンパスや複合パス上のパス上文字は上端または下端に中央揃えできません: {open} +@msg type on a path with no length or no height cannot be centered: {flat} 長さや高さのないパスのパス上文字は中央揃えできません: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} スレッドテキスト内のパス上文字は上端または下端に中央揃えできません: {frames} +@msg select type on a closed path クローズパス上のパス上文字を選択してください Fill with Placeholder Text サンプルテキストの割り付け Insert Inline Symbol インラインシンボルを挿入 Show Hidden Characters 制御文字を表示 @@ -512,6 +537,8 @@ digits Malayalam マラヤーラム数字 Extrude & Bevel… 押し出しとベベル… 3D (Classic) 3D(クラシック) Extrude & Bevel (Classic)… 押し出しとベベル(クラシック)… + Revolve (Classic)… 回転体(クラシック)… + Rotate (Classic)… 回転(クラシック)… Surface 表面 Wireframe ワイヤーフレーム No Shading 陰影なし @@ -814,8 +841,25 @@ digits Malayalam マラヤーラム数字 Stun Pulse 気絶 Stealth Fade ステルス Shield Buff シールド + Textures テクスチャ集 + Fine Grain 細かい粒子 + Canvas Weave キャンバス織り + Burlap Sack 麻袋 + Cracked Glaze ひび割れ釉 + Mosaic Floor モザイクの床 + Quilted Squares キルトの四角 + Leaded Glass 鉛ガラス + Damp Paper 湿った紙 Outlines and Rules アウトラインと罫線 Hand-Drawn 手描き風 + Painted and Sketched 絵画とスケッチ + Washed Blue にじみブルー + Bristle Ochre 筆跡オーカー + Pastel Heather パステルヘザー + Charcoal Shade 木炭シェード + Ink Contour インク輪郭 + Wet Ink 濡れ墨 + Fine Pen 細いペン Gradient Finishes グラデーション仕上げ Shape Effects シェイプ効果 Blends and Transparency ブレンドと透明 @@ -835,6 +879,8 @@ digits Malayalam マラヤーラム数字 Spectrum Gradients スペクトルグラデーション Sky Gradients 空のグラデーション Neutral Gradients ニュートラルグラデーション + Organic Fades オーガニックフェード + Holographic ホログラフィック Duotone Gradients ダブルトーングラデーション Radial Glows 円形グロー Save Swatch Library… スウォッチライブラリを保存… @@ -846,6 +892,7 @@ digits Malayalam マラヤーラム数字 Search Commands… コマンドを検索… VectorCraft Help… VectorCraft ヘルプ… Preview プレビュー + Preview: プレビュー: Show Edges エッジを表示 Show Corner Widget コーナーウィジェットを表示 Show Template テンプレートを表示 @@ -1435,6 +1482,14 @@ antiAlias Sharp シャープ Disable Auto Add/Delete 自動追加/削除機能を使用しない Disable Opacity Mask 不透明マスクを無効にする Discard 破棄 + Preserve 保持 + TIFF (Black & White) TIFF (白黒) + TIFF (8-bit Color) TIFF (8 bit カラー) + High Resolution 高解像度 + Medium Resolution 中解像度 + Low Resolution 低解像度 + Language Level 2 言語レベル 2 + Language Level 3 言語レベル 3 Discard Empty Type 空のテキストを破棄 Discard Recovered Documents 復帰したドキュメントを破棄 Discard White Overprint in Output 出力時に白のオーバープリントを破棄 @@ -2002,6 +2057,7 @@ antiAlias Sharp シャープ Include SVG Code SVG コードを含める Include Swatches for Tints ティント用のスウォッチを含める Include non-printing layers 印刷しないレイヤーを含む + Write pages longer than 200 in at full size in points 200 in より長いページを実寸のポイントで書き出す Ink インキ Insert Character 文字を挿入 Inspect Document ドキュメントを調査 @@ -2684,12 +2740,16 @@ mark-style Japanese 日本式 RECENT 最近使用したもの Radar Graph Tool レーダーチャートツール Radial Gradient 円形グラデーション + Conic Gradient 円錐グラデーション + Diamond Gradient ひし形グラデーション Random ランダム Randomize Colors カラーをランダム化 Randomly change color order カラーの順序をランダムに変更 Randomly change saturation and brightness 彩度と明度をランダムに変更 Range: 範囲: Raster File Format: ラスターファイル形式: + Include Placed Images 配置画像を含める + Include Fill Hatches 塗りのハッチングを含める Raster Sample Size: ラスターのサンプルサイズ: Raster/Vector Balance: ラスター/ベクターのバランス: Rasterize Unsupported Art 非対応のアートをラスタライズ @@ -2892,6 +2952,9 @@ mark-style Japanese 日本式 Right Plane 右面 Right: 右: Roman Hanging Punctuation 欧文ぶら下がり + Korean Line Break Anywhere 韓国語の任意位置での改行 + East Asian Composition Settings 東アジア言語の組版設定 + Korean Composition Settings 韓国語の組版設定 Rotate 回転 Rotate Tool 回転ツール Rotate View Tool 回転ビューツール @@ -3080,6 +3143,7 @@ mark-style Japanese 日本式 Show List View リスト表示 Show Note メモを表示 Show Options オプションを表示 + Show Recent Colors 最近使用したカラーを表示 Show Original Path 元のパスを表示 Open this dialog with these settings next time 次回はこの設定でこのダイアログを開く Auto-Simplify 自動単純化 @@ -3320,6 +3384,8 @@ mark-style Japanese 日本式 Toolbar: Single/Double Column ツールバー: 1 列/2 列 Toolbar: Add Tool ツールバー: ツールを追加 Toolbar: Remove Tool ツールバー: ツールを削除 + Add Tool… ツールを追加… + Remove Tool ツールを削除 Toolbar: Reset ツールバー: リセット Top: 上: Total Width: 合計幅: @@ -3891,6 +3957,8 @@ file-filter Templates テンプレート Scale at Center 中心から拡大・縮小 Up/Down: 上下: Left/Right: 左右: + Tate-chu-yoko Up/Down 縦中横の上下 + Tate-chu-yoko Left/Right 縦中横の左右 Temperature 色温度 Template テンプレート Templates テンプレート @@ -3929,6 +3997,7 @@ file-filter Templates テンプレート Weight 線幅 Windows Windows Working CMYK (don't tag) 作業用 CMYK (タグなし) + Working RGB (don't tag) 作業用 RGB (タグなし) Workspace {i} ワークスペース {i} Yellow イエロー [Normal Character Style] [標準文字スタイル] @@ -4030,6 +4099,13 @@ axis Both 両方 Dock Panel パネルをドッキング Dock to Top 上部にドッキング Dock to Bottom 下部にドッキング + Control Bar Options コントロールバーオプション + Tool Options ツールオプション + Object Options オブジェクトオプション + Image Options 画像オプション + Vertical Alignment 垂直方向の配置 + Align and Distribute 整列と分布 + Document Options ドキュメントオプション Dock Control Bar コントロールバーをドッキング Drag to float the toolbar ドラッグしてツールバーをフローティング Drag to the window's left or right edge to dock ウィンドウの左端または右端までドラッグしてドッキング @@ -4339,16 +4415,19 @@ swatch Bright Violet ビビッドバイオレット @msg `gradient` must be an object `gradient` にはオブジェクトを指定してください @msg `groupColors` must be an array `groupColors` には配列を指定してください @msg `mode` applies to freeform gradients `mode` はフリーフォームグラデーションにのみ適用されます +@msg a negative `aspect` applies to conic gradients 負の `aspect` は円錐グラデーションにのみ適用されます +@msg `focal` applies to radial gradients `focal` は円形グラデーションにのみ適用されます @msg `preserve` must be an object `preserve` にはオブジェクトを指定してください @msg `globalAdjust` must be an object `globalAdjust` にはオブジェクトを指定してください @msg `stops` must be an array `stops` には配列を指定してください +@msg `{key}` must be an array `{key}` には配列を指定してください @msg `{k}` must be [x, y] `{k}` は [x, y] の形式で指定してください @msg a gradient needs at least two stops グラデーションには 2 つ以上の分岐点が必要です @msg give both `start` and `end` [x, y] (or neither) `start` と `end` は両方とも [x, y] で指定するか、どちらも省略してください @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 unknown gradient kind `{k}` (linear, radial, freeform) `{k}` は不明なグラデーションの種類です (linear、radial、freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) `{k}` は不明なグラデーションの種類です (linear、radial、conic、diamond、freeform) @msg the art could not be sampled アートをサンプリングできませんでした @msg the art is too light for any dots アートが明るすぎて網点を生成できません @msg the document has no symbols ドキュメントにシンボルがありません @@ -4442,6 +4521,7 @@ swatch Bright Violet ビビッドバイオレット @msg `{key}` must be a #rrggbb color `{key}` は #rrggbb 形式のカラーにしてください @msg `{key}` must be a #rrggbb colour `{key}` は #rrggbb 形式のカラーにしてください @msg `{key}` must be a string `{key}` は文字列にしてください +@msg `{key}` must be a profile name or null `{key}` はプロファイル名または null にしてください @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 between {min} and {max} (got {x}) `{key}` は {min} から {max} までの値にしてください (指定値: {x}) @@ -4628,6 +4708,8 @@ swatch Bright Violet ビビッドバイオレット @msg the image's pixels don't match its size 画像のピクセル数がサイズと一致しません @msg {bpp}-bit bitmaps can't be read {bpp} ビットのビットマップは読み込めません @msg not an EMF or WMF file EMF ファイルでも WMF ファイルでもありません +@msg not an HP-GL file HP-GL ファイルではありません +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` は 1〜255 個の #rrggbb 形式のカラーの配列にしてください @msg its layers use {_1}, which aren't read yet レイヤーで使用されている {_1} はまだ読み込めません @msg the EMF header is damaged EMF ヘッダーが破損しています @msg damaged 破損しています @@ -4644,6 +4726,7 @@ swatch Bright Violet ビビッドバイオレット @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller アートボード {n} のページは {size} で、PDF のページ上限 14,400 pt (200 in) を超えています: UserUnit {unit} で書き出されるため、UserUnit を無視するアプリではその倍率だけ小さく表示されます @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in アートボード {n} のページは {size} で、PDF のページ上限 14,400 pt (200 in) を超えています: {label} のページは UserUnit なしでポイント単位で書き出され、上限を守るアプリではページが 200 in で切り取られます @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 には、14,400 pt (200 in) を超えるページがサイズを保つために必要な UserUnit がありません: ファイルは PDF 1.6 として書き出されます +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 には、14,400 pt (200 in) を超えるページが PDF/A-2 のページ上限 14,400 単位に収まるために必要な UserUnit がありません: ファイルは PDF 1.6 として書き出されます @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units アートボード {n} のページは {size} で、PDF のページ辺 3 から 14,400 単位には長く細すぎます: 短辺を 3 単位以上に保つ UserUnit {unit} で書き出され、上限を守るアプリは長辺を 14,400 単位で切り取ります @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} ファイルの実数は {max} までですが、アートボード {n} の {side} pt のページにはそれより大きな値が必要です: PDF/X 規格なしの PDF 1.6 以降を選ぶか、アートボードを小さくしてください @msg page {0} does not exist (the PDF has {1}) ページ {0} は存在しません (この PDF のページ数は {1} です) @@ -4838,6 +4921,14 @@ swatch Bright Violet ビビッドバイオレット @msg no such view 指定された表示が見つかりません @msg printing isn't available here この環境ではプリントできません @msg select an image 画像を選択してください +@msg `background` must be edges, corners or colors `background` は edges、corners または colors にしてください +@msg `match` must be distance or channels `match` は distance または channels にしてください +@msg `{key}` must be from 0 to 100 `{key}` は 0 から 100 までの値にしてください +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` には 16 進数(#rrggbb または #rgb)か black、white、red、green、blue で書いたカラーを 1〜16 個指定してください +@msg the linked image shows its preview: embed or relink it first リンク画像はプレビューを表示しています: 先に埋め込むか再リンクしてください +@msg a CMYK image has no transparency to set CMYK 画像には設定できる透明部分がありません +@msg every pixel matches the background: no image would be left すべてのピクセルが背景に一致します: 画像が残りません +@msg an image of {w} × {h} pixels is too large to change {w} × {h} ピクセルの画像は大きすぎて変更できません @msg the document has no artboards ドキュメントにアートボードがありません @msg tool (a tool id) is required tool (ツール ID) を指定してください @msg unknown tool `{t}` `{t}` は不明なツールです @@ -5009,6 +5100,8 @@ swatch Bright Violet ビビッドバイオレット @msg invalid object id {value}: expected a non-negative integer オブジェクト ID {value} は正しくありません: 0 以上の整数を指定してください @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}` の要素 {index} は {value} で、オブジェクト ID (0 以上の整数) ではありません @msg no such object id {value} ID が {value} のオブジェクトは見つかりません +@msg id {value} is a ruler guide, not an object ID {value} はオブジェクトではなくガイドです +@msg a ruler guide goes only directly in a layer or sublayer ガイドはレイヤーまたはサブレイヤーの直下にのみ置けます @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} はオブジェクトではなくレイヤーです。レイヤーは layer.move で移動してください @msg automation filesystem access is not granted: read authority is absent: {path} 自動化にはファイルシステムへのアクセスが許可されていません: 読み込み権限がありません: {path} @@ -5038,7 +5131,13 @@ swatch Bright Violet ビビッドバイオレット @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC または HEIF ファイルには読み込めない種類の画像が含まれています @msg HEIC and HEIF images can't be opened in this build このビルドでは HEIC と HEIF の画像を開けません @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル) -@msg zipped 32-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 32 bit PSD 画像データは読み込めません +@msg zipped 1-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 1 bit PSD 画像データは読み込めません +@msg the PSD file's layer data uses an unknown compression ({m}) PSD ファイルのレイヤーデータの圧縮方式が不明です({m}) +@msg the PSD file's layer records are damaged PSD ファイルのレイヤーレコードが破損しています +@msg the PSD file's layer groups are nested too deeply PSD ファイルのレイヤーグループの入れ子が深すぎます +@msg a layer of the PSD file is too large to read PSD ファイルのレイヤーが大きすぎて読み込めません +@msg the PSD file's layers take more memory to read than allowed PSD ファイルのレイヤーの読み込みに許容量を超えるメモリーが必要です +@msg the layers can't be read ({e}): the file opened as its merged image レイヤーを読み込めません({e}):ファイルは統合画像として開かれました @msg {depth}-bit PSD files in this colour mode can't be read このカラーモードの {depth} bit PSD ファイルは読み込めません @msg the PSD file is cut short PSD ファイルが途中で切れています @msg the PSD file's header is damaged PSD ファイルのヘッダーが破損しています @@ -5356,6 +5455,11 @@ lighting Light ライト Softness 柔らかさ Ambient Light 環境光 Light behind the object オブジェクトの背後のライト + Shadows シャドウ + Distance from Object オブジェクトからの距離 + Shadow Bounds シャドウの範囲 + Behind Object オブジェクトの背後 + Below Object オブジェクトの下 3D Lighting Preset 3D ライティングプリセット Standard 標準 Diffuse 拡散 @@ -5424,7 +5528,7 @@ lighting Light ライト @msg span must be "object" or "selection", got {v} span は "object" または "selection" で指定してください ({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 span: "selection" は線形または円形グラデーションを配置します。フリーグラデーションは配置できません +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" は線形、円形、円錐またはひし形グラデーションを配置します。フリーグラデーションは配置できません @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" はグラデーション自体を配置します: `start` と `end` は省略してください (これらはすでにドキュメント座標で配置を指定します) Make Image Dynamic 画像を動的にする Import Data Sets… データセットを読み込み… @@ -5616,6 +5720,7 @@ lighting Light ライト Ruby ルビ Geometric Guides 幾何ガイド Geometric Patterns 幾何パターン + Grit Textures 粒状テクスチャ Ease In イーズイン Ease Out イーズアウト Ease In Out イーズインアウト @@ -5691,6 +5796,8 @@ axis Y Axis Y 軸 Version: {version} バージョン: {version} Install “{name}” in place of the plug-in with the same ID? 同じ ID のプラグインの代わりに「{name}」をインストールしますか? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. このファイルは、以前にこの ID でインストールされていたプラグインではありません。この ID 用に保持されている設定とキャッシュを引き継ぎます。 + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 自動操作がこのプラグインのインストールを要求しました。インストールするには、オブジェクト › プラグイン › プラグインをインストール… をご自身で選んでください。 +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 自動操作がこのプラグインのインストールを要求しました。インストールするには、オブジェクト › プラグイン › プラグインをインストール… をご自身で選んでください。 @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees 「{name}」は ID {_1} のプラグインとは別のモジュールで、そのプラグイン用に保持されている設定とキャッシュを引き継ぐことになります。ユーザーが同意したら `replace: true` を指定してインストールしてください File SHA-256: {hash} ファイルの SHA-256: {hash} Read the objects it is given 渡されたオブジェクトの読み取り @@ -5736,6 +5843,11 @@ axis Y Axis Y 軸 @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です @msg memory budget (object {_1} needs {size} bytes of input, {left} left) メモリ予算 (オブジェクト {_1} には {size} バイトの入力が必要ですが、残りは {left} です) @msg object budget (more than {MAX_OBJECTS} read-only objects) オブジェクト予算 ({MAX_OBJECTS} 個を超える読み取り専用オブジェクト) +@msg instruction budget 命令予算 +@msg time budget 時間予算 +@msg memory budget (the selection is too large to hand over) メモリ予算 (選択範囲が大きすぎて渡せません) +@msg output size ({what} is {len} bytes, limit {max}) 出力サイズ ({what} は {len} バイト、上限 {max}) +@msg the plug-in's grant can't be removed from the plug-in store プラグインの許可をプラグインストアから削除できません @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 権限 `{shown}` は今後のプラグイン API 用に予約されています。このホストはこの権限を付与しません @msg unknown permission `{shown}` 不明な権限 `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants 「{name}」は権限 {asked} を求めています。デスクトップ アプリで人が承認するか、--allow-plugin-grants を付けて開始したセッションで `grant` を指定してください @@ -5748,6 +5860,12 @@ axis Y Axis Y 軸 @msg command {name}: `label` must be 1-64 printable characters コマンド {name}: `label` は印刷可能な 1-64 文字にしてください @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter コマンド {name}: a-z 0-9 _ からなり英字で始まる 1-{MAX_COMMAND_ID} 文字の ID を使用してください @msg command {name}: {e} コマンド {name}: {e} +@msg manifest: {e} マニフェスト: {e} +@msg manifest: {e} at line {line} column {column} マニフェスト: {e} ({line} 行目、{column} 列目) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` は、それぞれ `id` と `label` を持つコマンドのリストにしてください +@msg command {name} must be an object with an `id` and a `label` コマンド {name} は `id` と `label` を持つオブジェクトにしてください +@msg missing field `{key}` フィールド `{key}` がありません +@msg duplicate field `{key}` フィールド `{key}` が重複しています @msg only a filter or a live effect declares `commands` `commands` を宣言できるのはフィルターかライブ効果だけです @msg “{name}” › {label}: {e} 「{name}」 › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed モジュールの SHA-256 が `hash` の値と一致しません。何もインストールされませんでした @@ -5772,6 +5890,16 @@ axis Y Axis Y 軸 @msg message must be text message にはテキストを指定してください @msg allowContinue must be true or false allowContinue には true または false を指定してください @msg Batch cannot play an action with a stop バッチでは停止を含むアクションを再生できません + Insert Menu Item… メニュー項目を挿入… + Insert Menu Item メニュー項目を挿入 + Menu Item: メニュー項目: + No menu item matches. 一致するメニュー項目がありません。 + Several menu items match. Choose one from the list. 複数のメニュー項目が一致します。リストから 1 つ選択してください。 + Items that open a dialog, and File, Window and Help menu items, are not listed. ダイアログを開く項目と、ファイル、ウィンドウ、ヘルプメニューの項目は表示されません。 +@msg command must be text command にはテキストを指定してください +@msg no menu item that can be inserted runs this command このコマンドを実行する、挿入できるメニュー項目はありません +@msg the action already has 10,000 steps アクションにはすでに 10,000 ステップがあります +@msg the action set would be larger than 8 MiB アクションセットが 8 MiB を超えます Playback Options 再生オプション Accelerated 高速 Step by Step ステップ実行 @@ -5810,6 +5938,12 @@ axis Y Axis Y 軸 Crosshair クロスヘア Checkpoint チェックポイント Inventory Icons インベントリアイコン + Skill Icons スキルアイコン + Attack 攻撃 + Defend 防御 + Heal 回復 + Buff バフ + Ult 必殺 Sword 剣 Shield 盾 Potion ポーション @@ -5874,7 +6008,23 @@ axis Y Axis Y 軸 Dash Trail ダッシュトレイル Speed Line スピードライン Game Trails ゲームトレイル + Energy Beams エネルギービーム + Laser Bolt レーザーボルト + Plasma Arc プラズマアーク + Charge Wave チャージウェーブ + Spark Trail スパークトレイル Calligraphic Nibs カリグラフィペン先 + Bristle Brushes 剛毛ブラシ集 + Fine Liner 細線ライナー + Pointed Flat 先細平筆 + Stubby Round 短丸筆 + Dry Scrub ドライスクラブ + Soft Dome ソフトドーム + Filbert フィルバート + Angled Round 斜め丸筆 + Angled Flat 斜め平筆 + Fan Blender ぼかし扇筆 + Grass Fan 草描き扇筆 Pattern Borders パターンボーダー Scatter Shapes 散布シェイプ Save Brush Library… ブラシライブラリを保存… @@ -6074,9 +6224,12 @@ anchor Points: ポイント: @msg {label} must be a number {label} には数値を指定してください @msg {label} must be a number of at least 0.1 {label} には 0.1 以上の数値を指定してください Advanced Character Formats 詳細文字形式 + Basic Paragraph Formats 基本段落形式 + Composition 組版 Horizontal Scale 水平比率 Vertical Scale 垂直比率 @msg {label} must be a number from {min} to {max} {label} には {min} から {max} までの数値を指定してください +@msg {label} must be a whole number from {min} to {max} {label} には {min} から {max} までの整数を指定してください Character Color 文字カラー OpenType Features OpenType 機能 Stylistic Sets スタイルセット @@ -6084,6 +6237,10 @@ anchor Points: ポイント: @msg features lists at most {max} tags features に指定できるタグは {max} 個までです @msg unknown OpenType feature `{t}` 不明な OpenType 機能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} には 0 より大きく {max} 以下の数値を指定してください +@msg {label} must be at most {max} characters {label} には {max} 文字以内で指定してください +@msg {label} must be one character {label} には 1 文字を指定してください +@msg at most {max} tab stops タブストップは {max} 個までです +@msg unknown align `{other}` 不明な揃え `{other}` @msg no character style `{name}` 文字スタイル `{name}` が見つかりません # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6246,6 +6403,12 @@ breakText Glyphs 字形 Delete the selected brushes? 選択したブラシを削除しますか? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? これらのブラシの 1 つ以上が線で使われています。それらの線からブラシを外して、ブラシを削除しますか? Remove Strokes 線を削除 + Place Brush Art ブラシのアートを配置 + Replace Brush Art ブラシのアートを置き換え + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? このブラシは線で使われています。新しいアートをそれらの線に適用しますか?それとも線をそのままにして、新しいアートを持つブラシのコピーを追加しますか? + Apply to Strokes 線に適用 + Leave Strokes 線を保持 +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` にはアートがありません (アートを持つのは散布ブラシ、アートブラシ、パターンブラシだけです) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 配置ツール Arrange in Grid… グリッドに配置… @@ -6441,6 +6604,11 @@ breakText Glyphs 字形 @msg only an exporter or an importer declares `extensions` `extensions` を宣言できるのは書き出しプラグインと読み込みプラグインだけです @msg an importer always gets an import's budget: leave `budget` out 読み込みプラグインには常に読み込みの予算が割り当てられます: `budget` は省略してください +# Copy Troubleshooting Info + Copy Troubleshooting Info トラブルシューティング情報をコピー +@msg Copied the troubleshooting info トラブルシューティング情報をコピーしました +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report 前回の VectorCraft のセッションは、閉じる前に応答しなくなりました。ヘルプ › トラブルシューティング情報をコピー で、バグ報告用の詳細をコピーできます + # Safe Mode Safe Mode… セーフモード… Safe Mode セーフモード @@ -6461,6 +6629,8 @@ breakText Glyphs 字形 # Align to Pixel Grid Align to Pixel Grid ピクセルグリッドに整合 + Align New Objects to Pixel Grid 新規オブジェクトをピクセルグリッドに整合 + Not Aligned to Pixel Grid ピクセルグリッドに未整合 @msg only paths and compound paths can be aligned to the pixel grid ピクセルグリッドに整合できるのはパスと複合パスのみです @msg side is left or right, not `{s}` side は left または right です(`{s}` ではありません) Ignore All すべて無視 @@ -6491,8 +6661,33 @@ breakText Glyphs 字形 @plural {n} line cut|{n} lines cut {n} 行を切り詰め @msg `first` and `last` must be numbers of lines the console holds, first before last `first` と `last` には、コンソールが保持している行の番号を、`first` が `last` より前になるよう指定してください +# Learn panel + Learn 学ぶ + Explore tutorials チュートリアルを見る + For you おすすめ + Skills スキル + Get started はじめに + Quick skill guide クイックスキルガイド + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. 基本ツールを学ぶ短い実践チュートリアルを、スキルごとにまとめています。スキルを選ぶとチュートリアルが表示されます。 + List Tutorials チュートリアルの一覧 + Show Tutorial チュートリアルを表示 +@msg missing `tutorial` (see learn.list) `tutorial` が指定されていません (learn.list を参照) +@msg unknown tutorial `{id}` (see learn.list) `{id}` は不明なチュートリアルです (learn.list を参照) + # Deferred plug-in effects Refresh Deferred Effects 保留中の効果を更新 Deferred Effects 保留中の効果 @msg no plug-in effect is deferred 保留中のプラグイン効果はありません @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. プラグイン効果を {n} 件保留して開きました。「効果 › 保留中の効果を更新」で実行します。 + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools カッティングツール + Stencil Bridges… ステンシルブリッジ… + Stencil Bridges ステンシルブリッジ + Shortest Crossing 最短の横断 + Direction 方向 +@msg The selected art has no islands to bridge 選択したアートワークにはブリッジでつなぐアイランドがありません +@msg No bridge of this width fits across the selected art この幅のブリッジは選択したアートワークに収まりません +@msg Some islands could not be joined to the area around the art 一部のアイランドをアートワークの周囲の領域につなげられませんでした +@msg `width` must be from {lo} to {hi} pt `width` は {lo}~{hi} pt の範囲で指定してください +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` には 1 から {MAX_BRIDGES_PER_ISLAND} の整数を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index bb6a5da7d9..516d9720ab 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -92,6 +92,7 @@ Spelling მართლწერა Auto Spell Check მართლწერის ავტომატური შემოწმება Check Spelling… მართლწერის შემოწმება… + Check Spelling მართლწერის შემოწმება Edit Custom Dictionary… მომხმარებლის ლექსიკონის რედაქტირება… Edit Colors ფერების რედაქტირება Recolor Artwork… ნახატის ხელახლა შეფერადება… @@ -116,6 +117,7 @@ PDF Presets… PDF-ის პრესეტები… Perspective Grid Presets… პერსპექტივის ბადის პრესეტები… Color Settings… ფერის პარამეტრები… + Assign Profile პროფილის მინიჭება Assign Profile… პროფილის მინიჭება… Keyboard Shortcuts… კლავიატურის მალსახმობები… Preferences… პარამეტრები… @@ -160,6 +162,15 @@ Expand… გაშლა… Expand Appearance იერსახის გაშლა Crop Image გამოსახულების ჩამოჭრა + Image Tools გამოსახულების ხელსაწყოები + Remove Background… ფონის მოშორება… + Remove Background ფონის მოშორება + Background ფონი + Edge Color კიდის ფერი + Picked Colors არჩეული ფერები + Corner Color კუთხეების ფერი + Contiguous მომიჯნავე + Each Channel თითოეული არხი Mask ნიღაბი Rasterize… რასტრირება… Create Gradient Mesh… გრადიენტული ბადის შექმნა… @@ -209,6 +220,10 @@ Blend Options… გადასვლის პარამეტრები… Expand გაშლა Replace Spine ხერხემლის ჩანაცვლება + Create Spine ხერხემლის შექმნა + Create Spine: ხერხემლის შექმნა: + Always ყოველთვის + Never არასოდეს Reverse Spine ხერხემლის შებრუნება Reverse Front to Back რიგის შებრუნება წინიდან უკან Envelope Distort გარსით დეფორმაცია @@ -316,6 +331,8 @@ Stair Step საფეხურები Gravity გრავიტაცია Type on a Path Options… ტრაექტორიაზე ტექსტის პარამეტრები… + Center on Top ზემოთ ცენტრში მოთავსება + Center on Bottom ქვემოთ ცენტრში მოთავსება Threaded Text დაკავშირებული ტექსტი Create შექმნა Release Selection მონიშნულის მოხსნა @@ -331,6 +348,15 @@ Smart Punctuation… ჭკვიანი პუნქტუაცია… Create Outlines კონტურებად გარდაქმნა Optical Margin Alignment ოპტიკური არშიის სწორება + Dynamic Text დინამიკური ტექსტი + Dynamic Text Presets დინამიკური ტექსტის წინასწარი პარამეტრები + Arch თაღი +@msg select point type or type on a path აირჩიეთ წერტილოვანი ტექსტი ან ტრაექტორიაზე ტექსტი +@msg type on a path in a thread cannot use Dynamic Text: {frames} დაკავშირებულ ტექსტში ტრაექტორიაზე ტექსტი ვერ გამოიყენებს დინამიკურ ტექსტს: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} ღია ან შედგენილ ტრაექტორიაზე ტექსტი ვერ მოთავსდება ზემოთ ან ქვემოთ ცენტრში: {open} +@msg type on a path with no length or no height cannot be centered: {flat} ტექსტი ვერ მოთავსდება ცენტრში ტრაექტორიაზე, რომელსაც არ აქვს სიგრძე ან სიმაღლე: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} დაკავშირებულ ტექსტში ტრაექტორიაზე ტექსტი ვერ მოთავსდება ზემოთ ან ქვემოთ ცენტრში: {frames} +@msg select type on a closed path მონიშნეთ დახურულ ტრაექტორიაზე ტექსტი Fill with Placeholder Text შემავსებელი ტექსტით შევსება Insert Inline Symbol ჩადგმული სიმბოლოს ჩასმა Show Hidden Characters დამალული სიმბოლოების ჩვენება @@ -362,6 +388,8 @@ Stroke Pattern კონტურის პატერნი Patterns პატერნები Stroke Weight კონტურის სისქე + Stroke Weight Up კონტურის სისქის გაზრდა + Stroke Weight Down კონტურის სისქის შემცირება Graphic Style გრაფიკული სტილი Symbol Instance სიმბოლოს ეგზემპლარი Link Block Series დაკავშირებული ბლოკების სერია @@ -400,6 +428,8 @@ Extrude & Bevel… ამოწევა და წაკვეთა… 3D (Classic) 3D (კლასიკური) Extrude & Bevel (Classic)… ამოწევა და წაკვეთა (კლასიკური)… + Revolve (Classic)… ბრუნვა (კლასიკური)… + Rotate (Classic)… შემობრუნება (კლასიკური)… Surface ზედაპირი Wireframe მავთულის ჩარჩო No Shading დაჩრდილვის გარეშე @@ -451,6 +481,13 @@ Feather… კიდეების შერბილება… SVG Filters SVG ფილტრები Apply SVG Filter… SVG ფილტრის გამოყენება… + Apply SVG Filter SVG ფილტრის გამოყენება + SVG Filter SVG ფილტრი + New SVG Filter ახალი SVG ფილტრი + Edit SVG Filter SVG ფილტრის რედაქტირება + Delete SVG Filter SVG ფილტრის წაშლა + Import SVG Filter SVG ფილტრის იმპორტირება + Import SVG Filter… SVG ფილტრის იმპორტირება… Warp გაღუნვა Arc… რკალი… Arc Lower… ქვედა რკალი… @@ -470,6 +507,7 @@ Gaussian Blur… გაუსის გაბუნდოვნება… View ხედი Preview წინასწარი ნახვა + Preview: წინასწარი ნახვა: Overprint Preview ზედდაბეჭდვის წინასწარი ნახვა Pixel Preview პიქსელების წინასწარი ნახვა Trim View მოჭრილი ხედი @@ -677,8 +715,25 @@ Stun Pulse დაბნეულობა Stealth Fade შენიღბვა Shield Buff ფარი + Textures ტექსტურები + Fine Grain წვრილი მარცვალი + Canvas Weave ტილოს ქსოვილი + Burlap Sack ჯუთის ტომარა + Cracked Glaze დამსკდარი მინანქარი + Mosaic Floor მოზაიკის იატაკი + Quilted Squares ქვილთის კვადრატები + Leaded Glass ტყვიის მინა + Damp Paper ნესტიანი ქაღალდი Outlines and Rules კონტურები და ხაზები Hand-Drawn ხელით დახატული + Painted and Sketched დახატული და ესკიზური + Washed Blue გარეცხილი ლურჯი + Bristle Ochre ფუნჯის ოხრა + Pastel Heather პასტელის იისფერი + Charcoal Shade ნახშირის ჩრდილი + Ink Contour მელნის კონტური + Wet Ink სველი მელანი + Fine Pen წვრილი კალამი Gradient Finishes გრადიენტული ზედაპირები Shape Effects ფიგურის ეფექტები Blends and Transparency გადასვლები და გამჭვირვალობა @@ -698,6 +753,8 @@ Spectrum Gradients სპექტრის გრადიენტები Sky Gradients ცის გრადიენტები Neutral Gradients ნეიტრალური გრადიენტები + Organic Fades ორგანული გაქრობები + Holographic ჰოლოგრაფიული Duotone Gradients ორტონიანი გრადიენტები Radial Glows რადიალური ნათებები Save Swatch Library… ფერის ნიმუშების ბიბლიოთეკის შენახვა… @@ -755,6 +812,13 @@ Dock Panel პანელის მიმაგრება Dock to Top ზემოთ მიმაგრება Dock to Bottom ქვემოთ მიმაგრება + Control Bar Options მართვის ზოლის პარამეტრები + Tool Options ხელსაწყოს პარამეტრები + Object Options ობიექტის პარამეტრები + Image Options გამოსახულების პარამეტრები + Vertical Alignment ვერტიკალური სწორება + Align and Distribute სწორება და განაწილება + Document Options დოკუმენტის პარამეტრები Dock Control Bar მართვის ზოლის მიმაგრება Float Tool Group მცურავი ხელსაწყოთა ჯგუფი Services სერვისები @@ -1029,6 +1093,8 @@ lighting Light სინათლე Toolbar: Single/Double Column ხელსაწყოთა ზოლი: ერთი/ორი სვეტი Toolbar: Add Tool ხელსაწყოთა ზოლი: ხელსაწყოს დამატება Toolbar: Remove Tool ხელსაწყოთა ზოლი: ხელსაწყოს ამოშლა + Add Tool… ხელსაწყოს დამატება… + Remove Tool ხელსაწყოს ამოშლა Toolbar: Reset ხელსაწყოთა ზოლი: ჩამოყრა Two Point Perspective Preset 1 ორწერტილიანი პერსპექტივის პრესეტი 1 Two Point Perspective Preset 2 ორწერტილიანი პერსპექტივის პრესეტი 2 @@ -1384,6 +1450,7 @@ digits Malayalam მალაიალამური Roman Baseline ლათინური საბაზისო ხაზი Select a text object to edit its character attributes. სიმბოლოების ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. Show Options პარამეტრების ჩვენება + Show Recent Colors ბოლოდროინდელი ფერების ჩვენება Small Caps პატარა მთავრული Small Caps (on the roadmap) პატარა მთავრული (სამომავლო გეგმაშია) Standard Vertical Roman Alignment სტანდარტული ვერტიკალური ლათინური სწორება @@ -1411,6 +1478,8 @@ digits Malayalam მალაიალამური Scale at Center ცენტრიდან მასშტაბირება Up/Down: ზემოთ/ქვემოთ: Left/Right: მარცხნივ/მარჯვნივ: + Tate-chu-yoko Up/Down Tate-chu-yoko ზემოთ/ქვემოთ + Tate-chu-yoko Left/Right Tate-chu-yoko მარცხნივ/მარჯვნივ Underline ხაზგასმული Vertical Scale % ვერტიკალური მასშტაბი % Axis ღერძი @@ -1513,8 +1582,17 @@ digits Malayalam მალაიალამური No gradient swatches გრადიენტის ნიმუშები არ არის Points: clicks add free points წერტილები: დაწკაპუნებები ამატებს თავისუფალ წერტილებს Radial Gradient რადიალური გრადიენტი + Conic Gradient კონუსური გრადიენტი + Diamond Gradient რომბული გრადიენტი Reset to White, Black თეთრზე და შავზე დაბრუნება Reverse Gradient გრადიენტის შებრუნება + Gradient Presets გრადიენტის პრესეტები + Apply Gradient Preset გრადიენტის პრესეტის გამოყენება + Save Gradient Preset გრადიენტის პრესეტის შენახვა + Save Gradient Preset… გრადიენტის პრესეტის შენახვა… + Delete Gradient Preset გრადიენტის პრესეტის წაშლა + Show Presets პრესეტების ჩვენება + Hide Presets პრესეტების დამალვა Save to Swatches ფერის ნიმუშებში შენახვა Delete Graphic Style (Alt-click: without asking) გრაფიკული სტილის წაშლა (Alt-დაწკაპუნებით: დაუკითხავად) Delete the graphic style “{name}”? წაიშალოს გრაფიკული სტილი „{name}“? @@ -1553,6 +1631,7 @@ digits Malayalam მალაიალამური Rename Preset პრესეტის სახელის შეცვლა Save Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის შენახვა Delete Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის წაშლა + Cancel Image Trace გამოსახულების ვექტორიზაციის გაუქმება Method: მეთოდი: Mode: რეჟიმი: Noise ხმაური @@ -1676,6 +1755,9 @@ digits Malayalam მალაიალამური Right Indent მარჯვენა შეწევა Right-to-Left Paragraph Direction აბზაცის მიმართულება მარჯვნიდან მარცხნივ Roman Hanging Punctuation ლათინური გამოწეული პუნქტუაცია + Korean Line Break Anywhere კორეული სტრიქონის გადატანა ნებისმიერ ადგილას + East Asian Composition Settings აღმოსავლეთ აზიური აწყობის პარამეტრები + Korean Composition Settings კორეული აწყობის პარამეტრები Select a text object to edit its paragraph attributes. აბზაცის ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. Single-line Composer სტრიქონის მიხედვით აწყობა Toggle Line Composer აწყობის რეჟიმის გადართვა @@ -1762,6 +1844,7 @@ digits Malayalam მალაიალამური Simulate Paper ქაღალდის იმიტაცია Use Black Point Compensation შავი წერტილის კომპენსაციის გამოყენება Working CMYK (don't tag) სამუშაო CMYK (ტეგის გარეშე) + Working RGB (don't tag) სამუშაო RGB (ტეგის გარეშე) {name} (spot) {name} (სპოტ) Add to Profiles… პროფილებში დამატება… Align Stroke to Center კონტურის ცენტრზე სწორება @@ -2058,6 +2141,8 @@ digits Malayalam მალაიალამური Export Selected Art Only მხოლოდ მონიშნული ნახატის ექსპორტირება Number of Colors: ფერების რაოდენობა: Raster File Format: რასტრული ფაილის ფორმატი: + Include Placed Images განთავსებული გამოსახულებების ჩართვა + Include Fill Hatches შევსებების დაშტრიხვის ჩართვა True colour needs version 2004 or later: the nearest of 256 colours is written. სრულ ფერს სჭირდება 2004 ან უფრო ახალი ვერსია: იწერება 256 ფერიდან უახლოესი. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. ტექსტი კონტურებად იქცევა, ხოლო ის კონტურები, რომლებსაც CAD-ხაზი ვერ ხატავს, შევსებულ ფიგურებად. Type stays text, and every stroke is a line with its lineweight and dashes. ტექსტი ტექსტად რჩება, ყოველი კონტური კი ხაზია თავისი სისქითა და ტირეებით. @@ -2572,6 +2657,7 @@ antiAlias Sharp მკვეთრი General › Thumbnails ზოგადი › ესკიზები Grayscale images ნაცრისფერი გამოსახულებები Include non-printing layers არაბეჭდვადი შრეების ჩართვა + Write pages longer than 200 in at full size in points 200 in-ზე გრძელი გვერდების სრული ზომით, პუნქტებში ჩაწერა Left: მარცხნივ: Mark as trapped ტრაპინგის მარკირება Marks and Bleeds ნიშნები და ჭრისპირა არეები @@ -2946,6 +3032,7 @@ theme Appearance იერსახე Reshape Segment სეგმენტის ფორმის შეცვლა Split Path ტრაექტორიის გაყოფა Activate Document დოკუმენტის გააქტიურება + Move Document დოკუმენტის გადატანა Delete წაშლა Document JSON დოკუმენტის JSON Duplicate დუბლირება @@ -2961,6 +3048,8 @@ theme Appearance იერსახე Effects ეფექტები Move Effect ეფექტის გადატანა Remove Effect ეფექტის წაშლა + Duplicate Effects ეფექტების დუბლირება + Remove Effects ეფექტების წაშლა Expand Options გაშლის პარამეტრები File Info ფაილის ინფორმაცია Batch პაკეტური დამუშავება @@ -3364,6 +3453,7 @@ theme Appearance იერსახე Use Japanese Crop Marks იაპონური ჭრის ნიშნების გამოყენება Use Low Resolution Proxy for Linked EPS დაბალი გარჩევადობის პროქსის გამოყენება დაკავშირებული EPS-ისთვის Use Precise Cursors ზუსტი კურსორების გამოყენება + Caps Lock Cursor State Caps Lock-ის მდგომარეობა (კურსორი) Use Preview Bounds გადახედვის საზღვრების გამოყენება When pasting text ტექსტის ჩასმისას XML ID XML ID @@ -3520,6 +3610,8 @@ axis Both ორივე List Folder საქაღალდის სია Area Type Options არის ტექსტის პარამეტრები Reshape Type Area ტექსტის არის ფორმის შეცვლა + Reshape Type Path ტექსტის ტრაექტორიის ფორმის შეცვლა + Move Type Path Handle ტექსტის ტრაექტორიის სახელურის გადაადგილება Scale მასშტაბი Feet & Inches ფუტები და დუიმები Pixels პიქსელები @@ -3765,6 +3857,7 @@ font-technology Variable ცვლადი Flip არეკვლა Couldn't {} {name}: {e} ვერ მოხერხდა {}: {name}: {e} Delete Character Style სიმბოლოს სტილის წაშლა + Edit Character Style სიმბოლოს სტილის რედაქტირება Delete Layer შრის წაშლა Delete Paragraph Style აბზაცის სტილის წაშლა Duplicate Character Style სიმბოლოს სტილის დუბლირება @@ -3954,10 +4047,13 @@ font-technology Variable ცვლადი @msg `groupColors` must be an array `groupColors` უნდა იყოს მასივი @msg `library` is a library id or name (see {list}) `library` არის ბიბლიოთეკის id ან სახელი (იხ. {list}) @msg `mode` applies to freeform gradients `mode` ეხება თავისუფალი ფორმის გრადიენტებს +@msg a negative `aspect` applies to conic gradients უარყოფითი `aspect` ეხება კონუსურ გრადიენტებს +@msg `focal` applies to radial gradients `focal` ეხება რადიალურ გრადიენტებს @msg `preserve` must be an object `preserve` უნდა იყოს ობიექტი @msg `globalAdjust` must be an object `globalAdjust` უნდა იყოს ობიექტი @msg `sampleSize` must be 1, 3 or 5 `sampleSize` უნდა იყოს 1, 3 ან 5 @msg `stops` must be an array `stops` უნდა იყოს მასივი +@msg `{key}` must be an array `{key}` უნდა იყოს მასივი @msg `svg` must be an object of SVG options (see document.formats) `svg` უნდა იყოს SVG-ის პარამეტრების ობიექტი (იხ. document.formats) @msg `{_1}` is no save command `{_1}` შენახვის ბრძანება არ არის @msg `{area}` is no recovery area name `{area}` აღდგენის არის სახელი არ არის @@ -3970,6 +4066,7 @@ font-technology Variable ცვლადი @msg `{key}` must be a number, not {v} `{key}` უნდა იყოს რიცხვი და არა {v} @msg {key} must be Unix seconds (an integer) or null {key} უნდა იყოს Unix-დრო წამებში (მთელი რიცხვი) ან null @msg `{key}` must be a string `{key}` უნდა იყოს სტრიქონი +@msg `{key}` must be a profile name or null `{key}` უნდა იყოს პროფილის სახელი ან null @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 between {min} and {max} (got {x}) `{key}` უნდა იყოს {min}-სა და {max}-ს შორის (მიღებულია {x}) @@ -4110,6 +4207,7 @@ font-technology Variable ცვლადი @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller სამუშაო დაფა {n}-ის გვერდი არის {size}, რაც აღემატება PDF-ის გვერდის ლიმიტს 14 400 pt (200 in): ის იწერება UserUnit {unit}-ით, ამიტომ აპები, რომლებიც UserUnit-ს უგულებელყოფენ, მას ამდენჯერ პატარას აჩვენებენ @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in სამუშაო დაფა {n}-ის გვერდი არის {size}, რაც აღემატება PDF-ის გვერდის ლიმიტს 14 400 pt (200 in): {label} გვერდები იწერება UserUnit-ის გარეშე, პუნქტებში, და აპები, რომლებიც ლიმიტს იცავენ, გვერდს 200 in-ზე ჭრიან @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5-ს არ აქვს UserUnit, რომელიც 14 400 pt-ზე (200 in) გრძელ გვერდს ზომის შესანარჩუნებლად სჭირდება: ფაილი იწერება როგორც PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4-ს არ აქვს UserUnit, რომელიც 14 400 pt-ზე (200 in) გრძელ გვერდს PDF/A-2-ის 14 400 ერთეულიანი გვერდის ზღვარში დასარჩენად სჭირდება: ფაილი იწერება როგორც PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units სამუშაო დაფა {n}-ის გვერდი არის {size}, ძალიან გრძელი და ვიწრო PDF-ის 3-დან 14 400 ერთეულამდე გვერდის მხარეებისთვის: ის იწერება UserUnit {unit}-ით, რომელიც მოკლე მხარეს 3 ერთეულზე ან მეტზე ინარჩუნებს, ხოლო ზღვრის დამცველი აპები გრძელ მხარეს 14 400 ერთეულამდე ჭრიან @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} ფაილები ინახავს ნამდვილ რიცხვებს {max}-მდე, სამუშაო დაფა {n}-ის {side} pt სიგრძის გვერდს კი უფრო დიდი სჭირდება: აირჩიეთ PDF 1.6 ან უფრო ახალი PDF/X სტანდარტის გარეშე, ან უფრო პატარა სამუშაო დაფა @msg invalid image data for `{0}` არასწორი გამოსახულების მონაცემები `{0}`-სთვის @@ -4249,6 +4347,8 @@ font-technology Variable ცვლადი @msg not a stored central record ეს არ არის შენახული ცენტრალური ჩანაწერი @msg not a valid plug-in module: {0} ეს არ არის პლაგინის სწორი მოდული: {0} @msg not an EMF or WMF file ეს არ არის EMF ან WMF ფაილი +@msg not an HP-GL file ეს არ არის HP-GL ფაილი +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` უნდა იყოს 1-დან 255-მდე #rrggbb ფერის მასივი @msg not found ვერ მოიძებნა @msg not in pattern editing mode პატერნის რედაქტირების რეჟიმი არ არის ჩართული @msg finish editing the pattern first ჯერ დაასრულეთ პატერნის რედაქტირება @@ -4316,6 +4416,14 @@ font-technology Variable ცვლადი @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}-ზე მეტ საყრდენ წერტილს შექმნიდა, რასაც დოკუმენტი შეუფერხებლად ვერ აჩვენებს: გაზარდეთ ხმაური, შეამცირეთ ტრაექტორიები ან ფერები, ან აირჩიეთ ნაკლები სიზუსტის პრესეტი @msg select an envelope მონიშნეთ გარსი @msg select an image მონიშნეთ გამოსახულება +@msg `background` must be edges, corners or colors `background` უნდა იყოს edges, corners ან colors +@msg `match` must be distance or channels `match` უნდა იყოს distance ან channels +@msg `{key}` must be from 0 to 100 `{key}` უნდა იყოს 0-დან 100-მდე +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` უნდა შეიცავდეს 1-დან 16-მდე ფერს, თითოეულს თექვსმეტობით ფორმატში (#rrggbb ან #rgb) ან როგორც black, white, red, green ან blue +@msg the linked image shows its preview: embed or relink it first დაკავშირებული გამოსახულება გადახედვას აჩვენებს: ჯერ ჩააშენეთ ან ხელახლა მიაბით +@msg a CMYK image has no transparency to set CMYK გამოსახულებას არ აქვს დასაყენებელი გამჭვირვალობა +@msg every pixel matches the background: no image would be left ყველა პიქსელი ემთხვევა ფონს: გამოსახულება აღარ დარჩებოდა +@msg an image of {w} × {h} pixels is too large to change {w} × {h} პიქსელის გამოსახულება შესაცვლელად ზედმეტად დიდია @msg select an object in perspective მონიშნეთ ობიექტი პერსპექტივაში @msg select artwork (or a colour group) to recolor მონიშნეთ ხელახლა შესაფერადებელი ნახატი (ან ფერთა ჯგუფი) @msg Recolor completed; {locked} and {hidden} were left unchanged ხელახლა შეფერადება დასრულდა; უცვლელი დარჩა: {locked} და {hidden} @@ -4419,7 +4527,7 @@ font-technology Variable ცვლადი @msg unknown format უცნობი ფორმატი @msg unknown format `{f}` (Save writes {_1}) უცნობი ფორმატი `{f}` (შენახვა წერს: {_1}) @msg unknown freeform mode `{m}` (points, lines) უცნობი თავისუფალი რეჟიმი `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) უცნობი გრადიენტის სახე `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) უცნობი გრადიენტის სახე `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` უცნობი გამოკვეთა `{h}` @msg unknown option `{path}.{k}` უცნობი პარამეტრი `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) უცნობი ზედდაბეჭდვა `{o}` (preserve, simulate ან discard) @@ -4599,6 +4707,8 @@ font-technology Variable ცვლადი @msg invalid object id {value}: expected a non-negative integer ობიექტის არასწორი id {value}: მოსალოდნელია არაუარყოფითი მთელი რიცხვი @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}`-ის ელემენტი {index} არის {value} და არა ობიექტის id (არაუარყოფითი მთელი რიცხვი) @msg no such object id {value} ობიექტი id-ით {value} არ არსებობს +@msg id {value} is a ruler guide, not an object id {value} დამხმარე ხაზისაა და არა ობიექტის +@msg a ruler guide goes only directly in a layer or sublayer დამხმარე ხაზი შეიძლება იყოს მხოლოდ უშუალოდ შრეში ან ქვეშრეში @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} შრეა და არა ობიექტი; შრეების გადასატანად გამოიყენეთ layer.move @msg automation filesystem access is not granted: read authority is absent: {path} ავტომატიზაციას ფაილურ სისტემაზე წვდომა არ აქვს: წაკითხვის უფლება არ არის: {path} @@ -4628,7 +4738,13 @@ font-technology Variable ცვლადი @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC ან HEIF ფაილი შეიცავს გამოსახულების ტიპს, რომლის წაკითხვაც შეუძლებელია @msg HEIC and HEIF images can't be opened in this build ამ ვერსიაში HEIC და HEIF გამოსახულებების გახსნა შეუძლებელია @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD გამოსახულება ზედმეტად დიდია წასაკითხად ({_1} × {_2} პიქსელი) -@msg zipped 32-bit PSD image data with prediction can't be read zip-ით შეკუმშული 32-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება +@msg zipped 1-bit PSD image data with prediction can't be read zip-ით შეკუმშული 1-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება +@msg the PSD file's layer data uses an unknown compression ({m}) PSD ფაილის შრეების მონაცემები უცნობ შეკუმშვას იყენებს ({m}) +@msg the PSD file's layer records are damaged PSD ფაილის შრეების ჩანაწერები დაზიანებულია +@msg the PSD file's layer groups are nested too deeply PSD ფაილის შრეების ჯგუფები ზედმეტად ღრმადაა ჩადგმული +@msg a layer of the PSD file is too large to read PSD ფაილის შრე ზედმეტად დიდია წასაკითხად +@msg the PSD file's layers take more memory to read than allowed PSD ფაილის შრეების წასაკითხად დაშვებულზე მეტი მეხსიერებაა საჭირო +@msg the layers can't be read ({e}): the file opened as its merged image შრეების წაკითხვა ვერ ხერხდება ({e}): ფაილი გაიხსნა როგორც მისი გაერთიანებული გამოსახულება @msg {depth}-bit PSD files in this colour mode can't be read ამ ფერის რეჟიმში {depth}-ბიტიანი PSD ფაილების წაკითხვა ვერ ხერხდება @msg the PSD file is cut short PSD ფაილი შეკვეცილია @msg the PSD file's header is damaged PSD ფაილის სათაური დაზიანებულია @@ -5183,6 +5299,7 @@ mark-style Japanese იაპონური imageTrace Outline კონტური Run გაშვება Run Script სკრიპტის გაშვება + List Installed Scripts დაინსტალირებული სკრიპტების სია Stop Script სკრიპტის შეჩერება Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს @@ -5204,7 +5321,7 @@ imageTrace Outline კონტური Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი -@msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ შეცვალა გაუქმების ნაბიჯები, რომელთა აღდგენა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა +@msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ დაბრუნების ნაბიჯები შეცვალა და მათი პირვანდელ მდგომარეობაში მოყვანა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა @msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში @@ -5240,6 +5357,11 @@ imageTrace Outline კონტური In the File ფაილში Keys კლავიშები Light behind the object სინათლე ობიექტის უკან + Shadows ჩრდილები + Distance from Object მანძილი ობიექტიდან + Shadow Bounds ჩრდილის საზღვრები + Behind Object ობიექტის უკან + Below Object ობიექტის ქვეშ 3D Lighting Preset 3D განათების წინასწარი პარამეტრი Standard სტანდარტული Diffuse დიფუზური @@ -5406,7 +5528,7 @@ imageTrace Outline კონტური @msg span must be "object" or "selection", got {v} span უნდა იყოს "object" ან "selection", მიღებულია {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 span: "selection" ათავსებს წრფივ ან რადიალურ გრადიენტს და არა თავისუფალი ფორმისას +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" ათავსებს წრფივ, რადიალურ, კონუსურ ან რომბულ გრადიენტს და არა თავისუფალი ფორმისას @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" თავად ათავსებს გრადიენტს: გამოტოვეთ `start` და `end` (ისინი მას უკვე დოკუმენტის კოორდინატებში ათავსებენ) Make Image Dynamic გამოსახულების დინამიკურად ქცევა Import Data Sets… მონაცემთა ნაკრებების იმპორტი… @@ -5722,7 +5844,7 @@ imageTrace Outline კონტური @msg Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds. ბრტყელი ლოგოს რეჟიმი keepColors-ს არ იყენებს: ის ვექტორიზებს logoColors-ში მითითებულ ფერებს ან მის მიერ ნაპოვნ ფერებს. @msg Nothing was traced: none of the colors the trace found matches keepColors ({_1}). არაფერი ვექტორიზდა: ვექტორიზაციის მიერ ნაპოვნი არცერთი ფერი არ შეესაბამება keepColors-ს ({_1}). @msg Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists. არაფერი ვექტორიზდა: ფერის იგნორირება გამოტოვებს keepColors-ში ჩამოთვლილი ფერების ყველა არეს. -@msg Nothing was traced: the colors that match keepColors produce no paths. არაფერი ვექტორიზდა: keepColors-ის შესაბამისი ფერებიდან არცერთი კონტური არ მიიღება. +@msg Nothing was traced: the colors that match keepColors produce no paths. არაფერი ვექტორიზდა: keepColors-ის შესაბამისი ფერებიდან არცერთი ტრაექტორია არ მიიღება. @msg keepColors: none of the colors the trace found matches {c}, so nothing of it is traced. keepColors: ვექტორიზაციის მიერ ნაპოვნი არცერთი ფერი არ შეესაბამება {c}-ს, ამიტომ მისგან არაფერი ვექტორიზდება. @msg `colorGroup` needs `library: "document"` `colorGroup`-ს სჭირდება `library: "document"` @msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup`-ს სჭირდება `palette: "documentLibrary"` @@ -5776,6 +5898,8 @@ imageTrace Outline კონტური Clear History ისტორიის გასუფთავება New Document from State ახალი დოკუმენტი მდგომარეობიდან Continue in Background ფონურ რეჟიმში გაგრძელება + Cancel Opening გახსნის გაუქმება + Reading the file… ფაილი იკითხება… Artboard {n} of {total} სამუშაო დაფა {n} / {total} File {n} of {total} ფაილი {n} / {total} Auto Leading: ავტომატური სტრიქონთა დაშორება: @@ -5863,6 +5987,7 @@ imageTrace Outline კონტური Ruby რუბი Geometric Guides გეომეტრიული მიმმართველები Geometric Patterns გეომეტრიული პატერნები + Grit Textures მარცვლოვანი ტექსტურები Ease In ნელი დასაწყისი Ease Out ნელი დასასრული Ease In Out ნელი დასაწყისი და დასასრული @@ -5932,6 +6057,8 @@ axis Y Axis Y ღერძი Version: {version} ვერსია: {version} Install “{name}” in place of the plug-in with the same ID? დავაყენოთ „{name}“ იმავე ID-ის მქონე პლაგინის ნაცვლად? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. ეს ფაილი არ არის ამ ID-ით ადრე დაყენებული პლაგინი. ის მიიღებს ამ ID-სთვის შენახულ პარამეტრებს და ქეშს. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. ავტომატიზაციამ ამ პლაგინის დაყენება მოითხოვა. მის დასაყენებლად აირჩიეთ ობიექტი › პლაგინები › პლაგინის დაყენება… თავად. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. ავტომატიზაციამ ამ პლაგინის დაყენება მოითხოვა. მის დასაყენებლად აირჩიეთ ობიექტი › პლაგინები › პლაგინის დაყენება… თავად. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}“ სხვა მოდულია, ვიდრე პლაგინი ID-ით {_1}, და მიიღებდა მისთვის შენახულ პარამეტრებს და ქეშს: მომხმარებლის თანხმობის შემდეგ დააყენეთ ის `replace: true` პარამეტრით File SHA-256: {hash} ფაილის SHA-256: {hash} Read the objects it is given მიღებული ობიექტების წაკითხვა @@ -5977,6 +6104,11 @@ axis Y Axis Y ღერძი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) მეხსიერების ბიუჯეტი (ობიექტს {_1} სჭირდება შეყვანის {size} ბაიტი, დარჩენილია {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) ობიექტების ბიუჯეტი ({MAX_OBJECTS}-ზე მეტი მხოლოდ წასაკითხი ობიექტი) +@msg instruction budget ინსტრუქციების ბიუჯეტი +@msg time budget დროის ბიუჯეტი +@msg memory budget (the selection is too large to hand over) მეხსიერების ბიუჯეტი (მონიშნული ზედმეტად დიდია გადასაცემად) +@msg output size ({what} is {len} bytes, limit {max}) გამოტანის ზომა ({what}: {len} ბაიტი, ლიმიტი {max}) +@msg the plug-in's grant can't be removed from the plug-in store პლაგინის ნებართვის წაშლა პლაგინების საცავიდან შეუძლებელია @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it ნებართვა `{shown}` დაჯავშნილია პლაგინების მომავალი API-სთვის; ეს ჰოსტი მას არ გასცემს @msg unknown permission `{shown}` უცნობი ნებართვა `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ ითხოვს ნებართვებს {asked}: ისინი დესკტოპის აპში ადამიანმა უნდა დაამტკიცოს, ან გადაეცით `grant` --allow-plugin-grants-ით გაშვებულ სესიაში @@ -5989,6 +6121,12 @@ axis Y Axis Y ღერძი @msg command {name}: `label` must be 1-64 printable characters ბრძანება {name}: `label` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ბრძანება {name}: გამოიყენეთ 1-{MAX_COMMAND_ID} სიმბოლოიანი id a-z 0-9 _ სიმბოლოებიდან, რომელიც ასოთი იწყება @msg command {name}: {e} ბრძანება {name}: {e} +@msg manifest: {e} მანიფესტი: {e} +@msg manifest: {e} at line {line} column {column} მანიფესტი: {e} (სტრიქონი {line}, სვეტი {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` უნდა იყოს ბრძანებების სია, თითოეული `id`-ით და `label`-ით +@msg command {name} must be an object with an `id` and a `label` ბრძანება {name} უნდა იყოს ობიექტი `id`-ით და `label`-ით +@msg missing field `{key}` აკლია ველი `{key}` +@msg duplicate field `{key}` ველი `{key}` ორჯერაა @msg only a filter or a live effect declares `commands` `commands`-ს მხოლოდ ფილტრი ან ცოცხალი ეფექტი აცხადებს @msg “{name}” › {label}: {e} „{name}“ › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed მოდულს არ აქვს `hash`-ში მითითებული SHA-256: არაფერი დაყენებულა @@ -6013,6 +6151,16 @@ axis Y Axis Y ღერძი @msg message must be text message უნდა იყოს ტექსტი @msg allowContinue must be true or false allowContinue უნდა იყოს true ან false @msg Batch cannot play an action with a stop პაკეტურ დამუშავებას არ შეუძლია გაჩერების მქონე მოქმედების შესრულება + Insert Menu Item… მენიუს ელემენტის ჩასმა… + Insert Menu Item მენიუს ელემენტის ჩასმა + Menu Item: მენიუს ელემენტი: + No menu item matches. მენიუს არცერთი ელემენტი არ ემთხვევა. + Several menu items match. Choose one from the list. ემთხვევა მენიუს რამდენიმე ელემენტი. აირჩიეთ ერთი სიიდან. + Items that open a dialog, and File, Window and Help menu items, are not listed. დიალოგის გამხსნელი ელემენტები და მენიუების „ფაილი“, „ფანჯარა“ და „დახმარება“ ელემენტები სიაში არ არის. +@msg command must be text command უნდა იყოს ტექსტი +@msg no menu item that can be inserted runs this command ჩასმადი მენიუს არცერთი ელემენტი არ უშვებს ამ ბრძანებას +@msg the action already has 10,000 steps მოქმედებას უკვე 10 000 ნაბიჯი აქვს +@msg the action set would be larger than 8 MiB მოქმედებების ნაკრები 8 MiB-ზე დიდი გახდებოდა Playback Options შესრულების პარამეტრები Accelerated დაჩქარებული Step by Step ნაბიჯ-ნაბიჯ @@ -6051,6 +6199,12 @@ axis Y Axis Y ღერძი Crosshair სამიზნე Checkpoint საკონტროლო წერტილი Inventory Icons ინვენტარის ხატულები + Skill Icons უნარების ხატულები + Attack შეტევა + Defend თავდაცვა + Heal განკურნება + Buff გაძლიერება + Ult ულტი Sword მახვილი Shield ფარი Potion წამალი @@ -6115,7 +6269,23 @@ axis Y Axis Y ღერძი Dash Trail წყვეტილი კვალი Speed Line სიჩქარის ხაზი Game Trails თამაშის კვალი + Energy Beams ენერგიის სხივები + Laser Bolt ლაზერული ჭავლი + Plasma Arc პლაზმის რკალი + Charge Wave მუხტის ტალღა + Spark Trail ნაპერწკლის კვალი Calligraphic Nibs კალიგრაფიული წვერები + Bristle Brushes ჯაგრის ფუნჯები + Fine Liner წვრილი ხაზი + Pointed Flat წაწვეტებული ბრტყელი + Stubby Round მოკლე მრგვალი + Dry Scrub მშრალი ხეხვა + Soft Dome რბილი გუმბათი + Filbert ოვალური ბრტყელი + Angled Round დახრილი მრგვალი + Angled Flat დახრილი ბრტყელი + Fan Blender შერევის მარაო + Grass Fan ბალახის მარაო Pattern Borders პატერნის ბორდიურები Scatter Shapes გაბნეული ფიგურები Save Brush Library… ფუნჯების ბიბლიოთეკის შენახვა… @@ -6325,6 +6495,7 @@ anchor Points: წერტილები: Parametric Shape Tool პარამეტრული ფიგურის ხელსაწყო Parametric Shape პარამეტრული ფიგურა Edit Parametric Shape პარამეტრული ფიგურის რედაქტირება + Configure Shape ფიგურის პარამეტრების შეცვლა Convert to Parametric Shape პარამეტრულ ფიგურად გარდაქმნა Ring რგოლი Heart გული @@ -6386,9 +6557,12 @@ anchor Points: წერტილები: @msg {label} must be a number {label} უნდა იყოს რიცხვი @msg {label} must be a number of at least 0.1 {label} უნდა იყოს მინიმუმ 0,1 Advanced Character Formats სიმბოლოს დამატებითი ფორმატები + Basic Paragraph Formats აბზაცის ძირითადი ფორმატები + Composition კომპოზიცია Horizontal Scale ჰორიზონტალური მასშტაბი Vertical Scale ვერტიკალური მასშტაბი @msg {label} must be a number from {min} to {max} {label} უნდა იყოს რიცხვი {min}-დან {max}-მდე +@msg {label} must be a whole number from {min} to {max} {label} უნდა იყოს მთელი რიცხვი {min}-დან {max}-მდე Character Color სიმბოლოს ფერი OpenType Features OpenType შესაძლებლობები Stylistic Sets სტილისტური ნაკრებები @@ -6396,6 +6570,10 @@ anchor Points: წერტილები: @msg features lists at most {max} tags features შეიძლება შეიცავდეს არაუმეტეს {max} ტეგს @msg unknown OpenType feature `{t}` უცნობი OpenType შესაძლებლობა `{t}` @msg {label} must be a number above 0 and at most {max} {label} უნდა იყოს 0-ზე მეტი და არაუმეტეს {max}-ისა რიცხვი +@msg {label} must be at most {max} characters {label} უნდა შეიცავდეს არაუმეტეს {max} სიმბოლოს +@msg {label} must be one character {label} უნდა იყოს ერთი სიმბოლო +@msg at most {max} tab stops არაუმეტეს {max} ტაბულაციის გაჩერება +@msg unknown align `{other}` უცნობი სწორება `{other}` @msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6557,6 +6735,12 @@ breakText Glyphs გლიფები Delete the selected brushes? წაიშალოს არჩეული ფუნჯები? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? კონტურები იყენებს ამ ფუნჯებიდან ერთს ან მეტს. მოიხსნას ფუნჯები ამ კონტურებიდან და წაიშალოს ფუნჯები? Remove Strokes კონტურების მოხსნა + Place Brush Art ფუნჯის ნახატის განთავსება + Replace Brush Art ფუნჯის ნახატის ჩანაცვლება + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? კონტურები იყენებს ამ ფუნჯს. გამოყენებულ იქნას ახალი ნახატი ამ კონტურებზე, თუ დარჩეს ისინი როგორც არის და დაემატოს ფუნჯის ასლი ახალი ნახატით? + Apply to Strokes კონტურებზე გამოყენება + Leave Strokes კონტურების დატოვება +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` ნახატი არ აქვს (ნახატი მხოლოდ გაფანტვის, მხატვრულ და პატერნის ფუნჯებს აქვს) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools განლაგების ხელსაწყოები Arrange in Grid… ბადეში განლაგება… @@ -6605,10 +6789,28 @@ breakText Glyphs გლიფები Malayalam მალაიალამური Odia ორია Urdu ურდუ + Assamese ასამური + Sanskrit სანსკრიტი + German: Swiss გერმანული: შვეიცარია + Catalan კატალანური + Danish დანიური + Swedish შვედური + Finnish ფინური + Norwegian ნორვეგიული + Polish პოლონური + Czech ჩეხური + Russian რუსული + Bulgarian ბულგარული + Serbian: Cyrillic სერბული: კირილიცა + Serbian: Latin სერბული: ლათინიცა + Croatian ხორვატული + Turkish თურქული + Chinese ჩინური VectorCraft {release} and later (version {n}) VectorCraft {release} და უფრო ახალი (ვერსია {n}) # Document Tools add-on: Export All Open Documents (#4920). Export All Open Documents as PDF ყველა ღია დოკუმენტის ექსპორტი PDF-ად Export All Open Documents as SVG ყველა ღია დოკუმენტის ექსპორტი SVG-ად + Export All Open Documents ყველა ღია დოკუმენტის ექსპორტირება @msgplural Exported {n} document|Exported {n} documents ექსპორტირებულია დოკუმენტი ({n}) @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} ექსპორტირებულია დოკუმენტი ({n}); {title} არ ჩაიწერა: {error} # Document Tools add-on: Batch Trace Folder (#4921). @@ -6622,6 +6824,7 @@ breakText Glyphs გლიფები Static Symbol სტატიკური სიმბოლო Symbol Instance Appearance სიმბოლოს ეგზემპლარის იერსახე Reset Symbol Instance სიმბოლოს ეგზემპლარის ჩამოყრა + Select Symbol Instance Part სიმბოლოს ეგზემპლარის ნაწილის მონიშვნა @msg type must be static or dynamic, not {v} type უნდა იყოს static ან dynamic და არა {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` სტატიკური სიმბოლოა: ჯერ სიმბოლოს ტიპად დააყენეთ „დინამიკური“ @msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change სიმბოლოს ეგზემპლარში მონიშნული მრუდის, შედგენილი მრუდის ან ტექსტის მხოლოდ შევსება, კონტური, გამჭვირვალობა და შერევა შეიძლება შეიცვალოს @@ -6816,6 +7019,11 @@ font-script Japanese იაპონური @msg only an exporter or an importer declares `extensions` `extensions`-ს მხოლოდ ექსპორტის ან იმპორტის პლაგინი აცხადებს @msg an importer always gets an import's budget: leave `budget` out იმპორტის პლაგინი ყოველთვის იღებს იმპორტის ბიუჯეტს: გამოტოვეთ `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info პრობლემების მოგვარების ინფორმაციის კოპირება +@msg Copied the troubleshooting info პრობლემების მოგვარების ინფორმაცია კოპირებულია +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report VectorCraft-ის ბოლო სესიამ დახურვამდე პასუხის გაცემა შეწყვიტა. დახმარება › პრობლემების მოგვარების ინფორმაციის კოპირება აკოპირებს დეტალებს შეცდომის ანგარიშისთვის + # Safe Mode Safe Mode… უსაფრთხო რეჟიმი… Safe Mode უსაფრთხო რეჟიმი @@ -6836,12 +7044,19 @@ font-script Japanese იაპონური # Align to Pixel Grid Align to Pixel Grid პიქსელურ ბადეზე გასწორება + Align New Objects to Pixel Grid ახალი ობიექტების პიქსელურ ბადეზე გასწორება + Not Aligned to Pixel Grid პიქსელურ ბადეზე გაუსწორებელი @msg only paths and compound paths can be aligned to the pixel grid პიქსელურ ბადეზე მხოლოდ ტრაექტორიების და შედგენილი ტრაექტორიების გასწორებაა შესაძლებელი @msg side is left or right, not `{s}` side არის left ან right და არა `{s}` Ignore All ყველას იგნორირება Add to Dictionary ლექსიკონში დამატება No Suggestions შემოთავაზებები არ არის + Copies per Sheet (as many as fit, in a grid) ასლები ფურცელზე (რამდენიც დაეტევა, ბადედ) Edit Custom Dictionary მომხმარებლის ლექსიკონის რედაქტირება + Add to Custom Dictionary მომხმარებლის ლექსიკონში დამატება + Change in Custom Dictionary მომხმარებლის ლექსიკონში შეცვლა + Delete from Custom Dictionary მომხმარებლის ლექსიკონიდან წაშლა + Spelling Suggestions მართლწერის შეთავაზებები Entry: ჩანაწერი: # Script Console Script Console სკრიპტების კონსოლი @@ -6866,8 +7081,33 @@ font-script Japanese იაპონური @plural {n} line cut|{n} lines cut {n} სტრიქონი შემოკლდა @msg `first` and `last` must be numbers of lines the console holds, first before last `first` და `last` უნდა იყოს კონსოლში შენახული სტრიქონების ნომრები და `first` უნდა იყოს `last`-ზე წინ +# Learn panel + Learn სწავლა + Explore tutorials გაკვეთილების დათვალიერება + For you თქვენთვის + Skills უნარები + Get started დაწყება + Quick skill guide უნარების სწრაფი გზამკვლევი + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. მოკლე პრაქტიკული გაკვეთილები ძირითადი ხელსაწყოებისთვის, დაჯგუფებული უნარების მიხედვით. აირჩიეთ უნარი მისი გაკვეთილების სანახავად. + List Tutorials გაკვეთილების სია + Show Tutorial გაკვეთილის ჩვენება +@msg missing `tutorial` (see learn.list) აკლია `tutorial` (იხ. learn.list) +@msg unknown tutorial `{id}` (see learn.list) უცნობი გაკვეთილი `{id}` (იხ. learn.list) + # Deferred plug-in effects Refresh Deferred Effects გადადებული ეფექტების განახლება Deferred Effects გადადებული ეფექტები @msg no plug-in effect is deferred პლაგინის ეფექტი არ არის გადადებული @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. გაიხსნა, გადადებული პლაგინის ეფექტები: {n}. ეფექტი › გადადებული ეფექტების განახლება მათ გაუშვებს. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools ჭრის ხელსაწყოები + Stencil Bridges… ტრაფარეტის ხიდები… + Stencil Bridges ტრაფარეტის ხიდები + Shortest Crossing უმოკლესი გადაკვეთა + Direction მიმართულება +@msg The selected art has no islands to bridge მონიშნულ ნახატს არ აქვს დასაკავშირებელი კუნძულები +@msg No bridge of this width fits across the selected art ამ სიგანის ხიდი მონიშნულ ნახატზე არ ეტევა +@msg Some islands could not be joined to the area around the art ზოგიერთი კუნძული ვერ დაუკავშირდა ნახატის გარშემო არეს +@msg `width` must be from {lo} to {hi} pt `width` უნდა იყოს {lo}-დან {hi} pt-მდე +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` უნდა იყოს მთელი რიცხვი 1-დან {MAX_BRIDGES_PER_ISLAND}-მდე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b7f5824635..8c333d6634 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -179,6 +179,7 @@ digits Malayalam 말라얄람어 PDF Presets… PDF 프리셋… Perspective Grid Presets… 원근 격자 프리셋… Color Settings… 색상 설정… + Assign Profile 프로파일 지정 Assign Profile… 프로파일 지정… Keyboard Shortcuts… 키보드 단축키… Preferences… 환경 설정… @@ -224,6 +225,15 @@ digits Malayalam 말라얄람어 Expand… 확장… Expand Appearance 모양새 확장 Crop Image 이미지 자르기 + Image Tools 이미지 도구 + Remove Background… 배경 제거… + Remove Background 배경 제거 + Background 배경 + Edge Color 가장자리 색상 + Picked Colors 선택한 색상 + Corner Color 모퉁이 색상 + Contiguous 인접 + Each Channel 각 채널 Edit Path 패스 편집 Mask 마스크 Rasterize… 래스터화… @@ -273,6 +283,10 @@ digits Malayalam 말라얄람어 Blend Options… 블렌드 옵션… Expand 확장 Replace Spine 스파인 바꾸기 + Create Spine 스파인 만들기 + Create Spine: 스파인 만들기: + Always 항상 + Never 안 함 Reverse Spine 스파인 반전 Reverse Front to Back 앞뒤 반전 Envelope Distort 엔벨로프 왜곡 @@ -402,6 +416,8 @@ digits Malayalam 말라얄람어 Stair Step 계단 Gravity 중력 Type on a Path Options… 패스 위 문자 옵션… + Center on Top 위쪽에 가운데 맞춤 + Center on Bottom 아래쪽에 가운데 맞춤 Threaded Text 연결된 문자 Create 만들기 Release Selection 선택 해제 @@ -427,6 +443,15 @@ digits Malayalam 말라얄람어 Smart Punctuation… 스마트 문장 부호… Create Outlines 윤곽선 만들기 Optical Margin Alignment 시각적 여백 정렬 + Dynamic Text 동적 텍스트 + Dynamic Text Presets 동적 텍스트 사전 설정 + Arch 아치 +@msg select point type or type on a path 포인트 문자 또는 패스 위 문자를 선택하십시오 +@msg type on a path in a thread cannot use Dynamic Text: {frames} 연결된 문자의 패스 위 문자에는 동적 텍스트를 사용할 수 없습니다: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} 열린 패스나 컴파운드 패스 위 문자는 위쪽이나 아래쪽에 가운데 맞춤할 수 없습니다: {open} +@msg type on a path with no length or no height cannot be centered: {flat} 길이나 높이가 없는 패스 위 문자는 가운데 맞춤할 수 없습니다: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} 연결된 문자의 패스 위 문자는 위쪽이나 아래쪽에 가운데 맞춤할 수 없습니다: {frames} +@msg select type on a closed path 닫힌 패스 위 문자를 선택하세요 Fill with Placeholder Text 자리 표시 문자로 채우기 Insert Inline Symbol 인라인 심볼 삽입 Show Hidden Characters 숨겨진 문자 표시 @@ -505,6 +530,8 @@ digits Malayalam 말라얄람어 Extrude & Bevel… 돌출 및 경사… 3D (Classic) 3D(클래식) Extrude & Bevel (Classic)… 돌출 및 경사(클래식)… + Revolve (Classic)… 회전체(클래식)… + Rotate (Classic)… 회전(클래식)… Surface 표면 Wireframe 와이어프레임 No Shading 셰이딩 없음 @@ -807,8 +834,25 @@ digits Malayalam 말라얄람어 Stun Pulse 기절 Stealth Fade 은신 Shield Buff 방패 + Textures 텍스처 + Fine Grain 고운 입자 + Canvas Weave 캔버스 직조 + Burlap Sack 마대 자루 + Cracked Glaze 갈라진 유약 + Mosaic Floor 모자이크 바닥 + Quilted Squares 퀼트 사각형 + Leaded Glass 납유리 + Damp Paper 젖은 종이 Outlines and Rules 윤곽선과 괘선 Hand-Drawn 손그림 + Painted and Sketched 페인팅과 스케치 + Washed Blue 번진 파랑 + Bristle Ochre 붓결 황토 + Pastel Heather 파스텔 헤더 + Charcoal Shade 목탄 음영 + Ink Contour 잉크 윤곽 + Wet Ink 젖은 먹 + Fine Pen 가는 펜 Gradient Finishes 그레이디언트 마감 Shape Effects 모양 효과 Blends and Transparency 블렌드와 투명도 @@ -828,6 +872,8 @@ digits Malayalam 말라얄람어 Spectrum Gradients 스펙트럼 그레이디언트 Sky Gradients 하늘 그레이디언트 Neutral Gradients 중간색 그레이디언트 + Organic Fades 유기적 페이드 + Holographic 홀로그래픽 Duotone Gradients 듀오톤 그레이디언트 Radial Glows 방사형 광선 Save Swatch Library… 견본 라이브러리 저장… @@ -839,6 +885,7 @@ digits Malayalam 말라얄람어 Search Commands… 명령 검색… VectorCraft Help… VectorCraft 도움말… Preview 미리 보기 + Preview: 미리 보기: Show Edges 가장자리 표시 Show Corner Widget 모퉁이 위젯 표시 Show Template 템플릿 표시 @@ -1425,6 +1472,14 @@ antiAlias Sharp 날카롭게 Disable Auto Add/Delete 자동 추가/삭제 사용 안 함 Disable Opacity Mask 불투명 마스크 사용 안 함 Discard 삭제 + Preserve 보존 + TIFF (Black & White) TIFF (흑백) + TIFF (8-bit Color) TIFF (8비트 색상) + High Resolution 고해상도 + Medium Resolution 중간 해상도 + Low Resolution 저해상도 + Language Level 2 언어 수준 2 + Language Level 3 언어 수준 3 Discard Empty Type 빈 문자 삭제 Discard Recovered Documents 복구된 문서 삭제 Discard White Overprint in Output 출력에서 흰색 오버프린트 삭제 @@ -2031,6 +2086,7 @@ antiAlias Sharp 날카롭게 Include SVG Code SVG 코드 포함 Include Swatches for Tints 농도별 견본 포함 Include non-printing layers 인쇄되지 않는 레이어 포함 + Write pages longer than 200 in at full size in points 200 in보다 긴 페이지를 실제 크기의 포인트로 기록 Ink 잉크 Insert Character 문자 삽입 Inspect Document 문서 검사 @@ -2674,12 +2730,16 @@ mark-style Japanese 일본식 RECENT 최근 항목 Radar Graph Tool 레이더 그래프 도구 Radial Gradient 방사형 그레이디언트 + Conic Gradient 원뿔형 그레이디언트 + Diamond Gradient 다이아몬드 그레이디언트 Random 무작위 Randomize Colors 색상 무작위 변경 Randomly change color order 색상 순서를 무작위로 변경 Randomly change saturation and brightness 채도와 명도를 무작위로 변경 Range: 범위: Raster File Format: 래스터 파일 형식: + Include Placed Images 배치된 이미지 포함 + Include Fill Hatches 칠 해치 포함 Raster Sample Size: 래스터 샘플 크기: Raster/Vector Balance: 래스터/벡터 균형: Rasterize Unsupported Art 지원되지 않는 아트웍 래스터화 @@ -2881,6 +2941,9 @@ mark-style Japanese 일본식 Right Plane 오른쪽 평면 Right: 오른쪽: Roman Hanging Punctuation 로마자 걸림 문장 부호 + Korean Line Break Anywhere 한글 어디서나 줄 바꿈 + East Asian Composition Settings 동아시아 조판 설정 + Korean Composition Settings 한글 조판 설정 Rotate 회전 Rotate Tool 회전 도구 Rotate View Tool 보기 회전 도구 @@ -3069,6 +3132,7 @@ mark-style Japanese 일본식 Show List View 목록 보기 표시 Show Note 메모 표시 Show Options 옵션 표시 + Show Recent Colors 최근 색상 표시 Show Original Path 원래 패스 표시 Open this dialog with these settings next time 다음에 이 설정으로 이 대화상자 열기 Auto-Simplify 자동 단순화 @@ -3309,6 +3373,8 @@ mark-style Japanese 일본식 Toolbar: Single/Double Column 도구 막대: 한 줄/두 줄 Toolbar: Add Tool 도구 막대: 도구 추가 Toolbar: Remove Tool 도구 막대: 도구 제거 + Add Tool… 도구 추가… + Remove Tool 도구 제거 Toolbar: Reset 도구 막대: 재설정 Top: 위쪽: Total Width: 전체 너비: @@ -3879,6 +3945,8 @@ file-filter Templates 템플릿 Scale at Center 중심에서 크기 조정 Up/Down: 위/아래: Left/Right: 왼쪽/오른쪽: + Tate-chu-yoko Up/Down 다테추요코 위/아래 + Tate-chu-yoko Left/Right 다테추요코 왼쪽/오른쪽 Temperature 색온도 Template 템플릿 Templates 템플릿 @@ -3917,6 +3985,7 @@ file-filter Templates 템플릿 Weight 두께 Windows Windows Working CMYK (don't tag) 작업용 CMYK (태그 안 함) + Working RGB (don't tag) 작업용 RGB (태그 안 함) Workspace {i} 작업 영역 {i} Yellow 노랑 [Normal Character Style] [기본 문자 스타일] @@ -4014,6 +4083,13 @@ axis Both 양쪽 Dock Panel 패널 고정 Dock to Top 위쪽에 고정 Dock to Bottom 아래쪽에 고정 + Control Bar Options 컨트롤 막대 옵션 + Tool Options 도구 옵션 + Object Options 개체 옵션 + Image Options 이미지 옵션 + Vertical Alignment 세로 정렬 + Align and Distribute 정렬 및 분포 + Document Options 문서 옵션 Dock Control Bar 컨트롤 막대 고정 Drag to float the toolbar 드래그하여 도구 모음 분리 Drag to the window's left or right edge to dock 창 왼쪽 또는 오른쪽 가장자리로 드래그하여 고정 @@ -4266,16 +4342,19 @@ theme Appearance 외관 @msg `gradient` must be an object `gradient`는 개체여야 합니다 @msg `groupColors` must be an array `groupColors`는 배열이어야 합니다 @msg `mode` applies to freeform gradients `mode`는 자유형 그레이디언트에 적용됩니다 +@msg a negative `aspect` applies to conic gradients 음수 `aspect`는 원뿔형 그레이디언트에 적용됩니다 +@msg `focal` applies to radial gradients `focal`은 방사형 그레이디언트에 적용됩니다 @msg `preserve` must be an object `preserve`는 개체여야 합니다 @msg `globalAdjust` must be an object `globalAdjust`는 개체여야 합니다 @msg `stops` must be an array `stops`는 배열이어야 합니다 +@msg `{key}` must be an array `{key}`은(는) 배열이어야 합니다 @msg `{k}` must be [x, y] `{k}`은(는) [x, y]여야 합니다 @msg a gradient needs at least two stops 그레이디언트에는 정지점이 두 개 이상 필요합니다 @msg give both `start` and `end` [x, y] (or neither) `start`와 `end` [x, y]를 모두 지정하세요(또는 둘 다 생략) @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 unknown gradient kind `{k}` (linear, radial, freeform) 알 수 없는 그레이디언트 종류 `{k}`(linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) 알 수 없는 그레이디언트 종류 `{k}`(linear, radial, conic, diamond, freeform) @msg the art could not be sampled 아트웍을 샘플링할 수 없습니다 @msg the art is too light for any dots 아트웍이 너무 밝아 점을 만들 수 없습니다 @msg the document has no symbols 문서에 심볼이 없습니다 @@ -4369,6 +4448,7 @@ theme Appearance 외관 @msg `{key}` must be a #rrggbb color `{key}`은(는) #rrggbb 색상이어야 합니다 @msg `{key}` must be a #rrggbb colour `{key}`은(는) #rrggbb 색상이어야 합니다 @msg `{key}` must be a string `{key}`은(는) 문자열이어야 합니다 +@msg `{key}` must be a profile name or null `{key}`은(는) 프로파일 이름 또는 null이어야 합니다 @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 between {min} and {max} (got {x}) `{key}`은(는) {min}에서 {max} 사이여야 합니다({x} 입력됨) @@ -4555,6 +4635,8 @@ theme Appearance 외관 @msg the image's pixels don't match its size 이미지의 픽셀이 크기와 맞지 않습니다 @msg {bpp}-bit bitmaps can't be read {bpp}비트 비트맵은 읽을 수 없습니다 @msg not an EMF or WMF file EMF 또는 WMF 파일이 아닙니다 +@msg not an HP-GL file HP-GL 파일이 아닙니다 +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens`는 #rrggbb 색상 1~255개의 배열이어야 합니다 @msg its layers use {_1}, which aren't read yet 레이어에 {_1}이(가) 있으며, 아직 읽을 수 없습니다 @msg the EMF header is damaged EMF 헤더가 손상되었습니다 @msg damaged 손상됨 @@ -4571,6 +4653,7 @@ theme Appearance 외관 @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 아트보드 {n}의 페이지는 {size}로 PDF 페이지 한도 14,400 pt (200 in)보다 깁니다: UserUnit {unit}(으)로 기록되므로 UserUnit을 무시하는 앱에서는 그 배수만큼 작게 표시됩니다 @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 아트보드 {n}의 페이지는 {size}로 PDF 페이지 한도 14,400 pt (200 in)보다 깁니다: {label} 페이지는 UserUnit 없이 포인트 단위로 기록되며, 한도를 지키는 앱은 페이지를 200 in으로 자릅니다 @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5에는 14,400 pt (200 in)보다 긴 페이지가 크기를 유지하는 데 필요한 UserUnit이 없습니다: 파일이 PDF 1.6으로 기록됩니다 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4에는 14,400 pt (200 in)보다 긴 페이지가 PDF/A-2의 페이지 한도인 14,400 단위 안에 들어가는 데 필요한 UserUnit이 없습니다: 파일이 PDF 1.6으로 기록됩니다 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 아트보드 {n}의 페이지는 {size}로, PDF 페이지 변 3에서 14,400 단위에 비해 너무 길고 좁습니다: 짧은 변을 3 단위 이상으로 유지하는 UserUnit {unit}로 기록되며, 한도를 지키는 앱은 긴 변을 14,400 단위로 자릅니다 @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 파일은 실수를 최대 {max}까지 담는데 아트보드 {n}의 {side} pt 페이지에는 더 큰 값이 필요합니다: PDF/X 표준 없이 PDF 1.6 이상을 선택하거나 더 작은 아트보드를 사용하세요 @msg page {0} does not exist (the PDF has {1}) 페이지 {0}이(가) 없습니다(PDF의 페이지 수: {1}) @@ -4765,6 +4848,14 @@ theme Appearance 외관 @msg no such view 해당 보기가 없습니다 @msg printing isn't available here 여기서는 인쇄할 수 없습니다 @msg select an image 이미지를 선택하세요 +@msg `background` must be edges, corners or colors `background`는 edges, corners 또는 colors여야 합니다 +@msg `match` must be distance or channels `match`는 distance 또는 channels여야 합니다 +@msg `{key}` must be from 0 to 100 `{key}`는 0에서 100 사이여야 합니다 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors`에는 16진수(#rrggbb 또는 #rgb)나 black, white, red, green, blue로 쓴 색상이 1~16개 있어야 합니다 +@msg the linked image shows its preview: embed or relink it first 연결된 이미지가 미리 보기를 표시하고 있습니다: 먼저 포함하거나 다시 링크하세요 +@msg a CMYK image has no transparency to set CMYK 이미지에는 설정할 투명도가 없습니다 +@msg every pixel matches the background: no image would be left 모든 픽셀이 배경과 일치합니다: 남는 이미지가 없습니다 +@msg an image of {w} × {h} pixels is too large to change {w} × {h}픽셀 이미지는 너무 커서 변경할 수 없습니다 @msg the document has no artboards 문서에 아트보드가 없습니다 @msg tool (a tool id) is required 도구(도구 id)가 필요합니다 @msg unknown tool `{t}` 알 수 없는 도구 `{t}` @@ -4936,6 +5027,8 @@ theme Appearance 외관 @msg invalid object id {value}: expected a non-negative integer 개체 id {value}이(가) 올바르지 않습니다: 음이 아닌 정수여야 합니다 @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}`의 항목 {index}은(는) {value}이며, 음이 아닌 정수인 개체 id가 아닙니다 @msg no such object id {value} id가 {value}인 개체가 없습니다 +@msg id {value} is a ruler guide, not an object id {value}은(는) 개체가 아니라 안내선입니다 +@msg a ruler guide goes only directly in a layer or sublayer 안내선은 레이어나 하위 레이어 바로 아래에만 둘 수 있습니다 @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}은(는) 개체가 아닌 레이어입니다. 레이어는 layer.move로 이동하세요 @msg automation filesystem access is not granted: read authority is absent: {path} 자동화 파일 시스템 접근이 허용되지 않았습니다: 읽기 권한이 없습니다: {path} @@ -4965,7 +5058,13 @@ theme Appearance 외관 @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC 또는 HEIF 파일에 읽을 수 없는 종류의 이미지가 있습니다 @msg HEIC and HEIF images can't be opened in this build 이 빌드에서는 HEIC 및 HEIF 이미지를 열 수 없습니다 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 이미지가 너무 커서 읽을 수 없습니다({_1} × {_2}픽셀) -@msg zipped 32-bit PSD image data with prediction can't be read 예측이 적용된 ZIP 압축 32비트 PSD 이미지 데이터는 읽을 수 없습니다 +@msg zipped 1-bit PSD image data with prediction can't be read 예측이 적용된 ZIP 압축 1비트 PSD 이미지 데이터는 읽을 수 없습니다 +@msg the PSD file's layer data uses an unknown compression ({m}) PSD 파일의 레이어 데이터가 알 수 없는 압축({m})을 사용합니다 +@msg the PSD file's layer records are damaged PSD 파일의 레이어 레코드가 손상되었습니다 +@msg the PSD file's layer groups are nested too deeply PSD 파일의 레이어 그룹이 너무 깊이 중첩되어 있습니다 +@msg a layer of the PSD file is too large to read PSD 파일의 레이어가 너무 커서 읽을 수 없습니다 +@msg the PSD file's layers take more memory to read than allowed PSD 파일의 레이어를 읽는 데 허용된 것보다 많은 메모리가 필요합니다 +@msg the layers can't be read ({e}): the file opened as its merged image 레이어를 읽을 수 없습니다({e}): 파일이 병합된 이미지로 열렸습니다 @msg {depth}-bit PSD files in this colour mode can't be read 이 색상 모드의 {depth}비트 PSD 파일은 읽을 수 없습니다 @msg the PSD file is cut short PSD 파일이 잘려 있습니다 @msg the PSD file's header is damaged PSD 파일의 헤더가 손상되었습니다 @@ -5275,6 +5374,11 @@ lighting Light 광원 Softness 부드러움 Ambient Light 주변광 Light behind the object 개체 뒤의 조명 + Shadows 그림자 + Distance from Object 개체로부터의 거리 + Shadow Bounds 그림자 범위 + Behind Object 개체 뒤 + Below Object 개체 아래 3D Lighting Preset 3D 조명 사전 설정 Standard 표준 Diffuse 확산 @@ -5342,7 +5446,7 @@ lighting Light 광원 @msg span must be "object" or "selection", got {v} span은 "object" 또는 "selection"이어야 합니다. {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 span: "selection"은 선형 또는 방사형 그레이디언트를 배치합니다. 자유형 그레이디언트는 배치할 수 없습니다 +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection"은 선형, 방사형, 원뿔형 또는 다이아몬드 그레이디언트를 배치합니다. 자유형 그레이디언트는 배치할 수 없습니다 @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection"은 그레이디언트 자체를 배치합니다: `start`와 `end`를 빼세요 (이미 문서 좌표로 배치합니다) Make Image Dynamic 이미지를 동적으로 만들기 Import Data Sets… 데이터 세트 가져오기… @@ -5527,6 +5631,7 @@ lighting Light 광원 Ruby 루비 Geometric Guides 기하학적 안내선 Geometric Patterns 기하학적 패턴 + Grit Textures 입자 텍스처 Ease In 서서히 시작 Ease Out 서서히 종료 Ease In Out 서서히 시작 및 종료 @@ -5587,6 +5692,8 @@ axis Y Axis Y축 Version: {version} 버전: {version} Install “{name}” in place of the plug-in with the same ID? 같은 ID의 플러그인 대신 “{name}”을(를) 설치하시겠습니까? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 이 파일은 이전에 이 ID로 설치된 플러그인이 아닙니다. 이 ID에 보관된 설정과 캐시를 받습니다. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 자동화가 이 플러그인 설치를 요청했습니다. 설치하려면 직접 개체 › 플러그인 › 플러그인 설치…를 선택하세요. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 자동화가 이 플러그인 설치를 요청했습니다. 설치하려면 직접 개체 › 플러그인 › 플러그인 설치…를 선택하세요. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}”은(는) ID {_1}의 플러그인과 다른 모듈이며 그 플러그인에 보관된 설정과 캐시를 받게 됩니다. 사용자가 동의하면 `replace: true`로 설치하세요 File SHA-256: {hash} 파일 SHA-256: {hash} Read the objects it is given 전달받은 개체 읽기 @@ -5632,6 +5739,11 @@ axis Y Axis Y축 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 메모리 예산(개체 {_1}에 입력 {size}바이트가 필요하지만 {left}바이트 남음) @msg object budget (more than {MAX_OBJECTS} read-only objects) 개체 예산(읽기 전용 개체 {MAX_OBJECTS}개 초과) +@msg instruction budget 명령어 예산 +@msg time budget 시간 예산 +@msg memory budget (the selection is too large to hand over) 메모리 예산(선택 항목이 너무 커서 넘길 수 없음) +@msg output size ({what} is {len} bytes, limit {max}) 출력 크기({what}: {len}바이트, 제한 {max}) +@msg the plug-in's grant can't be removed from the plug-in store 플러그인 저장소에서 플러그인의 권한을 제거할 수 없습니다 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` 권한은 이후 플러그인 API용으로 예약되어 있습니다. 이 호스트는 이 권한을 부여하지 않습니다 @msg unknown permission `{shown}` 알 수 없는 권한 `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}”은(는) {asked} 권한을 요청합니다. 데스크톱 앱에서 사람이 승인하거나 --allow-plugin-grants로 시작한 세션에서 `grant`를 전달하세요 @@ -5644,6 +5756,12 @@ axis Y Axis Y축 @msg command {name}: `label` must be 1-64 printable characters 명령 {name}: `label`은 인쇄 가능한 문자 1-64자여야 합니다 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 명령 {name}: a-z 0-9 _로 이루어지고 문자로 시작하는 1-{MAX_COMMAND_ID}자 ID를 사용하세요 @msg command {name}: {e} 명령 {name}: {e} +@msg manifest: {e} 매니페스트: {e} +@msg manifest: {e} at line {line} column {column} 매니페스트: {e} ({line}행 {column}열) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands`는 각각 `id`와 `label`이 있는 명령 목록이어야 합니다 +@msg command {name} must be an object with an `id` and a `label` 명령 {name}은(는) `id`와 `label`이 있는 객체여야 합니다 +@msg missing field `{key}` `{key}` 필드가 없습니다 +@msg duplicate field `{key}` `{key}` 필드가 중복되었습니다 @msg only a filter or a live effect declares `commands` 필터나 라이브 효과만 `commands`를 선언합니다 @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed 모듈의 SHA-256이 `hash`에 지정된 값과 다릅니다. 아무것도 설치되지 않았습니다 @@ -5668,6 +5786,16 @@ axis Y Axis Y축 @msg message must be text message의 값은 텍스트여야 합니다 @msg allowContinue must be true or false allowContinue의 값은 true 또는 false여야 합니다 @msg Batch cannot play an action with a stop 일괄 처리에서는 중지가 있는 액션을 재생할 수 없습니다 + Insert Menu Item… 메뉴 항목 삽입… + Insert Menu Item 메뉴 항목 삽입 + Menu Item: 메뉴 항목: + No menu item matches. 일치하는 메뉴 항목이 없습니다. + Several menu items match. Choose one from the list. 여러 메뉴 항목이 일치합니다. 목록에서 하나를 선택하세요. + Items that open a dialog, and File, Window and Help menu items, are not listed. 대화 상자를 여는 항목과 파일, 윈도우, 도움말 메뉴의 항목은 표시되지 않습니다. +@msg command must be text command의 값은 텍스트여야 합니다 +@msg no menu item that can be inserted runs this command 이 명령을 실행하는 삽입 가능한 메뉴 항목이 없습니다 +@msg the action already has 10,000 steps 액션에 이미 단계가 10,000개 있습니다 +@msg the action set would be larger than 8 MiB 액션 세트가 8 MiB를 넘게 됩니다 Playback Options 재생 옵션 Accelerated 가속 Step by Step 단계별 @@ -5706,6 +5834,12 @@ axis Y Axis Y축 Crosshair 십자선 Checkpoint 체크포인트 Inventory Icons 인벤토리 아이콘 + Skill Icons 스킬 아이콘 + Attack 공격 + Defend 방어 + Heal 치유 + Buff 버프 + Ult 궁극기 Sword 검 Shield 방패 Potion 포션 @@ -5770,7 +5904,23 @@ axis Y Axis Y축 Dash Trail 대시 트레일 Speed Line 스피드 라인 Game Trails 게임 트레일 + Energy Beams 에너지 빔 + Laser Bolt 레이저 볼트 + Plasma Arc 플라즈마 아크 + Charge Wave 차지 웨이브 + Spark Trail 스파크 트레일 Calligraphic Nibs 서예 펜촉 + Bristle Brushes 강모 브러시 모음 + Fine Liner 가는 라이너 + Pointed Flat 뾰족한 평붓 + Stubby Round 짧은 둥근 붓 + Dry Scrub 마른 문지르기 + Soft Dome 부드러운 돔 + Filbert 필버트 + Angled Round 사선 둥근 붓 + Angled Flat 사선 평붓 + Fan Blender 블렌딩 부채붓 + Grass Fan 잔디 부채붓 Pattern Borders 패턴 테두리 Scatter Shapes 흩뿌리기 모양 Save Brush Library… 브러시 라이브러리 저장… @@ -5970,9 +6120,12 @@ anchor Points: 포인트: @msg {label} must be a number {label}은(는) 숫자여야 합니다 @msg {label} must be a number of at least 0.1 {label}은(는) 0.1 이상의 숫자여야 합니다 Advanced Character Formats 고급 문자 형식 + Basic Paragraph Formats 기본 단락 형식 + Composition 조판 Horizontal Scale 가로 비율 Vertical Scale 세로 비율 @msg {label} must be a number from {min} to {max} {label}은(는) {min}에서 {max} 사이의 숫자여야 합니다 +@msg {label} must be a whole number from {min} to {max} {label}은(는) {min}에서 {max} 사이의 정수여야 합니다 Character Color 문자 색상 OpenType Features OpenType 기능 Stylistic Sets 스타일 세트 @@ -5980,6 +6133,10 @@ anchor Points: 포인트: @msg features lists at most {max} tags features에는 태그를 최대 {max}개까지 지정할 수 있습니다 @msg unknown OpenType feature `{t}` 알 수 없는 OpenType 기능 `{t}` @msg {label} must be a number above 0 and at most {max} {label}은(는) 0 초과 {max} 이하의 숫자여야 합니다 +@msg {label} must be at most {max} characters {label}은(는) 최대 {max}자여야 합니다 +@msg {label} must be one character {label}은(는) 한 글자여야 합니다 +@msg at most {max} tab stops 탭 정지는 최대 {max}개까지 지정할 수 있습니다 +@msg unknown align `{other}` 알 수 없는 정렬 `{other}` @msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6142,6 +6299,12 @@ breakText Glyphs 글리프 Delete the selected brushes? 선택한 브러시를 삭제하시겠습니까? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 선에서 이 브러시 중 하나 이상을 사용합니다. 해당 선에서 브러시를 제거하고 브러시를 삭제하시겠습니까? Remove Strokes 선 제거 + Place Brush Art 브러시 아트 배치 + Replace Brush Art 브러시 아트 바꾸기 + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 선에서 이 브러시를 사용합니다. 새 아트를 해당 선에 적용하시겠습니까, 아니면 선을 그대로 두고 새 아트로 브러시 사본을 추가하시겠습니까? + Apply to Strokes 선에 적용 + Leave Strokes 선 유지 +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}`에는 아트가 없습니다 (흩뿌리기, 아트, 패턴 브러시에만 아트가 있습니다) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 배치 도구 Arrange in Grid… 격자로 배치… @@ -6337,6 +6500,11 @@ breakText Glyphs 글리프 @msg only an exporter or an importer declares `extensions` `extensions`는 내보내기 또는 가져오기 플러그인만 선언합니다 @msg an importer always gets an import's budget: leave `budget` out 가져오기 플러그인은 항상 가져오기 예산을 받습니다: `budget`을 생략하세요 +# Copy Troubleshooting Info + Copy Troubleshooting Info 문제 해결 정보 복사 +@msg Copied the troubleshooting info 문제 해결 정보를 복사했습니다 +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report 지난 VectorCraft 세션이 닫히기 전에 응답을 멈췄습니다. 도움말 › 문제 해결 정보 복사로 버그 보고용 세부 정보를 복사할 수 있습니다 + # Safe Mode Safe Mode… 안전 모드… Safe Mode 안전 모드 @@ -6357,6 +6525,8 @@ breakText Glyphs 글리프 # Align to Pixel Grid Align to Pixel Grid 픽셀 격자에 정렬 + Align New Objects to Pixel Grid 새 개체를 픽셀 격자에 정렬 + Not Aligned to Pixel Grid 픽셀 격자에 정렬되지 않음 @msg only paths and compound paths can be aligned to the pixel grid 패스와 컴파운드 패스만 픽셀 격자에 정렬할 수 있습니다 @msg side is left or right, not `{s}` side는 left 또는 right입니다(`{s}` 아님) Ignore All 모두 무시 @@ -6387,8 +6557,33 @@ breakText Glyphs 글리프 @plural {n} line cut|{n} lines cut 줄 {n}개 잘림 @msg `first` and `last` must be numbers of lines the console holds, first before last `first`와 `last`는 콘솔에 있는 줄 번호여야 하며 `first`가 `last`보다 앞서야 합니다 +# Learn panel + Learn 학습 + Explore tutorials 튜토리얼 살펴보기 + For you 추천 + Skills 기술 + Get started 시작하기 + Quick skill guide 빠른 기술 가이드 + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. 기본 도구를 익히는 짧은 실습 튜토리얼을 기술별로 모았습니다. 기술을 선택하면 해당 튜토리얼이 표시됩니다. + List Tutorials 튜토리얼 목록 + Show Tutorial 튜토리얼 표시 +@msg missing `tutorial` (see learn.list) `tutorial`이 없습니다(learn.list 참조) +@msg unknown tutorial `{id}` (see learn.list) 알 수 없는 튜토리얼 `{id}`(learn.list 참조) + # Deferred plug-in effects Refresh Deferred Effects 보류된 효과 새로 고침 Deferred Effects 보류된 효과 @msg no plug-in effect is deferred 보류된 플러그인 효과가 없습니다 @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 플러그인 효과 {n}개를 보류하고 열었습니다. 효과 › 보류된 효과 새로 고침으로 실행합니다. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools 커팅 도구 + Stencil Bridges… 스텐실 브리지… + Stencil Bridges 스텐실 브리지 + Shortest Crossing 최단 가로지르기 + Direction 방향 +@msg The selected art has no islands to bridge 선택한 아트워크에 연결할 섬이 없습니다 +@msg No bridge of this width fits across the selected art 이 너비의 브리지가 선택한 아트워크에 들어가지 않습니다 +@msg Some islands could not be joined to the area around the art 일부 섬을 아트워크 주변 영역에 연결할 수 없습니다 +@msg `width` must be from {lo} to {hi} pt `width`는 {lo}에서 {hi}pt 사이여야 합니다 +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count`는 1에서 {MAX_BRIDGES_PER_ISLAND} 사이의 정수여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 32db6785bb..7376a8edf4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -106,6 +106,7 @@ PDF Presets… PDF-voorinstellingen… Perspective Grid Presets… Voorinstellingen voor perspectiefraster… Color Settings… Kleurinstellingen… + Assign Profile Profiel toewijzen Assign Profile… Profiel toewijzen… Keyboard Shortcuts… Sneltoetsen… Import Shortcut Set Sneltoetsenset importeren @@ -203,6 +204,15 @@ Expand… Uitbreiden… Expand Appearance Uiterlijk uitbreiden Crop Image Afbeelding bijsnijden + Image Tools Afbeeldingshulpmiddelen + Remove Background… Achtergrond verwijderen… + Remove Background Achtergrond verwijderen + Background Achtergrond + Edge Color Randkleur + Picked Colors Gekozen kleuren + Corner Color Hoekkleur + Contiguous Aaneengesloten + Each Channel Elk kanaal Edit Path Pad bewerken Mask Masker Rasterize… Rasteriseren… @@ -252,6 +262,10 @@ Blend Options… Vermengopties… Expand Uitbreiden Replace Spine Rug vervangen + Create Spine Rug maken + Create Spine: Rug maken: + Always Altijd + Never Nooit Reverse Spine Rug omkeren Reverse Front to Back Van voor naar achter omkeren Envelope Distort Envelopvervorming @@ -366,6 +380,8 @@ Stair Step Trap Gravity Zwaartekracht Type on a Path Options… Opties voor tekst op pad… + Center on Top Boven centreren + Center on Bottom Onder centreren Threaded Text Gekoppelde tekst Create Maken Release Selection Selectie vrijgeven @@ -381,6 +397,9 @@ Smart Punctuation… Slimme interpunctie… Create Outlines Omzetten in curven Optical Margin Alignment Optische marge-uitlijning + Dynamic Text Dynamische tekst + Dynamic Text Presets Voorinstellingen voor dynamische tekst + Arch Gewelf Fill with Placeholder Text Vullen met plaatshoudertekst Insert Inline Symbol Inline-symbool invoegen Show Hidden Characters Verborgen tekens tonen @@ -451,6 +470,8 @@ Extrude & Bevel… Extruderen en afschuinen… 3D (Classic) 3D (klassiek) Extrude & Bevel (Classic)… Extruderen en afschuinen (klassiek)… + Revolve (Classic)… Draaien (klassiek)… + Rotate (Classic)… Roteren (klassiek)… Surface Oppervlak Wireframe Draadmodel No Shading Geen arcering @@ -521,6 +542,7 @@ Gaussian Blur… Gaussiaanse vervaging… View Beeld Preview Voorbeeld + Preview: Voorbeeld: Overprint Preview Overprintvoorbeeld Pixel Preview Pixelvoorbeeld Trim View Bijsnijweergave @@ -743,8 +765,25 @@ Stun Pulse Verdoving Stealth Fade Sluipen Shield Buff Schild + Textures Texturen + Fine Grain Fijne korrel + Canvas Weave Canvasweefsel + Burlap Sack Jutezak + Cracked Glaze Gecraqueleerd glazuur + Mosaic Floor Mozaïekvloer + Quilted Squares Gequilte vierkanten + Leaded Glass Glas-in-lood + Damp Paper Vochtig papier Outlines and Rules Omtrekken en lijnen Hand-Drawn Handgetekend + Painted and Sketched Geschilderd en geschetst + Washed Blue Verwassen blauw + Bristle Ochre Borsteloker + Pastel Heather Pastelheide + Charcoal Shade Houtskoolschaduw + Ink Contour Inktcontour + Wet Ink Natte inkt + Fine Pen Fijne pen Gradient Finishes Verloopafwerkingen Shape Effects Vormeffecten Blends and Transparency Vermengingen en transparantie @@ -764,6 +803,8 @@ Spectrum Gradients Spectrumverlopen Sky Gradients Luchtverlopen Neutral Gradients Neutrale verlopen + Organic Fades Organische vervagingen + Holographic Holografisch Duotone Gradients Duotoonverlopen Radial Glows Radiale gloed Save Swatch Library… Staalenbibliotheek opslaan… @@ -822,6 +863,13 @@ Dock Panel Paneel dokken Dock to Top Bovenaan dokken Dock to Bottom Onderaan dokken + Control Bar Options Opties voor bedieningsbalk + Tool Options Gereedschapsopties + Object Options Objectopties + Image Options Afbeeldingsopties + Vertical Alignment Verticale uitlijning + Align and Distribute Uitlijnen en verdelen + Document Options Documentopties Dock Control Bar Bedieningsbalk dokken Float Tool Group Gereedschapsgroep laten zweven Services Diensten @@ -1096,6 +1144,8 @@ lighting Light Licht Toolbar: Single/Double Column Werkbalk: Enkele/dubbele kolom Toolbar: Add Tool Werkbalk: gereedschap toevoegen Toolbar: Remove Tool Werkbalk: gereedschap verwijderen + Add Tool… Gereedschap toevoegen… + Remove Tool Gereedschap verwijderen Toolbar: Reset Werkbalk: herstellen Two Point Perspective Preset 1 Voorinstelling perspectief met twee vluchtpunten 1 Two Point Perspective Preset 2 Voorinstelling perspectief met twee vluchtpunten 2 @@ -1475,6 +1525,7 @@ digits Malayalam Malayalam Roman Baseline Romeinse basislijn Select a text object to edit its character attributes. Selecteer een tekstobject om de tekenkenmerken ervan te bewerken. Show Options Opties tonen + Show Recent Colors Recente kleuren tonen Small Caps Kleine kapitalen Small Caps (on the roadmap) Kleine kapitalen (op de roadmap) Standard Vertical Roman Alignment Standaard verticale Romeinse uitlijning @@ -1502,6 +1553,8 @@ digits Malayalam Malayalam Scale at Center Schalen vanuit het midden Up/Down: Omhoog/omlaag: Left/Right: Links/rechts: + Tate-chu-yoko Up/Down Tate-chu-yoko omhoog/omlaag + Tate-chu-yoko Left/Right Tate-chu-yoko links/rechts Underline Onderstrepen Vertical Scale % Verticale schaal % Axis As @@ -1604,6 +1657,8 @@ digits Malayalam Malayalam No gradient swatches Geen verloopstalen Points: clicks add free points Punten: klikken voegen vrije punten toe Radial Gradient Radiaal verloop + Conic Gradient Conisch verloop + Diamond Gradient Ruitverloop Reset to White, Black Herstellen naar wit, zwart Reverse Gradient Verloop omkeren Save to Swatches Opslaan in stalen @@ -1784,6 +1839,9 @@ digits Malayalam Malayalam Right Indent Rechts inspringen Right-to-Left Paragraph Direction Alinearichting van rechts naar links Roman Hanging Punctuation Romeinse hangende leestekens + Korean Line Break Anywhere Koreaans regeleinde overal + East Asian Composition Settings Instellingen voor Oost-Aziatische zetting + Korean Composition Settings Instellingen voor Koreaanse zetting Select a text object to edit its paragraph attributes. Selecteer een tekstobject om de alineakenmerken ervan te bewerken. Single-line Composer Compositie per regel Toggle Line Composer Compositiemethode wisselen @@ -1870,6 +1928,7 @@ digits Malayalam Malayalam Simulate Paper Papier simuleren Use Black Point Compensation Zwartpuntcompensatie gebruiken Working CMYK (don't tag) Werk-CMYK (niet taggen) + Working RGB (don't tag) Werk-RGB (niet taggen) {name} (spot) {name} (spotkleur) Add to Profiles… Toevoegen aan profielen… Align Stroke to Center Lijn in het midden uitlijnen @@ -2169,6 +2228,8 @@ digits Malayalam Malayalam Export Selected Art Only Alleen geselecteerde artwork exporteren Number of Colors: Aantal kleuren: Raster File Format: Rasterbestandsindeling: + Include Placed Images Geplaatste afbeeldingen opnemen + Include Fill Hatches Arceringen van vullingen opnemen True colour needs version 2004 or later: the nearest of 256 colours is written. Echte kleur vereist versie 2004 of later: de dichtstbijzijnde van 256 kleuren wordt weggeschreven. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Tekst wordt omlijningen, en lijnen die een CAD-lijn niet kan tekenen, worden gevulde vormen. Type stays text, and every stroke is a line with its lineweight and dashes. Tekst blijft tekst en elke lijn wordt een lijn met zijn eigen lijndikte en streepjes. @@ -2712,6 +2773,7 @@ antiAlias Sharp Scherp General › Thumbnails Algemeen › Miniaturen Grayscale images Grijswaardenafbeeldingen Include non-printing layers Niet-afdrukbare lagen opnemen + Write pages longer than 200 in at full size in points Pagina's langer dan 200 in op ware grootte in punten schrijven Left: Links: Mark as trapped Markeren als getrapt Marks and Bleeds Steker en afloop @@ -4197,6 +4259,8 @@ imageTrace Outline Contour @msg `gradient` must be an object `gradient` moet een object zijn @msg `library` is a library id or name (see {list}) `library` is een bibliotheek-id of -naam (zie {list}) @msg `mode` applies to freeform gradients `mode` geldt voor verlopen met vrije vorm +@msg a negative `aspect` applies to conic gradients een negatieve `aspect` geldt voor conische verlopen +@msg `focal` applies to radial gradients `focal` geldt voor radiale verlopen @msg `sampleSize` must be 1, 3 or 5 `sampleSize` moet 1, 3 of 5 zijn @msg `stops` must be an array `stops` moet een array zijn @msg `svg` must be an object of SVG options (see document.formats) `svg` moet een object met SVG-opties zijn (zie document.formats) @@ -4463,6 +4527,8 @@ imageTrace Outline Contour @msg not a stored central record geen opgeslagen centraal record @msg not a valid plug-in module: {0} geen geldige plug-inmodule: {0} @msg not an EMF or WMF file geen EMF- of WMF-bestand +@msg not an HP-GL file geen HP-GL-bestand +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` moet een array van 1 tot 255 #rrggbb-kleuren zijn @msg not found niet gevonden @msg not in pattern editing mode niet in patroonbewerkingsmodus @msg finish editing the pattern first rond eerst het bewerken van het patroon af @@ -4630,7 +4696,7 @@ imageTrace Outline Contour @msg unknown format onbekende indeling @msg unknown format `{f}` (Save writes {_1}) onbekende indeling `{f}` (Opslaan schrijft {_1}) @msg unknown freeform mode `{m}` (points, lines) onbekende vrijvormmodus `{m}` (punten, lijnen) -@msg unknown gradient kind `{k}` (linear, radial, freeform) onbekend verlooptype `{k}` (lineair, radiaal, vrijvorm) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) onbekend verlooptype `{k}` (lineair, radiaal, conisch, ruit, vrijvorm) @msg unknown highlight `{h}` onbekende markering `{h}` @msg unknown option `{path}.{k}` onbekende optie `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) onbekende overdruk `{o}` (behouden, simuleren of verwerpen) @@ -4814,6 +4880,8 @@ imageTrace Outline Contour @msg invalid object id {value}: expected a non-negative integer ongeldige object-id {value}: een niet-negatief geheel getal verwacht @msg `{key}` entry {index} is {value}, not a non-negative integer object id item {index} van `{key}` is {value}, geen object-id (een niet-negatief geheel getal) @msg no such object id {value} er is geen object met id {value} +@msg id {value} is a ruler guide, not an object id {value} is van een hulplijn, niet van een object +@msg a ruler guide goes only directly in a layer or sublayer een hulplijn kan alleen direct in een laag of sublaag staan @msg automation filesystem access is not granted: read authority is absent: {path} toegang tot het bestandssysteem voor automatisering is niet verleend: de leesbevoegdheid ontbreekt: {path} @msg automation filesystem access is not granted: write authority is absent: {path} toegang tot het bestandssysteem voor automatisering is niet verleend: de schrijfbevoegdheid ontbreekt: {path} @msg automation path rejected: outside the read root {root}: {path} automatiseringspad afgewezen: buiten de leesroot {root}: {path} @@ -4830,7 +4898,13 @@ imageTrace Outline Contour @msg the PSD file has an unknown colour mode ({m}) het PSD-bestand heeft een onbekende kleurmodus ({m}) @msg the PSD file's image data uses an unknown compression ({m}) de afbeeldingsgegevens van het PSD-bestand gebruiken een onbekende compressie ({m}) @msg the PSD image is too large to read ({_1} × {_2} pixels) de PSD-afbeelding is te groot om te lezen ({_1} × {_2} pixels) -@msg zipped 32-bit PSD image data with prediction can't be read gezipte 32-bits PSD-afbeeldingsgegevens met voorspelling kunnen niet worden gelezen +@msg zipped 1-bit PSD image data with prediction can't be read gezipte 1-bits PSD-afbeeldingsgegevens met voorspelling kunnen niet worden gelezen +@msg the PSD file's layer data uses an unknown compression ({m}) de laaggegevens van het PSD-bestand gebruiken een onbekende compressie ({m}) +@msg the PSD file's layer records are damaged de laagrecords van het PSD-bestand zijn beschadigd +@msg the PSD file's layer groups are nested too deeply de laaggroepen van het PSD-bestand zijn te diep genest +@msg a layer of the PSD file is too large to read een laag van het PSD-bestand is te groot om te lezen +@msg the PSD file's layers take more memory to read than allowed de lagen van het PSD-bestand hebben meer geheugen nodig om te lezen dan toegestaan +@msg the layers can't be read ({e}): the file opened as its merged image de lagen kunnen niet worden gelezen ({e}): het bestand is geopend als zijn samengevoegde afbeelding @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bits PSD-bestanden in deze kleurmodus kunnen niet worden gelezen @msg the PSD file is cut short het PSD-bestand is afgekapt @msg the PSD file's header is damaged de header van het PSD-bestand is beschadigd @@ -5238,6 +5312,11 @@ mark-style Japanese Japans Softness Zachtheid Ambient Light Omgevingslicht Light behind the object Licht achter het object + Shadows Schaduwen + Distance from Object Afstand tot object + Shadow Bounds Schaduwgrenzen + Behind Object Achter object + Below Object Onder object 3D Lighting Preset Voorinstelling 3D-belichting Standard Standaard Diffuse Diffuus @@ -5381,7 +5460,7 @@ mark-style Japanese Japans @msg span must be "object" or "selection", got {v} span moet "object" of "selection" zijn, maar is {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" plaatst een `gradient`, geen staal @msg span: "selection" places a gradient: give `gradient` span: "selection" plaatst een verloop: geef `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" plaatst een lineair of radiaal verloop, geen vrij verloop +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" plaatst een lineair, radiaal, conisch of ruitvormig verloop, geen vrij verloop @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" plaatst het verloop zelf: laat `start` en `end` weg (die plaatsen het al in documentcoördinaten) Make Image Dynamic Afbeelding dynamisch maken Import Data Sets… Gegevenssets importeren… @@ -5848,6 +5927,7 @@ swatch Bright Violet Felviolet Ruby Ruby Geometric Guides Geometrische hulplijnen Geometric Patterns Geometrische patronen + Grit Textures Korrelige texturen Ease In Langzaam beginnen Ease Out Langzaam eindigen Ease In Out Langzaam beginnen en eindigen @@ -5901,6 +5981,7 @@ axis Y Axis Y-as Version: {version} Versie: {version} Install “{name}” in place of the plug-in with the same ID? „{name}” installeren in plaats van de plug-in met dezelfde ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Dit bestand is niet de plug-in die eerder met deze ID was geïnstalleerd. Het krijgt de instellingen en cache die voor die ID bewaard zijn. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Een automatisering heeft gevraagd deze plug-in te installeren. Kies zelf Object › Plug-ins › Plug-in installeren… om hem te installeren. File SHA-256: {hash} SHA-256 van het bestand: {hash} Read the objects it is given De objecten lezen die het krijgt Change, add and delete objects in the document Objecten in het document wijzigen, toevoegen en verwijderen @@ -5933,6 +6014,16 @@ axis Y Axis Y-as @msg message must be text message moet tekst zijn @msg allowContinue must be true or false allowContinue moet true of false zijn @msg Batch cannot play an action with a stop Batch kan geen actie met een stop afspelen + Insert Menu Item… Menu-item invoegen… + Insert Menu Item Menu-item invoegen + Menu Item: Menu-item: + No menu item matches. Geen menu-item komt overeen. + Several menu items match. Choose one from the list. Meerdere menu-items komen overeen. Kies er een uit de lijst. + Items that open a dialog, and File, Window and Help menu items, are not listed. Items die een dialoogvenster openen en items uit de menu’s Bestand, Venster en Help worden niet weergegeven. +@msg command must be text command moet tekst zijn +@msg no menu item that can be inserted runs this command geen invoegbaar menu-item voert deze opdracht uit +@msg the action already has 10,000 steps de actie heeft al 10.000 stappen +@msg the action set would be larger than 8 MiB de actieset zou groter worden dan 8 MiB Playback Options Afspeelopties Accelerated Versneld Step by Step Stap voor stap @@ -5966,6 +6057,12 @@ axis Y Axis Y-as Crosshair Vizier Checkpoint Controlepunt Inventory Icons Inventarisiconen + Skill Icons Vaardigheidsiconen + Attack Aanval + Defend Verdediging + Heal Genezen + Buff Buff + Ult Ult Sword Zwaard Shield Schild Potion Drank @@ -6024,7 +6121,23 @@ axis Y Axis Y-as Dash Trail Streepspoor Speed Line Snelheidslijn Game Trails Spelsporen + Energy Beams Energiestralen + Laser Bolt Laserbout + Plasma Arc Plasmaboog + Charge Wave Laadgolf + Spark Trail Vonkenspoor Calligraphic Nibs Kalligrafische penpunten + Bristle Brushes Borstelpenselen + Fine Liner Fijne liner + Pointed Flat Spitse platte + Stubby Round Korte ronde + Dry Scrub Droog schrobben + Soft Dome Zachte koepel + Filbert Kattentong + Angled Round Schuine ronde + Angled Flat Schuine platte + Fan Blender Vervloeiwaaier + Grass Fan Graswaaier Pattern Borders Patroonranden Scatter Shapes Strooivormen Save Brush Library… Penseelbibliotheek opslaan… @@ -6368,6 +6481,12 @@ breakText Glyphs Glyphs Delete the selected brushes? Geselecteerde kwasten verwijderen? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Contouren gebruiken een of meer van deze kwasten. De kwasten van deze contouren halen en de kwasten verwijderen? Remove Strokes Contouren verwijderen + Place Brush Art Penseelillustratie plaatsen + Replace Brush Art Penseelillustratie vervangen + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Contouren gebruiken dit penseel. De nieuwe illustratie op deze contouren toepassen, of ze laten zoals ze zijn en een kopie van het penseel met de nieuwe illustratie toevoegen? + Apply to Strokes Op contouren toepassen + Leave Strokes Contouren behouden +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` heeft geen illustratie (alleen verspreidings-, art- en patroonpenselen hebben er een) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Schikgereedschappen Arrange in Grid… In raster schikken… @@ -6550,6 +6669,11 @@ breakText Glyphs Glyphs No importer plug-ins installed Geen importplug-ins geïnstalleerd Read files you open in its format and make documents from them Bestanden lezen die u in zijn indeling opent en er documenten van maken +# Copy Troubleshooting Info + Copy Troubleshooting Info Probleemoplossingsgegevens kopiëren +@msg Copied the troubleshooting info Probleemoplossingsgegevens gekopieerd +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report De laatste sessie van VectorCraft reageerde niet meer voordat deze werd gesloten. Help › Probleemoplossingsgegevens kopiëren kopieert de details voor een foutrapport + # Safe Mode Safe Mode… Veilige modus… Safe Mode Veilige modus @@ -6570,6 +6694,8 @@ breakText Glyphs Glyphs # Align to Pixel Grid Align to Pixel Grid Uitlijnen op pixelraster + Align New Objects to Pixel Grid Nieuwe objecten uitlijnen op pixelraster + Not Aligned to Pixel Grid Niet uitgelijnd op pixelraster @msg side is left or right, not `{s}` side is left of right, niet `{s}` Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: @@ -6595,6 +6721,26 @@ breakText Glyphs Glyphs @plural {n} earlier line dropped|{n} earlier lines dropped {n} eerdere regel verwijderd|{n} eerdere regels verwijderd @plural {n} line cut|{n} lines cut {n} regel ingekort|{n} regels ingekort +# Learn panel + Learn Leren + Explore tutorials Tutorials verkennen + For you Voor jou + Skills Vaardigheden + Get started Aan de slag + Quick skill guide Snelgids voor vaardigheden + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Korte praktische tutorials voor de belangrijkste gereedschappen, gegroepeerd per vaardigheid. Kies een vaardigheid om de tutorials ervan te zien. + List Tutorials Tutorials weergeven + Show Tutorial Tutorial tonen +@msg missing `tutorial` (see learn.list) `tutorial` ontbreekt (zie learn.list) +@msg unknown tutorial `{id}` (see learn.list) onbekende tutorial `{id}` (zie learn.list) + # Deferred plug-in effects Refresh Deferred Effects Uitgestelde effecten vernieuwen Deferred Effects Uitgestelde effecten + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Snijgereedschap + Stencil Bridges… Sjabloonbruggen… + Stencil Bridges Sjabloonbruggen + Shortest Crossing Kortste oversteek + Direction Richting diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 398adf5f50..21543430d6 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -121,6 +121,7 @@ PDF Presets… Ustawienia PDF… Perspective Grid Presets… Ustawienia siatki perspektywy… Color Settings… Ustawienia kolorów… + Assign Profile Przypisz profil Assign Profile… Przypisz profil… Keyboard Shortcuts… Skróty klawiaturowe… Preferences… Preferencje… @@ -166,6 +167,15 @@ Expand… Rozszerz… Expand Appearance Rozszerz wygląd Crop Image Kadruj obraz + Image Tools Narzędzia obrazu + Remove Background… Usuń tło… + Remove Background Usuń tło + Background Tło + Edge Color Kolor krawędzi + Picked Colors Wybrane kolory + Corner Color Kolor narożników + Contiguous Ciągły + Each Channel Każdy kanał Edit Path Edytuj ścieżkę Mask Maska Rasterize… Rasteryzuj… @@ -216,6 +226,10 @@ Blend Options… Opcje przejścia… Expand Rozszerz Replace Spine Zastąp grzbiet + Create Spine Utwórz grzbiet + Create Spine: Utwórz grzbiet: + Always Zawsze + Never Nigdy Reverse Spine Odwróć grzbiet Reverse Front to Back Odwróć kolejność od przodu do tyłu Envelope Distort Zniekształcenie kopertowe @@ -350,6 +364,8 @@ Stair Step Schodki Gravity Grawitacja Type on a Path Options… Opcje tekstu na ścieżce… + Center on Top Wyśrodkuj na górze + Center on Bottom Wyśrodkuj na dole Threaded Text Tekst wątkowy Create Utwórz Release Selection Uwolnij zaznaczenie @@ -365,6 +381,15 @@ Smart Punctuation… Inteligentna interpunkcja… Create Outlines Utwórz kontury Optical Margin Alignment Optyczne wyrównanie marginesów + Dynamic Text Tekst dynamiczny + Dynamic Text Presets Ustawienia predefiniowane tekstu dynamicznego + Arch Sklepienie +@msg select point type or type on a path zaznacz tekst punktowy lub tekst na ścieżce +@msg type on a path in a thread cannot use Dynamic Text: {frames} tekst na ścieżce w tekście wątkowym nie może używać tekstu dynamicznego: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} nie można wyśrodkować na górze ani na dole tekstu na ścieżce otwartej lub złożonej: {open} +@msg type on a path with no length or no height cannot be centered: {flat} nie można wyśrodkować tekstu na ścieżce bez długości lub bez wysokości: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} nie można wyśrodkować na górze ani na dole tekstu na ścieżce w tekście wątkowym: {frames} +@msg select type on a closed path zaznacz tekst na zamkniętej ścieżce Fill with Placeholder Text Wypełnij tekstem zastępczym Insert Inline Symbol Wstaw symbol w tekście Show Hidden Characters Pokaż ukryte znaki @@ -436,6 +461,8 @@ Extrude & Bevel… Wyciągnięcie i fazowanie… 3D (Classic) 3D (klasyczne) Extrude & Bevel (Classic)… Wyciągnięcie i fazowanie (klasyczne)… + Revolve (Classic)… Obrót (klasyczny)… + Rotate (Classic)… Obróć (klasyczny)… Surface Powierzchnia Wireframe Szkielet No Shading Bez cieniowania @@ -509,6 +536,7 @@ Gaussian Blur… Rozmycie gaussowskie… View Widok Preview Podgląd + Preview: Podgląd: Overprint Preview Podgląd nadruku Pixel Preview Podgląd pikseli Trim View Widok przycięty @@ -737,8 +765,25 @@ Stun Pulse Ogłuszenie Stealth Fade Ukrycie Shield Buff Tarcza + Textures Tekstury + Fine Grain Drobne ziarno + Canvas Weave Splot płótna + Burlap Sack Worek jutowy + Cracked Glaze Spękana glazura + Mosaic Floor Mozaikowa posadzka + Quilted Squares Pikowane kwadraty + Leaded Glass Witraż ołowiany + Damp Paper Wilgotny papier Outlines and Rules Kontury i linie Hand-Drawn Rysowane odręcznie + Painted and Sketched Malowane i szkicowane + Washed Blue Rozmyty błękit + Bristle Ochre Ochra pędzlem + Pastel Heather Pastelowy wrzos + Charcoal Shade Cień węglem + Ink Contour Kontur tuszem + Wet Ink Mokry tusz + Fine Pen Cienkie pióro Gradient Finishes Wykończenia gradientowe Shape Effects Efekty kształtów Blends and Transparency Przejścia i przezroczystość @@ -758,6 +803,8 @@ Spectrum Gradients Gradienty widma Sky Gradients Gradienty nieba Neutral Gradients Gradienty neutralne + Organic Fades Organiczne zanikania + Holographic Holograficzne Duotone Gradients Gradienty dwutonowe Radial Glows Blaski promieniste Save Swatch Library… Zapisz bibliotekę próbek… @@ -817,6 +864,13 @@ Dock Panel Zadokuj panel Dock to Top Zadokuj u góry Dock to Bottom Zadokuj u dołu + Control Bar Options Opcje paska sterowania + Tool Options Opcje narzędzia + Object Options Opcje obiektu + Image Options Opcje obrazu + Vertical Alignment Wyrównanie w pionie + Align and Distribute Wyrównaj i rozmieść + Document Options Opcje dokumentu Dock Control Bar Zadokuj pasek sterowania Float Tool Group Odepnij grupę narzędzi Services Usługi @@ -1100,6 +1154,8 @@ lighting Light Światło Toolbar: Single/Double Column Pasek narzędzi: jedna/dwie kolumny Toolbar: Add Tool Pasek narzędzi: dodaj narzędzie Toolbar: Remove Tool Pasek narzędzi: usuń narzędzie + Add Tool… Dodaj narzędzie… + Remove Tool Usuń narzędzie Toolbar: Reset Pasek narzędzi: resetuj Two Point Perspective Preset 1 Ustawienie perspektywy dwupunktowej 1 Two Point Perspective Preset 2 Ustawienie perspektywy dwupunktowej 2 @@ -1460,6 +1516,7 @@ digits Malayalam Malajalam Roman Baseline Linia bazowa łacińska Select a text object to edit its character attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty znaków. Show Options Pokaż opcje + Show Recent Colors Pokaż ostatnie kolory Color Panel Options Opcje panelu Kolor Small Caps Kapitaliki Small Caps (on the roadmap) Kapitaliki (w planach) @@ -1488,6 +1545,8 @@ digits Malayalam Malajalam Scale at Center Skaluj od środka Up/Down: W górę/w dół: Left/Right: W lewo/w prawo: + Tate-chu-yoko Up/Down Tate-chu-yoko w górę/w dół + Tate-chu-yoko Left/Right Tate-chu-yoko w lewo/w prawo Underline Podkreślenie Vertical Scale % Skala pionowa % Axis Oś @@ -1590,6 +1649,8 @@ digits Malayalam Malajalam No gradient swatches Brak próbek gradientów Points: clicks add free points Punkty: kliknięcia dodają wolne punkty Radial Gradient Gradient promienisty + Conic Gradient Gradient stożkowy + Diamond Gradient Gradient rombowy Reset to White, Black Resetuj do bieli i czerni Reverse Gradient Odwróć gradient Save to Swatches Zapisz w próbkach @@ -1880,6 +1941,9 @@ digits Malayalam Malajalam Right Indent Wcięcie z prawej Right-to-Left Paragraph Direction Kierunek akapitu od prawej do lewej Roman Hanging Punctuation Wysunięta interpunkcja łacińska + Korean Line Break Anywhere Koreański podział wiersza w dowolnym miejscu + East Asian Composition Settings Ustawienia składu wschodnioazjatyckiego + Korean Composition Settings Ustawienia składu koreańskiego Select a text object to edit its paragraph attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty akapitu. Single-line Composer Kompozytor jednowierszowy Toggle Line Composer Przełącz kompozytor wierszy @@ -1966,6 +2030,7 @@ digits Malayalam Malajalam Simulate Paper Symuluj papier Use Black Point Compensation Użyj kompensacji punktu czerni Working CMYK (don't tag) Roboczy CMYK (bez znacznika) + Working RGB (don't tag) Roboczy RGB (bez znacznika) {name} (spot) {name} (dodatkowy) Add to Profiles… Dodaj do profili… Align Stroke to Center Wyrównaj obrys do środka @@ -2265,6 +2330,8 @@ digits Malayalam Malajalam Export Selected Art Only Eksportuj tylko zaznaczoną kompozycję Number of Colors: Liczba kolorów: Raster File Format: Format pliku rastrowego: + Include Placed Images Uwzględnij umieszczone obrazy + Include Fill Hatches Uwzględnij kreskowania wypełnień True colour needs version 2004 or later: the nearest of 256 colours is written. Pełny kolor wymaga wersji 2004 lub nowszej: zapisywany jest najbliższy z 256 kolorów. Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Tekst staje się konturami, a obrysy, których linia CAD nie narysuje, stają się wypełnionymi kształtami. Type stays text, and every stroke is a line with its lineweight and dashes. Tekst pozostaje tekstem, a każdy obrys jest linią z grubością i kreskami. @@ -2798,6 +2865,7 @@ antiAlias Sharp Ostre General › Thumbnails Ogólne › Miniatury Grayscale images Obrazy w skali szarości Include non-printing layers Uwzględnij warstwy niedrukowane + Write pages longer than 200 in at full size in points Zapisuj strony dłuższe niż 200 in w pełnym rozmiarze, w punktach Left: Lewy: Mark as trapped Oznacz jako z zalewkami Marks and Bleeds Znaczniki i spady @@ -4329,10 +4397,13 @@ imageTrace Outline Kontur @msg `groupColors` must be an array `groupColors` musi być tablicą @msg `library` is a library id or name (see {list}) `library` to identyfikator lub nazwa biblioteki (patrz {list}) @msg `mode` applies to freeform gradients `mode` dotyczy gradientów dowolnych +@msg a negative `aspect` applies to conic gradients ujemny `aspect` dotyczy gradientów stożkowych +@msg `focal` applies to radial gradients `focal` dotyczy gradientów radialnych @msg `preserve` must be an object `preserve` musi być obiektem @msg `globalAdjust` must be an object `globalAdjust` musi być obiektem @msg `sampleSize` must be 1, 3 or 5 `sampleSize` musi wynosić 1, 3 lub 5 @msg `stops` must be an array `stops` musi być tablicą +@msg `{key}` must be an array `{key}` musi być tablicą @msg `svg` must be an object of SVG options (see document.formats) `svg` musi być obiektem opcji SVG (patrz document.formats) @msg `{_1}` is no save command `{_1}` nie jest poleceniem zapisu @msg `{area}` is no recovery area name `{area}` nie jest nazwą obszaru odzyskiwania @@ -4346,6 +4417,7 @@ imageTrace Outline Kontur @msg `{key}` must be a number, not {v} `{key}` musi być liczbą, nie {v} @msg {key} must be Unix seconds (an integer) or null {key} musi być czasem Unix w sekundach (liczbą całkowitą) lub null @msg `{key}` must be a string `{key}` musi być ciągiem znaków +@msg `{key}` must be a profile name or null `{key}` musi być nazwą profilu lub null @msg `{key}` must be a whole number `{key}` musi być liczbą całkowitą @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` musi być liczbą całkowitą od {min} do {max} (podano {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` musi mieścić się w zakresie od {min} do {max} (podano {x}) @@ -4498,6 +4570,7 @@ imageTrace Outline Kontur @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller strona obszaru kompozycji {n} ma {size}, czyli więcej niż limit strony PDF wynoszący 14 400 pt (200 in): jest zapisywana z UserUnit {unit}, więc aplikacje ignorujące UserUnit pokazują ją tyle razy mniejszą @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in strona obszaru kompozycji {n} ma {size}, czyli więcej niż limit strony PDF wynoszący 14 400 pt (200 in): strony {label} są zapisywane bez UserUnit, w punktach, a aplikacje przestrzegające limitu przycinają stronę do 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 nie ma UserUnit, którego strona dłuższa niż 14 400 pt (200 in) potrzebuje, aby zachować rozmiar: plik jest zapisywany jako PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 nie ma UserUnit, którego strona dłuższa niż 14 400 pt (200 in) potrzebuje, aby zmieścić się w limicie strony PDF/A-2 wynoszącym 14 400 jednostek: plik jest zapisywany jako PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units strona obszaru kompozycji {n} ma {size} i jest za długa i za wąska dla boków strony PDF od 3 do 14 400 jednostek: jest zapisywana z UserUnit {unit}, która utrzymuje krótszy bok na co najmniej 3 jednostkach, a aplikacje przestrzegające limitu przycinają dłuższy bok do 14 400 jednostek @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard pliki {label} mieszczą liczby rzeczywiste do {max}, a strona obszaru kompozycji {n} o długości {side} pt wymaga większych: wybierz PDF 1.6 lub nowszy bez standardu PDF/X albo mniejszy obszar kompozycji @msg invalid image data for `{0}` nieprawidłowe dane obrazu dla `{0}` @@ -4647,6 +4720,8 @@ imageTrace Outline Kontur @msg not a stored central record to nie jest zapisany rekord centralny @msg not a valid plug-in module: {0} nieprawidłowy moduł wtyczki: {0} @msg not an EMF or WMF file to nie jest plik EMF ani WMF +@msg not an HP-GL file to nie jest plik HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` musi być tablicą od 1 do 255 kolorów #rrggbb @msg not found nie znaleziono @msg not in pattern editing mode nie jest w trybie edycji wzorka @msg finish editing the pattern first najpierw zakończ edycję wzorka @@ -4727,6 +4802,14 @@ imageTrace Outline Kontur @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 ten obrys utworzyłby ponad {max} punktów kontrolnych, więcej niż dokument może płynnie wyświetlić: zwiększ Szum, zmniejsz Ścieżki lub Kolory albo wybierz ustawienie o niższej wierności @msg select an envelope zaznacz kopertę @msg select an image zaznacz obraz +@msg `background` must be edges, corners or colors `background` musi mieć wartość edges, corners lub colors +@msg `match` must be distance or channels `match` musi mieć wartość distance lub channels +@msg `{key}` must be from 0 to 100 `{key}` musi mieścić się w zakresie od 0 do 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` musi zawierać od 1 do 16 kolorów, każdy szesnastkowo (#rrggbb lub #rgb) albo jako black, white, red, green lub blue +@msg the linked image shows its preview: embed or relink it first połączony obraz pokazuje podgląd: najpierw go osadź lub połącz ponownie +@msg a CMYK image has no transparency to set obraz CMYK nie ma przezroczystości, którą można ustawić +@msg every pixel matches the background: no image would be left każdy piksel pasuje do tła: nie zostałby żaden obraz +@msg an image of {w} × {h} pixels is too large to change obraz o wymiarach {w} × {h} pikseli jest zbyt duży, aby go zmienić @msg select an object in perspective zaznacz obiekt w perspektywie @msg select artwork (or a colour group) to recolor zaznacz kompozycję (lub grupę kolorów), aby zmienić kolory @msg Recolor completed; {locked} and {hidden} were left unchanged Zmiana kolorów zakończona; bez zmian: {locked} i {hidden} @@ -4833,7 +4916,7 @@ imageTrace Outline Kontur @msg unknown format nieznany format @msg unknown format `{f}` (Save writes {_1}) nieznany format `{f}` (zapis tworzy {_1}) @msg unknown freeform mode `{m}` (points, lines) nieznany tryb dowolny `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) nieznany rodzaj gradientu `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) nieznany rodzaj gradientu `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` nieznane wyróżnienie `{h}` @msg unknown option `{path}.{k}` nieznana opcja `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) nieznana wartość nadruków `{o}` (preserve, simulate lub discard) @@ -5033,6 +5116,8 @@ imageTrace Outline Kontur @msg invalid object id {value}: expected a non-negative integer nieprawidłowy identyfikator obiektu {value}: oczekiwano nieujemnej liczby całkowitej @msg `{key}` entry {index} is {value}, not a non-negative integer object id element {index} w `{key}` to {value}, a nie identyfikator obiektu (nieujemna liczba całkowita) @msg no such object id {value} brak obiektu o identyfikatorze {value} +@msg id {value} is a ruler guide, not an object identyfikator {value} należy do linii pomocniczej, a nie do obiektu +@msg a ruler guide goes only directly in a layer or sublayer linia pomocnicza może się znajdować tylko bezpośrednio w warstwie lub podwarstwie @msg id {value} is a layer, not an object identyfikator {value} oznacza warstwę, a nie obiekt @msg id {value} is a layer, not an object; move layers with layer.move identyfikator {value} oznacza warstwę, a nie obiekt; warstwy przenosi się za pomocą layer.move @msg automation filesystem access is not granted: read authority is absent: {path} nie przyznano dostępu automatyzacji do systemu plików: brak uprawnień do odczytu: {path} @@ -5062,7 +5147,13 @@ imageTrace Outline Kontur @msg the HEIC or HEIF file holds a kind of image that can't be read plik HEIC lub HEIF zawiera rodzaj obrazu, którego nie można odczytać @msg HEIC and HEIF images can't be opened in this build obrazów HEIC i HEIF nie można otworzyć w tej wersji @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD jest zbyt duży, aby go odczytać ({_1} × {_2} pikseli) -@msg zipped 32-bit PSD image data with prediction can't be read nie można odczytać spakowanych 32-bitowych danych obrazu PSD z predykcją +@msg zipped 1-bit PSD image data with prediction can't be read nie można odczytać spakowanych 1-bitowych danych obrazu PSD z predykcją +@msg the PSD file's layer data uses an unknown compression ({m}) dane warstw pliku PSD używają nieznanej kompresji ({m}) +@msg the PSD file's layer records are damaged rekordy warstw pliku PSD są uszkodzone +@msg the PSD file's layer groups are nested too deeply grupy warstw pliku PSD są zagnieżdżone zbyt głęboko +@msg a layer of the PSD file is too large to read warstwa pliku PSD jest zbyt duża, aby ją odczytać +@msg the PSD file's layers take more memory to read than allowed odczytanie warstw pliku PSD wymaga więcej pamięci, niż jest dozwolone +@msg the layers can't be read ({e}): the file opened as its merged image nie można odczytać warstw ({e}): plik otwarto jako jego scalony obraz @msg {depth}-bit PSD files in this colour mode can't be read nie można odczytać {depth}-bitowych plików PSD w tym trybie koloru @msg the PSD file is cut short plik PSD jest ucięty @msg the PSD file's header is damaged nagłówek pliku PSD jest uszkodzony @@ -5543,6 +5634,11 @@ mark-style Japanese Japońskie Softness Miękkość Ambient Light Światło otoczenia Light behind the object Światło za obiektem + Shadows Cienie + Distance from Object Odległość od obiektu + Shadow Bounds Granice cienia + Behind Object Za obiektem + Below Object Pod obiektem 3D Lighting Preset Ustawienie oświetlenia 3D Standard Standardowe Diffuse Rozproszone @@ -5621,7 +5717,7 @@ mark-style Japanese Japońskie @msg span must be "object" or "selection", got {v} span musi mieć wartość "object" lub "selection", a nie {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" umieszcza `gradient`, a nie próbkę @msg span: "selection" places a gradient: give `gradient` span: "selection" umieszcza gradient: podaj `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" umieszcza gradient liniowy lub radialny, a nie dowolny +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" umieszcza gradient liniowy, radialny, stożkowy lub rombowy, a nie dowolny @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" umieszcza sam gradient: pomiń `start` i `end` (one już umieszczają go we współrzędnych dokumentu) Make Image Dynamic Uczyń obraz dynamicznym Import Data Sets… Importuj zestawy danych… @@ -5805,6 +5901,7 @@ mark-style Japanese Japońskie Ruby Ruby Geometric Guides Geometryczne linie pomocnicze Geometric Patterns Wzorki geometryczne + Grit Textures Tekstury ziarniste Ease In Łagodny początek Ease Out Łagodny koniec Ease In Out Łagodny początek i koniec @@ -5863,6 +5960,8 @@ axis Y Axis Oś Y Version: {version} Wersja: {version} Install “{name}” in place of the plug-in with the same ID? Zainstalować „{name}” zamiast wtyczki o tym samym ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ten plik nie jest wtyczką zainstalowaną wcześniej z tym ID. Otrzyma ustawienia i pamięć podręczną przechowywane dla tego ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatyzacja poprosiła o zainstalowanie tej wtyczki. Aby ją zainstalować, wybierz Obiekt › Wtyczki › Zainstaluj wtyczkę… samodzielnie. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatyzacja poprosiła o zainstalowanie tej wtyczki. Aby ją zainstalować, wybierz Obiekt › Wtyczki › Zainstaluj wtyczkę… samodzielnie. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}” to inny moduł niż wtyczka o ID {_1} i otrzymałby przechowywane dla niej ustawienia i pamięć podręczną: zainstaluj go z `replace: true`, gdy użytkownik się zgodzi File SHA-256: {hash} SHA-256 pliku: {hash} Read the objects it is given Odczytywać obiekty, które otrzymuje @@ -5908,6 +6007,11 @@ axis Y Axis Oś Y @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budżet pamięci (obiekt {_1} wymaga {size} bajtów danych wejściowych, pozostało {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budżet obiektów (ponad {MAX_OBJECTS} obiektów tylko do odczytu) +@msg instruction budget budżet instrukcji +@msg time budget budżet czasu +@msg memory budget (the selection is too large to hand over) budżet pamięci (zaznaczenie jest zbyt duże, aby je przekazać) +@msg output size ({what} is {len} bytes, limit {max}) rozmiar wyjścia ({what} ma {len} bajtów, limit {max}) +@msg the plug-in's grant can't be removed from the plug-in store nie można usunąć uprawnienia wtyczki z magazynu wtyczek @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it uprawnienie `{shown}` jest zarezerwowane dla późniejszego API wtyczek; ten host go nie przyznaje @msg unknown permission `{shown}` nieznane uprawnienie `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}” prosi o uprawnienia {asked}: musi je zatwierdzić osoba w aplikacji desktopowej albo przekaż `grant` w sesji uruchomionej z --allow-plugin-grants @@ -5920,6 +6024,12 @@ axis Y Axis Oś Y @msg command {name}: `label` must be 1-64 printable characters polecenie {name}: `label` musi mieć 1-64 drukowalnych znaków @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter polecenie {name}: użyj id z 1-{MAX_COMMAND_ID} znaków spośród a-z 0-9 _, zaczynającego się od litery @msg command {name}: {e} polecenie {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} (wiersz {line}, kolumna {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` musi być listą poleceń, każde z `id` i `label` +@msg command {name} must be an object with an `id` and a `label` polecenie {name} musi być obiektem z `id` i `label` +@msg missing field `{key}` brak pola `{key}` +@msg duplicate field `{key}` zduplikowane pole `{key}` @msg only a filter or a live effect declares `commands` `commands` deklaruje tylko filtr lub efekt na żywo @msg “{name}” › {label}: {e} „{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed moduł nie ma skrótu SHA-256 podanego w `hash`: nic nie zainstalowano @@ -5944,6 +6054,16 @@ axis Y Axis Oś Y @msg message must be text message musi być tekstem @msg allowContinue must be true or false allowContinue musi mieć wartość true lub false @msg Batch cannot play an action with a stop Przetwarzanie wsadowe nie może odtworzyć operacji z zatrzymaniem + Insert Menu Item… Wstaw polecenie menu… + Insert Menu Item Wstaw polecenie menu + Menu Item: Polecenie menu: + No menu item matches. Żadne polecenie menu nie pasuje. + Several menu items match. Choose one from the list. Pasuje kilka poleceń menu. Wybierz jedno z listy. + Items that open a dialog, and File, Window and Help menu items, are not listed. Polecenia otwierające okno dialogowe oraz polecenia menu Plik, Okno i Pomoc nie są wyświetlane. +@msg command must be text command musi być tekstem +@msg no menu item that can be inserted runs this command żadne polecenie menu, które można wstawić, nie uruchamia tego polecenia +@msg the action already has 10,000 steps operacja ma już 10 000 kroków +@msg the action set would be larger than 8 MiB zestaw operacji byłby większy niż 8 MiB Playback Options Opcje odtwarzania Accelerated Przyspieszone Step by Step Krok po kroku @@ -5982,6 +6102,12 @@ axis Y Axis Oś Y Crosshair Celownik Checkpoint Punkt kontrolny Inventory Icons Ikony ekwipunku + Skill Icons Ikony umiejętności + Attack Atak + Defend Obrona + Heal Leczenie + Buff Wzmocnienie + Ult Ult Sword Miecz Shield Tarcza Potion Mikstura @@ -6046,7 +6172,23 @@ axis Y Axis Oś Y Dash Trail Ślad kreskowany Speed Line Linia prędkości Game Trails Ślady gry + Energy Beams Wiązki energii + Laser Bolt Pocisk laserowy + Plasma Arc Łuk plazmowy + Charge Wave Fala ładunku + Spark Trail Ślad iskier Calligraphic Nibs Stalówki kaligraficzne + Bristle Brushes Pędzle włosiankowe + Fine Liner Cienka linia + Pointed Flat Szpiczasty płaski + Stubby Round Krótki okrągły + Dry Scrub Suche szorowanie + Soft Dome Miękka kopuła + Filbert Koci język + Angled Round Skośny okrągły + Angled Flat Skośny płaski + Fan Blender Wachlarz do mieszania + Grass Fan Wachlarz do trawy Pattern Borders Obramowania wzorków Scatter Shapes Kształty rozproszone Save Brush Library… Zapisz bibliotekę pędzli… @@ -6244,9 +6386,12 @@ anchor Points: Punkty: @msg {label} must be a number {label} musi być liczbą @msg {label} must be a number of at least 0.1 {label} musi być liczbą co najmniej 0,1 Advanced Character Formats Zaawansowane formaty znaków + Basic Paragraph Formats Podstawowe formaty akapitu + Composition Skład Horizontal Scale Skala pozioma Vertical Scale Skala pionowa @msg {label} must be a number from {min} to {max} {label} musi być liczbą od {min} do {max} +@msg {label} must be a whole number from {min} to {max} {label} musi być liczbą całkowitą od {min} do {max} Character Color Kolor znaków OpenType Features Funkcje OpenType Stylistic Sets Zestawy stylistyczne @@ -6254,6 +6399,10 @@ anchor Points: Punkty: @msg features lists at most {max} tags features może zawierać najwyżej {max} znaczników @msg unknown OpenType feature `{t}` nieznana funkcja OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musi być liczbą większą od 0 i nie większą niż {max} +@msg {label} must be at most {max} characters {label} może mieć najwyżej {max} znaków +@msg {label} must be one character {label} musi być jednym znakiem +@msg at most {max} tab stops najwyżej {max} tabulatorów +@msg unknown align `{other}` nieznane wyrównanie `{other}` @msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6416,6 +6565,12 @@ breakText Glyphs Glify Delete the selected brushes? Usunąć zaznaczone pędzle? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Obrysy używają co najmniej jednego z tych pędzli. Zdjąć pędzle z tych obrysów i usunąć pędzle? Remove Strokes Usuń obrysy + Place Brush Art Umieść kompozycję pędzla + Replace Brush Art Zastąp kompozycję pędzla + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Obrysy używają tego pędzla. Zastosować nową kompozycję do tych obrysów, czy pozostawić je bez zmian i dodać kopię pędzla z nową kompozycją? + Apply to Strokes Zastosuj do obrysów + Leave Strokes Pozostaw obrysy +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` nie ma kompozycji (mają ją tylko pędzle rozproszone, artystyczne i wzorka) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Narzędzia układania Arrange in Grid… Ułóż w siatce… @@ -6611,6 +6766,11 @@ breakText Glyphs Glify @msg only an exporter or an importer declares `extensions` `extensions` deklaruje tylko wtyczka eksportu lub importu @msg an importer always gets an import's budget: leave `budget` out wtyczka importu zawsze dostaje budżet importu: pomiń `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Kopiuj informacje diagnostyczne +@msg Copied the troubleshooting info Skopiowano informacje diagnostyczne +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Ostatnia sesja VectorCraft przestała odpowiadać przed zamknięciem. Pomoc › Kopiuj informacje diagnostyczne kopiuje szczegóły do zgłoszenia błędu + # Safe Mode Safe Mode… Tryb awaryjny… Safe Mode Tryb awaryjny @@ -6631,6 +6791,8 @@ breakText Glyphs Glify # Align to Pixel Grid Align to Pixel Grid Wyrównaj do siatki pikseli + Align New Objects to Pixel Grid Wyrównaj nowe obiekty do siatki pikseli + Not Aligned to Pixel Grid Niewyrównane do siatki pikseli @msg only paths and compound paths can be aligned to the pixel grid do siatki pikseli można wyrównać tylko ścieżki i ścieżki złożone @msg side is left or right, not `{s}` side to left lub right, a nie `{s}` Ignore All Ignoruj wszystko @@ -6661,8 +6823,33 @@ breakText Glyphs Glify @plural {n} line cut|{n} lines cut {n} skrócony wiersz|{n} skrócone wiersze|{n} skróconych wierszy @msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` muszą być numerami wierszy przechowywanych w konsoli, `first` przed `last` +# Learn panel + Learn Nauka + Explore tutorials Przeglądaj samouczki + For you Dla Ciebie + Skills Umiejętności + Get started Pierwsze kroki + Quick skill guide Krótki przewodnik po umiejętnościach + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Krótkie praktyczne samouczki dotyczące podstawowych narzędzi, pogrupowane według umiejętności. Wybierz umiejętność, aby zobaczyć jej samouczki. + List Tutorials Wyświetl samouczki + Show Tutorial Pokaż samouczek +@msg missing `tutorial` (see learn.list) brak `tutorial` (patrz learn.list) +@msg unknown tutorial `{id}` (see learn.list) nieznany samouczek `{id}` (patrz learn.list) + # Deferred plug-in effects Refresh Deferred Effects Odśwież odroczone efekty Deferred Effects Odroczone efekty @msg no plug-in effect is deferred żaden efekt wtyczki nie jest odroczony @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Otwarto z {n} odroczonym efektem wtyczki. Efekt › Odśwież odroczone efekty go uruchamia.|Otwarto z {n} odroczonymi efektami wtyczek. Efekt › Odśwież odroczone efekty je uruchamia.|Otwarto z {n} odroczonymi efektami wtyczek. Efekt › Odśwież odroczone efekty je uruchamia. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Narzędzia do cięcia + Stencil Bridges… Mostki szablonu… + Stencil Bridges Mostki szablonu + Shortest Crossing Najkrótsze przejście + Direction Kierunek +@msg The selected art has no islands to bridge Zaznaczona grafika nie ma wysp do połączenia +@msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej grafice +@msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół grafiki +@msg `width` must be from {lo} to {hi} pt `width` musi mieścić się w zakresie od {lo} do {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` musi być liczbą całkowitą od 1 do {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9ede5521a8..906d4f1aee 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -255,6 +255,7 @@ antiAlias Sharp Nítido Asset Export Settings Configurações de Exportação de Ativos Assets Ativos Assign Atribuir + Assign Profile Atribuir Perfil Assign Profile… Atribuir Perfil… Assign: Atribuir: Attach to Active Plane Anexar ao Plano Ativo @@ -626,6 +627,15 @@ antiAlias Sharp Nítido Created: Criado: Crop Recortar Crop Image Recortar Imagem + Image Tools Ferramentas de imagem + Remove Background… Remover Fundo… + Remove Background Remover Fundo + Background Fundo + Edge Color Cor da Borda + Picked Colors Cores Escolhidas + Corner Color Cor dos Cantos + Contiguous Contíguo + Each Channel Cada Canal Edit Path Editar caminho Mask Máscara Crop Marks Marcas de Corte @@ -1036,6 +1046,8 @@ antiAlias Sharp Nítido Extrude & Bevel… Extrusão e Bisel… 3D (Classic) 3D (Clássico) Extrude & Bevel (Classic)… Extrusão e Bisel (Clássico)… + Revolve (Classic)… Revolver (Clássico)… + Rotate (Classic)… Girar (Clássico)… Surface Superfície Wireframe Aramado No Shading Sem Sombreamento @@ -1268,6 +1280,14 @@ antiAlias Sharp Nítido Hair Space Espaço Fino Hand Tool Ferramenta Mão Hand-Drawn Desenhado à Mão + Painted and Sketched Pintado e Esboçado + Washed Blue Azul Lavado + Bristle Ochre Ocre de Cerdas + Pastel Heather Urze Pastel + Charcoal Shade Sombra a Carvão + Ink Contour Contorno a Nanquim + Wet Ink Nanquim Úmido + Fine Pen Pena Fina Handles Alças Hard Light Luz Forte Hard Mix Mistura definida @@ -1456,6 +1476,7 @@ antiAlias Sharp Nítido Include SVG Code Incluir Código SVG Include Swatches for Tints Incluir Amostras para Tons Include non-printing layers Incluir camadas de não impressão + Write pages longer than 200 in at full size in points Gravar páginas com mais de 200 in em tamanho real, em pontos Inflate… Inflar… Info Informações Ink Tinta @@ -1930,6 +1951,15 @@ antiAlias Sharp Nítido Open… Abrir… Optical Óptico Optical Margin Alignment Alinhamento de Margem Óptica + Dynamic Text Texto Dinâmico + Dynamic Text Presets Predefinições de Texto Dinâmico + Arch Abóbada +@msg select point type or type on a path selecione texto de ponto ou texto em um caminho +@msg type on a path in a thread cannot use Dynamic Text: {frames} o texto em um caminho de um texto encadeado não pode usar Texto Dinâmico: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} o texto em um caminho aberto ou composto não pode ser centralizado em cima ou embaixo: {open} +@msg type on a path with no length or no height cannot be centered: {flat} o texto em um caminho sem comprimento ou sem altura não pode ser centralizado: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} o texto em um caminho de um texto encadeado não pode ser centralizado em cima ou embaixo: {frames} +@msg select type on a closed path selecione texto em um caminho fechado Optimize for fast web view Otimizar para visualização rápida na web Optimized Otimizado Options Opções @@ -1937,6 +1967,8 @@ antiAlias Sharp Nítido Options… Opções… Order: Ordem: Ordinals Ordinais + Organic Fades Esmaecimentos Orgânicos + Holographic Holográficos Orientation Orientação Orientation: Orientação: Original Original @@ -2104,6 +2136,7 @@ antiAlias Sharp Nítido Presets: Predefinidos: Press Pressione Preview Visualização + Preview: Visualização: Preview Mode Modo de Visualização Preview in Browser Visualizar no Navegador Preview the document as it is now Visualizar o documento como está agora @@ -2174,6 +2207,8 @@ digits Malayalam Malaiala Radial Radial Radial Glows Brilhos Radiais Radial Gradient Gradiente Radial + Conic Gradient Gradiente Cônico + Diamond Gradient Gradiente em Losango Radius: Raio: Rainbow Arco-íris Random Aleatório @@ -2183,6 +2218,8 @@ digits Malayalam Malaiala Range: Intervalo: Raster Effects Efeitos de Raster Raster File Format: Formato de Arquivo Raster: + Include Placed Images Incluir Imagens Inseridas + Include Fill Hatches Incluir Hachuras dos Preenchimentos Raster Sample Size: Tamanho da Amostra Raster: Raster/Vector Balance: Equilíbrio Raster/Vetor: Rasterize Unsupported Art Rasterizar Arte Não Suportada @@ -2338,6 +2375,10 @@ digits Malayalam Malaiala Replace: Substituir: Replace Font Substituir Fonte Replace Spine Substituir Coluna + Create Spine Criar Coluna + Create Spine: Criar Coluna: + Always Sempre + Never Nunca Replace Symbol Substituir Símbolo Reset Transformation Redefinir Transformação Replace With Font Substituir Com Fonte @@ -2410,6 +2451,9 @@ digits Malayalam Malaiala Rise… Rise… Roman Baseline Linha de Base Romana Roman Hanging Punctuation Pontuação Pendurada Romana + Korean Line Break Anywhere Quebra de Linha Coreana em Qualquer Lugar + East Asian Composition Settings Configurações de Composição do Leste Asiático + Korean Composition Settings Configurações de Composição Coreana Rotate Girar Rotate Tool Ferramenta Girar Rotate View Tool Ferramenta Girar Visualização @@ -2655,6 +2699,15 @@ digits Malayalam Malaiala Stun Pulse Atordoamento Stealth Fade Furtividade Shield Buff Escudo + Textures Texturas + Fine Grain Grão fino + Canvas Weave Trama de tela + Burlap Sack Saco de juta + Cracked Glaze Esmalte craquelado + Mosaic Floor Piso de mosaico + Quilted Squares Quadrados acolchoados + Leaded Glass Vitral de chumbo + Damp Paper Papel úmido Shape Forma Shape Builder Construtor de Formas Shape Builder Regions Regiões do Construtor de Formas @@ -2702,6 +2755,7 @@ digits Malayalam Malaiala Show List View Mostrar Exibição de Lista Show Note Mostrar Nota Show Options Mostrar Opções + Show Recent Colors Mostrar Cores Recentes Show Original Path Mostrar Caminho Original Open this dialog with these settings next time Abrir este diálogo com estas configurações na próxima vez Auto-Simplify Simplificar Automaticamente @@ -3018,6 +3072,8 @@ digits Malayalam Malaiala Type becomes outlines, and strokes a CAD line can't draw become filled shapes. O texto vira contornos, e os traços que uma linha CAD não pode desenhar viram formas preenchidas. Type on a Path Texto em um Caminho Type on a Path Options… Opções de Texto em um Caminho… + Center on Top Centralizar em Cima + Center on Bottom Centralizar em Baixo Type on a Path Tool Ferramenta Texto em um Caminho Type stays text, and every stroke is a line with its lineweight and dashes. O texto permanece texto, e todo traço é uma linha com sua espessura e tracejados. Type: Tipo: @@ -3283,6 +3339,13 @@ imageTrace Outline Contorno Dock Panel Encaixar Painel Dock to Top Encaixar na Parte Superior Dock to Bottom Encaixar na Parte Inferior + Control Bar Options Opções da Barra de Controle + Tool Options Opções de Ferramenta + Object Options Opções de Objeto + Image Options Opções de Imagem + Vertical Alignment Alinhamento Vertical + Align and Distribute Alinhar e Distribuir + Document Options Opções de Documento Dock Control Bar Encaixar Barra de Controle Float Tool Group Flutuar Grupo de Ferramentas Services Serviços @@ -3749,10 +3812,13 @@ axis Both Ambos @msg `groupColors` must be an array `groupColors` deve ser uma matriz @msg `library` is a library id or name (see {list}) `library` é o id ou o nome de uma biblioteca (veja {list}) @msg `mode` applies to freeform gradients `mode` se aplica a gradientes de forma livre +@msg a negative `aspect` applies to conic gradients um `aspect` negativo se aplica a gradientes cônicos +@msg `focal` applies to radial gradients `focal` se aplica a gradientes radiais @msg `preserve` must be an object `preserve` deve ser um objeto @msg `globalAdjust` must be an object `globalAdjust` deve ser um objeto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` deve ser 1, 3 ou 5 @msg `stops` must be an array `stops` deve ser uma matriz +@msg `{key}` must be an array `{key}` deve ser uma matriz @msg `svg` must be an object of SVG options (see document.formats) `svg` deve ser um objeto com opções de SVG (veja document.formats) @msg `{_1}` is no save command `{_1}` não é um comando de salvar @msg `{area}` is no recovery area name `{area}` não é o nome de uma área de recuperação @@ -3766,6 +3832,7 @@ axis Both Ambos @msg `{key}` must be a number, not {v} `{key}` deve ser um número, não {v} @msg {key} must be Unix seconds (an integer) or null {key} deve ser um tempo Unix em segundos (um inteiro) ou null @msg `{key}` must be a string `{key}` deve ser uma string +@msg `{key}` must be a profile name or null `{key}` deve ser um nome de perfil ou null @msg `{key}` must be a whole number `{key}` deve ser um número inteiro @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` deve ser um número inteiro entre {min} e {max} (recebido {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` deve estar entre {min} e {max} (recebido {x}) @@ -3910,6 +3977,7 @@ axis Both Ambos @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller a página da prancheta {n} tem {size}, mais que o limite de página do PDF de 14.400 pt (200 in): ela é gravada com um UserUnit de {unit}, então apps que ignoram UserUnit a mostram essa quantidade de vezes menor @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in a página da prancheta {n} tem {size}, mais que o limite de página do PDF de 14.400 pt (200 in): páginas {label} são gravadas sem UserUnit, em pontos, e apps que respeitam o limite cortam a página em 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 o PDF 1.5 não tem UserUnit, de que uma página com mais de 14.400 pt (200 in) precisa para manter seu tamanho: o arquivo é gravado como PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 o PDF 1.4 não tem UserUnit, de que uma página com mais de 14.400 pt (200 in) precisa para ficar dentro do limite de página do PDF/A-2, de 14.400 unidades: o arquivo é gravado como PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units a página da prancheta {n} tem {size}, longa e estreita demais para os lados de página do PDF, de 3 a 14.400 unidades: ela é gravada com uma UserUnit de {unit}, que mantém o lado menor em 3 unidades ou mais, e os apps que seguem o limite cortam o lado maior em 14.400 unidades @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard os arquivos {label} aceitam números reais de até {max}, e a página da prancheta {n}, com {side} pt, precisa de números maiores: escolha PDF 1.6 ou posterior sem padrão PDF/X, ou uma prancheta menor @msg invalid image data for `{0}` dados de imagem inválidos para `{0}` @@ -4057,6 +4125,8 @@ axis Both Ambos @msg not a stored central record não é um registro central armazenado @msg not a valid plug-in module: {0} não é um módulo de plug-in válido: {0} @msg not an EMF or WMF file não é um arquivo EMF ou WMF +@msg not an HP-GL file não é um arquivo HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` deve ser uma matriz de 1 a 255 cores #rrggbb @msg not found não encontrado @msg not in pattern editing mode não está no modo de edição de padrão @msg finish editing the pattern first termine de editar o padrão primeiro @@ -4135,6 +4205,14 @@ axis Both Ambos @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 esta vetorização geraria mais de {max} pontos de ancoragem, mais do que o documento consegue exibir com fluidez: aumente Ruído, reduza Traçados ou Cores, ou escolha uma predefinição de menor fidelidade @msg select an envelope selecione um envelope @msg select an image selecione uma imagem +@msg `background` must be edges, corners or colors `background` deve ser edges, corners ou colors +@msg `match` must be distance or channels `match` deve ser distance ou channels +@msg `{key}` must be from 0 to 100 `{key}` deve estar entre 0 e 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` deve listar de 1 a 16 cores, cada uma em hexadecimal (#rrggbb ou #rgb) ou como black, white, red, green ou blue +@msg the linked image shows its preview: embed or relink it first a imagem vinculada mostra sua prévia: incorpore-a ou revincule-a primeiro +@msg a CMYK image has no transparency to set uma imagem CMYK não tem transparência para definir +@msg every pixel matches the background: no image would be left todos os pixels correspondem ao fundo: nenhuma imagem restaria +@msg an image of {w} × {h} pixels is too large to change uma imagem de {w} × {h} pixels é grande demais para ser alterada @msg select an object in perspective selecione um objeto em perspectiva @msg select artwork (or a colour group) to recolor selecione uma arte-final (ou um grupo de cores) para recolorir @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloração concluída; sem alteração: {locked} e {hidden} @@ -4241,7 +4319,7 @@ axis Both Ambos @msg unknown format formato desconhecido @msg unknown format `{f}` (Save writes {_1}) formato desconhecido `{f}` (Salvar grava {_1}) @msg unknown freeform mode `{m}` (points, lines) modo de forma livre desconhecido `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) tipo de gradiente desconhecido `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) tipo de gradiente desconhecido `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` destaque desconhecido `{h}` @msg unknown option `{path}.{k}` opção desconhecida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressões desconhecidas `{o}` (preserve, simulate ou discard) @@ -4433,6 +4511,8 @@ axis Both Ambos @msg invalid object id {value}: expected a non-negative integer id de objeto inválido {value}: era esperado um inteiro não negativo @msg `{key}` entry {index} is {value}, not a non-negative integer object id a entrada {index} de `{key}` é {value}, não um id de objeto (inteiro não negativo) @msg no such object id {value} não existe objeto com o id {value} +@msg id {value} is a ruler guide, not an object o id {value} é de uma guia, não de um objeto +@msg a ruler guide goes only directly in a layer or sublayer uma guia só pode ficar diretamente em uma camada ou subcamada @msg id {value} is a layer, not an object o id {value} é uma camada, não um objeto @msg id {value} is a layer, not an object; move layers with layer.move o id {value} é uma camada, não um objeto; mova camadas com layer.move @msg automation filesystem access is not granted: read authority is absent: {path} o acesso da automação ao sistema de arquivos não foi concedido: falta autorização de leitura: {path} @@ -4462,7 +4542,13 @@ axis Both Ambos @msg the HEIC or HEIF file holds a kind of image that can't be read o arquivo HEIC ou HEIF contém um tipo de imagem que não pode ser lido @msg HEIC and HEIF images can't be opened in this build imagens HEIC e HEIF não podem ser abertas nesta versão @msg the PSD image is too large to read ({_1} × {_2} pixels) a imagem PSD é grande demais para ser lida ({_1} × {_2} pixels) -@msg zipped 32-bit PSD image data with prediction can't be read dados de imagem PSD de 32 bits compactados em zip com previsão não podem ser lidos +@msg zipped 1-bit PSD image data with prediction can't be read dados de imagem PSD de 1 bit compactados em zip com previsão não podem ser lidos +@msg the PSD file's layer data uses an unknown compression ({m}) os dados de camada do arquivo PSD usam uma compactação desconhecida ({m}) +@msg the PSD file's layer records are damaged os registros de camadas do arquivo PSD estão danificados +@msg the PSD file's layer groups are nested too deeply os grupos de camadas do arquivo PSD estão aninhados profundamente demais +@msg a layer of the PSD file is too large to read uma camada do arquivo PSD é grande demais para ser lida +@msg the PSD file's layers take more memory to read than allowed as camadas do arquivo PSD precisam de mais memória do que o permitido para serem lidas +@msg the layers can't be read ({e}): the file opened as its merged image as camadas não podem ser lidas ({e}): o arquivo foi aberto como sua imagem mesclada @msg {depth}-bit PSD files in this colour mode can't be read arquivos PSD de {depth} bits neste modo de cor não podem ser lidos @msg the PSD file is cut short o arquivo PSD está incompleto @msg the PSD file's header is damaged o cabeçalho do arquivo PSD está danificado @@ -4565,6 +4651,11 @@ axis Both Ambos Softness Suavidade Ambient Light Luz ambiente Light behind the object Luz atrás do objeto + Shadows Sombras + Distance from Object Distância do objeto + Shadow Bounds Limites da sombra + Behind Object Atrás do objeto + Below Object Abaixo do objeto 3D Lighting Preset Predefinição de iluminação 3D Standard Padrão Diffuse Difusa @@ -5021,6 +5112,8 @@ axis Both Ambos Scale at Center Dimensionar a partir do centro Up/Down: Para Cima/Para Baixo: Left/Right: Esquerda/Direita: + Tate-chu-yoko Up/Down Tate-chu-yoko Para Cima/Para Baixo + Tate-chu-yoko Left/Right Tate-chu-yoko Esquerda/Direita Temperature Temperatura Templates Modelos Text Wrap Options Opções de Quebra de Texto @@ -5032,6 +5125,8 @@ axis Both Ambos Tip on the end point Ponta no ponto final Toolbar: Add Tool Barra de Ferramentas: Adicionar Ferramenta Toolbar: Remove Tool Barra de Ferramentas: Remover Ferramenta + Add Tool… Adicionar Ferramenta… + Remove Tool Remover Ferramenta Toolbar: Reset Barra de Ferramentas: Redefinir Top Superior Top in Front Superior na Frente @@ -5064,6 +5159,7 @@ axis Both Ambos Weight Espessura Windows Windows Working CMYK (don't tag) CMYK de Trabalho (não marcar) + Working RGB (don't tag) RGB de Trabalho (não marcar) Workspace {i} Espaço de Trabalho {i} Yellow Amarelo [Normal Character Style] [Estilo de Caractere Normal] @@ -5651,7 +5747,7 @@ mark-style Japanese Japonesas @msg span must be "object" or "selection", got {v} span deve ser "object" ou "selection", não {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" posiciona um `gradient`, não uma amostra @msg span: "selection" places a gradient: give `gradient` span: "selection" posiciona um degradê: informe `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" posiciona um degradê linear ou radial, não um de forma livre +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" posiciona um degradê linear, radial, cônico ou em losango, não um de forma livre @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" posiciona o próprio degradê: omita `start` e `end` (eles já o posicionam em coordenadas do documento) Make Image Dynamic Tornar imagem dinâmica @msg Batch: {count} processed Lote: {count} processados @@ -5866,6 +5962,7 @@ mark-style Japanese Japonesas Ruby Ruby Geometric Guides Guias geométricas Geometric Patterns Padrões geométricos + Grit Textures Texturas granuladas Ease In Entrada suave Ease Out Saída suave Ease In Out Entrada e saída suaves @@ -5924,6 +6021,8 @@ axis Y Axis Eixo Y Version: {version} Versão: {version} Install “{name}” in place of the plug-in with the same ID? Instalar “{name}” no lugar do plug-in com o mesmo ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este arquivo não é o plug-in instalado antes com este ID. Ele recebe as configurações e o cache guardados para esse ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Uma automação pediu para instalar este plug-in. Para instalá-lo, escolha Objeto › Plug-ins › Instalar Plug-in… você mesmo. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Uma automação pediu para instalar este plug-in. Para instalá-lo, escolha Objeto › Plug-ins › Instalar Plug-in… você mesmo. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}” é um módulo diferente do plug-in com ID {_1} e receberia as configurações e o cache guardados para ele: instale-o com `replace: true` depois que o usuário concordar File SHA-256: {hash} SHA-256 do arquivo: {hash} Read the objects it is given Ler os objetos que recebe @@ -5969,6 +6068,11 @@ axis Y Axis Eixo Y @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) orçamento de memória (o objeto {_1} precisa de {size} bytes de entrada, restam {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) orçamento de objetos (mais de {MAX_OBJECTS} objetos somente leitura) +@msg instruction budget orçamento de instruções +@msg time budget orçamento de tempo +@msg memory budget (the selection is too large to hand over) orçamento de memória (a seleção é grande demais para ser entregue) +@msg output size ({what} is {len} bytes, limit {max}) tamanho da saída ({what} tem {len} bytes, limite {max}) +@msg the plug-in's grant can't be removed from the plug-in store a permissão do plug-in não pode ser removida do armazenamento de plug-ins @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a permissão `{shown}` está reservada para uma API de plug-in futura; este host não a concede @msg unknown permission `{shown}` permissão desconhecida `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” pede as permissões {asked}: uma pessoa precisa aprová-las no aplicativo de desktop, ou passe `grant` em uma sessão iniciada com --allow-plugin-grants @@ -5981,6 +6085,12 @@ axis Y Axis Eixo Y @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve ter 1-64 caracteres imprimíveis @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: use um id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que comece com uma letra @msg command {name}: {e} comando {name}: {e} +@msg manifest: {e} manifesto: {e} +@msg manifest: {e} at line {line} column {column} manifesto: {e} (linha {line}, coluna {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` deve ser uma lista de comandos, cada um com `id` e `label` +@msg command {name} must be an object with an `id` and a `label` o comando {name} deve ser um objeto com `id` e `label` +@msg missing field `{key}` falta o campo `{key}` +@msg duplicate field `{key}` campo `{key}` duplicado @msg only a filter or a live effect declares `commands` só um filtro ou um efeito dinâmico declara `commands` @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed o módulo não tem o SHA-256 indicado em `hash`: nada foi instalado @@ -6005,6 +6115,16 @@ axis Y Axis Eixo Y @msg message must be text message deve ser texto @msg allowContinue must be true or false allowContinue deve ser true ou false @msg Batch cannot play an action with a stop Lote não pode reproduzir uma ação com uma parada + Insert Menu Item… Inserir Item de Menu… + Insert Menu Item Inserir Item de Menu + Menu Item: Item de menu: + No menu item matches. Nenhum item de menu corresponde. + Several menu items match. Choose one from the list. Vários itens de menu correspondem. Escolha um da lista. + Items that open a dialog, and File, Window and Help menu items, are not listed. Itens que abrem uma caixa de diálogo e itens dos menus Arquivo, Janela e Ajuda não são listados. +@msg command must be text command deve ser texto +@msg no menu item that can be inserted runs this command nenhum item de menu que possa ser inserido executa este comando +@msg the action already has 10,000 steps a ação já tem 10.000 etapas +@msg the action set would be larger than 8 MiB o conjunto de ações ficaria maior que 8 MiB Playback Options Opções de Reprodução Accelerated Acelerada Step by Step Passo a Passo @@ -6043,6 +6163,12 @@ axis Y Axis Eixo Y Crosshair Mira Checkpoint Ponto de verificação Inventory Icons Ícones de inventário + Skill Icons Ícones de habilidade + Attack Ataque + Defend Defesa + Heal Cura + Buff Buff + Ult Ult Sword Espada Shield Escudo Potion Poção @@ -6107,7 +6233,23 @@ axis Y Axis Eixo Y Dash Trail Rastro tracejado Speed Line Linha de velocidade Game Trails Rastros de jogo + Energy Beams Feixes de energia + Laser Bolt Raio laser + Plasma Arc Arco de plasma + Charge Wave Onda de carga + Spark Trail Rastro de faíscas Calligraphic Nibs Penas Caligráficas + Bristle Brushes Pincéis de Cerdas + Fine Liner Traço Fino + Pointed Flat Chato Pontudo + Stubby Round Redondo Curto + Dry Scrub Esfregado Seco + Soft Dome Cúpula Suave + Filbert Língua de Gato + Angled Round Redondo Chanfrado + Angled Flat Chato Chanfrado + Fan Blender Leque Esfumador + Grass Fan Leque de Grama Pattern Borders Bordas de Padrão Scatter Shapes Formas de Dispersão Save Brush Library… Salvar Biblioteca de Pincéis… @@ -6305,9 +6447,12 @@ anchor Points: Pontos: @msg {label} must be a number {label} deve ser um número @msg {label} must be a number of at least 0.1 {label} deve ser um número de pelo menos 0,1 Advanced Character Formats Formatos avançados de caracteres + Basic Paragraph Formats Formatos básicos de parágrafo + Composition Composição Horizontal Scale Escala Horizontal Vertical Scale Escala Vertical @msg {label} must be a number from {min} to {max} {label} deve ser um número de {min} a {max} +@msg {label} must be a whole number from {min} to {max} {label} deve ser um número inteiro de {min} a {max} Character Color Cor do Caractere OpenType Features Recursos OpenType Stylistic Sets Conjuntos Estilísticos @@ -6315,6 +6460,10 @@ anchor Points: Pontos: @msg features lists at most {max} tags features aceita no máximo {max} marcas @msg unknown OpenType feature `{t}` recurso OpenType desconhecido `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve ser um número maior que 0 e no máximo {max} +@msg {label} must be at most {max} characters {label} deve ter no máximo {max} caracteres +@msg {label} must be one character {label} deve ser um único caractere +@msg at most {max} tab stops no máximo {max} paradas de tabulação +@msg unknown align `{other}` alinhamento desconhecido `{other}` @msg no character style `{name}` Estilo de caractere `{name}` não encontrado # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6478,6 +6627,12 @@ breakText Glyphs Glifos Delete the selected brushes? Excluir os pincéis selecionados? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Traçados usam um ou mais destes pincéis. Remover os pincéis desses traçados e excluir os pincéis? Remove Strokes Remover Traçados + Place Brush Art Colocar Arte do Pincel + Replace Brush Art Substituir Arte do Pincel + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Traçados usam este pincel. Aplicar a nova arte a esses traçados, ou deixá-los como estão e adicionar uma cópia do pincel com a nova arte? + Apply to Strokes Aplicar aos Traçados + Leave Strokes Manter Traçados +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` não tem arte (só os pincéis de dispersão, de arte e de padrão têm) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ferramentas de Organização Arrange in Grid… Organizar em Grade… @@ -6828,6 +6983,11 @@ swatch Yellow Green Verde-amarelado @msg only an exporter or an importer declares `extensions` só um plug-in de exportação ou de importação declara `extensions` @msg an importer always gets an import's budget: leave `budget` out um plug-in de importação sempre recebe o orçamento de uma importação: omita `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Copiar informações de solução de problemas +@msg Copied the troubleshooting info Informações de solução de problemas copiadas +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report A última sessão do VectorCraft parou de responder antes de fechar. Ajuda › Copiar informações de solução de problemas copia os detalhes para um relatório de bug + # Safe Mode Safe Mode… Modo de Segurança… Safe Mode Modo de Segurança @@ -6848,6 +7008,8 @@ swatch Yellow Green Verde-amarelado # Align to Pixel Grid Align to Pixel Grid Alinhar à Grade de Pixels + Align New Objects to Pixel Grid Alinhar Novos Objetos à Grade de Pixels + Not Aligned to Pixel Grid Não Alinhado à Grade de Pixels @msg only paths and compound paths can be aligned to the pixel grid somente caminhos e caminhos compostos podem ser alinhados à grade de pixels @msg side is left or right, not `{s}` side é left ou right, não `{s}` Ignore All Ignorar Tudo @@ -6878,8 +7040,33 @@ swatch Yellow Green Verde-amarelado @plural {n} line cut|{n} lines cut {n} linha cortada|{n} linhas cortadas @msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devem ser números de linhas que o console mantém, `first` antes de `last` +# Learn panel + Learn Aprender + Explore tutorials Explorar tutoriais + For you Para você + Skills Habilidades + Get started Primeiros passos + Quick skill guide Guia rápido de habilidades + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Tutoriais práticos curtos das ferramentas essenciais, agrupados por habilidade. Escolha uma habilidade para ver os tutoriais dela. + List Tutorials Listar Tutoriais + Show Tutorial Mostrar Tutorial +@msg missing `tutorial` (see learn.list) falta `tutorial` (veja learn.list) +@msg unknown tutorial `{id}` (see learn.list) tutorial desconhecido `{id}` (veja learn.list) + # Deferred plug-in effects Refresh Deferred Effects Atualizar Efeitos Adiados Deferred Effects Efeitos Adiados @msg no plug-in effect is deferred nenhum efeito de plug-in está adiado @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Aberto com {n} efeito de plug-in adiado. Efeito › Atualizar Efeitos Adiados o executa.|Aberto com {n} efeitos de plug-in adiados. Efeito › Atualizar Efeitos Adiados os executa. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Ferramentas de Corte + Stencil Bridges… Pontes de Estêncil… + Stencil Bridges Pontes de Estêncil + Shortest Crossing Travessia mais curta + Direction Direção +@msg The selected art has no islands to bridge A arte selecionada não tem ilhas para unir +@msg No bridge of this width fits across the selected art Nenhuma ponte desta largura cabe na arte selecionada +@msg Some islands could not be joined to the area around the art Algumas ilhas não puderam ser unidas à área ao redor da arte +@msg `width` must be from {lo} to {hi} pt `width` deve estar entre {lo} e {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` deve ser um número inteiro de 1 a {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 50eb9e969d..c147cf76df 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -260,6 +260,7 @@ font-technology Variable Вариативные Asset Export Settings Параметры экспорта ресурсов Assets Ресурсы Assign Назначить + Assign Profile Назначить профиль Assign Profile… Назначить профиль… Assign: Назначить: Attach to Active Plane Прикрепить к активной плоскости @@ -698,6 +699,15 @@ font-technology Variable Вариативные Created: Создано: Crop Обрезать Crop Image Обрезать изображение + Image Tools Инструменты изображения + Remove Background… Удалить фон… + Remove Background Удалить фон + Background Фон + Edge Color Цвет края + Picked Colors Выбранные цвета + Corner Color Цвет углов + Contiguous Смежные + Each Channel Каждый канал Edit Path Редактировать контур Mask Маска Crop Marks Метки обрезки @@ -1141,6 +1151,8 @@ font-technology Variable Вариативные Extrude & Bevel… Выдавливание и фаска… 3D (Classic) 3D (классические) Extrude & Bevel (Classic)… Выдавливание и фаска (классическое)… + Revolve (Classic)… Вращение (классическое)… + Rotate (Classic)… Поворот (классический)… Surface Поверхность Wireframe Каркас No Shading Без затенения @@ -1453,6 +1465,14 @@ file-filter Templates Шаблоны Hair Space Волосяная шпация Hand Tool Инструмент «Рука» Hand-Drawn Нарисованный от руки + Painted and Sketched Живопись и эскизы + Washed Blue Размытый синий + Bristle Ochre Охра кистью + Pastel Heather Пастельный вереск + Charcoal Shade Тень углём + Ink Contour Контур тушью + Wet Ink Влажная тушь + Fine Pen Тонкое перо Handles Маркеры Hard Light Жёсткий свет Hard Mix Жёсткое наложение @@ -1683,6 +1703,7 @@ file-filter Templates Шаблоны Include Linked Files Включать связанные файлы Include Metadata Включать метаданные Include non-printing layers Включать непечатаемые слои + Write pages longer than 200 in at full size in points Записывать страницы длиннее 200 in в полном размере, в пунктах Include SVG Code Включать код SVG Include Swatches for Tints Включать образцы для оттенков Inflate… Надувание… @@ -2359,12 +2380,23 @@ file-filter Templates Шаблоны Open… Открыть… Optical Оптический Optical Margin Alignment Оптическое выравнивание полей + Dynamic Text Динамический текст + Dynamic Text Presets Наборы параметров динамического текста + Arch Арка +@msg select point type or type on a path выберите точечный текст или текст по контуру +@msg type on a path in a thread cannot use Dynamic Text: {frames} текст по контуру в связанном тексте не может использовать динамический текст: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} нельзя центрировать вверху или внизу текст по незамкнутому или составному контуру: {open} +@msg type on a path with no length or no height cannot be centered: {flat} нельзя центрировать текст по контуру без длины или без высоты: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} нельзя центрировать вверху или внизу текст по контуру в связанном тексте: {frames} +@msg select type on a closed path выделите текст по замкнутому контуру Optimize for fast web view Оптимизировать для быстрого просмотра в web Optimized Оптимизировано Options Параметры Options for Selection… Параметры выделения… Options: Параметры: Options… Параметры… + Organic Fades Органические затухания + Holographic Голографические or more spaces with a tab или больше пробелов на табуляцию Order: Порядок: Ordinals Порядковые числительные @@ -2558,6 +2590,7 @@ diagnostics ui интерфейс Presets: Наборы: Press Нажмите Preview Просмотр + Preview: Просмотр: Preview All Layers Просмотреть все слои Preview in Browser Просмотреть в браузере Preview in Browser needs the desktop app (the web downloads files instead) Просмотр в браузере требует настольного приложения (web-версия скачивает файлы) @@ -2638,6 +2671,8 @@ digits Malayalam Малаялам Radial Радиальный Radial Glows Радиальные свечения Radial Gradient Радиальный градиент + Conic Gradient Конический градиент + Diamond Gradient Ромбовидный градиент Radius 1 Радиус 1 Radius 2 Радиус 2 Radius1 Радиус1 @@ -2650,6 +2685,8 @@ digits Malayalam Малаялам Range: Диапазон: Raster Effects Растровые эффекты Raster File Format: Формат растрового файла: + Include Placed Images Включать размещенные изображения + Include Fill Hatches Включать штриховку заливок Raster Sample Size: Размер растрового образца: Raster/Vector Balance: Баланс растровых/векторных: Rasterize Растеризовать @@ -2831,6 +2868,10 @@ digits Malayalam Малаялам Replace Font Заменить шрифт Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Замените его другим файлом или игнорируйте: его изображения продолжат показывать предварительный просмотр, сохранённый с документом. Replace Spine Заменить остов + Create Spine Создать остов + Create Spine: Создать остов: + Always Всегда + Never Никогда Replace Symbol Заменить символ Reset Transformation Сбросить трансформацию Replace With Font Заменить шрифтом @@ -2910,6 +2951,9 @@ digits Malayalam Малаялам Rise… Подъём… Roman Baseline Римская базовая линия Roman Hanging Punctuation Римская висячая пунктуация + Korean Line Break Anywhere Перенос корейского текста в любом месте + East Asian Composition Settings Параметры восточноазиатского набора + Korean Composition Settings Параметры корейского набора Rotate Повернуть Rotate 90° CW Повернуть на 90° по часовой стрелке Rotate Tool Инструмент «Поворот» @@ -3195,6 +3239,15 @@ digits Malayalam Малаялам Stun Pulse Оглушение Stealth Fade Скрытность Shield Buff Щит + Textures Текстуры + Fine Grain Мелкое зерно + Canvas Weave Холстяное плетение + Burlap Sack Мешковина + Cracked Glaze Потрескавшаяся глазурь + Mosaic Floor Мозаичный пол + Quilted Squares Стёганые квадраты + Leaded Glass Витражное стекло + Damp Paper Влажная бумага Shape Фигура Shape Builder Создание фигур Shape Builder Regions Области создания фигур @@ -3257,6 +3310,7 @@ digits Malayalam Малаялам Show Modified Показать изменённые Show Note Показать примечание Show Options Показать параметры + Show Recent Colors Показать последние цвета Show Original Path Показать исходный контур Open this dialog with these settings next time Открывать это диалоговое окно с этими параметрами в следующий раз Auto-Simplify Автоматическое упрощение @@ -3561,6 +3615,8 @@ digits Malayalam Малаялам Scale at Center Масштабировать от центра Up/Down: Вверх/вниз: Left/Right: Влево/вправо: + Tate-chu-yoko Up/Down Tate-chu-yoko вверх/вниз + Tate-chu-yoko Left/Right Tate-chu-yoko влево/вправо Temperature Температура Temperature/Tint… Температура/оттенок… Template Шаблон @@ -3630,6 +3686,8 @@ digits Malayalam Малаялам Toolbar: Single/Double Column Панель инструментов: один/два столбца Toolbar: Add Tool Панель инструментов: добавить инструмент Toolbar: Remove Tool Панель инструментов: убрать инструмент + Add Tool… Добавить инструмент… + Remove Tool Убрать инструмент Toolbar: Reset Панель инструментов: сбросить Toolbars Панели инструментов Tools Инструменты @@ -3701,6 +3759,8 @@ digits Malayalam Малаялам Type on a Path Текст по контуру Type on a Path Options Параметры текста по контуру Type on a Path Options… Параметры текста по контуру… + Center on Top Центрировать вверху + Center on Bottom Центрировать внизу Type on a Path Tool Инструмент «Текст по контуру» Type Orientation Ориентация текста Type stays text, and every stroke is a line with its lineweight and dashes. Текст остаётся текстом, и каждая обводка — линия с её толщиной и штрихами. @@ -3894,6 +3954,7 @@ digits Malayalam Малаялам Windows Windows Working CMYK Рабочий CMYK Working CMYK (don't tag) Рабочий CMYK (без пометки) + Working RGB (don't tag) Рабочий RGB (без пометки) Workspace Рабочая среда Workspace {i} Рабочая среда {i} Wrinkle Tool Инструмент «Морщины» @@ -4082,6 +4143,13 @@ axis Both Оба Dock Panel Прикрепить панель Dock to Top Прикрепить сверху Dock to Bottom Прикрепить снизу + Control Bar Options Параметры панели управления + Tool Options Параметры инструмента + Object Options Параметры объекта + Image Options Параметры изображения + Vertical Alignment Вертикальное выравнивание + Align and Distribute Выровнять и распределить + Document Options Параметры документа Dock Control Bar Прикрепить панель управления Drag to float the toolbar Перетащите, чтобы сделать панель инструментов плавающей Drag to the window's left or right edge to dock Перетащите к левому или правому краю окна для прикрепления @@ -4234,10 +4302,13 @@ axis Both Оба @msg `groupColors` must be an array `groupColors` должно быть массивом @msg `library` is a library id or name (see {list}) `library` — это идентификатор или имя библиотеки (см. {list}) @msg `mode` applies to freeform gradients `mode` применяется к произвольным градиентам +@msg a negative `aspect` applies to conic gradients отрицательный `aspect` применяется к коническим градиентам +@msg `focal` applies to radial gradients `focal` применяется к радиальным градиентам @msg `preserve` must be an object `preserve` должно быть объектом @msg `globalAdjust` must be an object `globalAdjust` должно быть объектом @msg `sampleSize` must be 1, 3 or 5 `sampleSize` должно быть 1, 3 или 5 @msg `stops` must be an array `stops` должно быть массивом +@msg `{key}` must be an array `{key}` должно быть массивом @msg `svg` must be an object of SVG options (see document.formats) `svg` должно быть объектом параметров SVG (см. document.formats) @msg `{_1}` is no save command `{_1}` не является командой сохранения @msg `{area}` is no recovery area name `{area}` не является именем области восстановления @@ -4251,6 +4322,7 @@ axis Both Оба @msg `{key}` must be a number, not {v} `{key}` должно быть числом, а не {v} @msg {key} must be Unix seconds (an integer) or null {key} должно быть временем Unix в секундах (целым числом) или null @msg `{key}` must be a string `{key}` должно быть строкой +@msg `{key}` must be a profile name or null `{key}` должно быть именем профиля или null @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 between {min} and {max} (got {x}) `{key}` должно быть от {min} до {max} (получено {x}) @@ -4403,6 +4475,7 @@ axis Both Оба @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller страница монтажной области {n} имеет размер {size}, что больше ограничения PDF на размер страницы в 14 400 pt (200 in): она записывается с UserUnit {unit}, поэтому приложения, которые игнорируют UserUnit, показывают её во столько же раз меньше @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in страница монтажной области {n} имеет размер {size}, что больше ограничения PDF на размер страницы в 14 400 pt (200 in): страницы {label} записываются без UserUnit, в пунктах, и приложения, соблюдающие ограничение, обрезают страницу до 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 в PDF 1.5 нет UserUnit, который нужен странице длиннее 14 400 pt (200 in), чтобы сохранить размер: файл записывается как PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 в PDF 1.4 нет UserUnit, который нужен странице длиннее 14 400 pt (200 in), чтобы уложиться в предел страницы PDF/A-2 в 14 400 единиц: файл записывается как PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units страница монтажной области {n} имеет размер {size} и слишком длинная и узкая для сторон страницы PDF от 3 до 14 400 единиц: она записывается с UserUnit {unit}, которая держит короткую сторону не меньше 3 единиц, а приложения, соблюдающие предел, обрезают длинную сторону до 14 400 единиц @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файлы {label} вмещают вещественные числа до {max}, а странице монтажной области {n} длиной {side} pt нужны большие: выберите PDF 1.6 или новее без стандарта PDF/X или монтажную область меньшего размера @msg invalid image data for `{0}` недопустимые данные изображения для `{0}` @@ -4551,6 +4624,8 @@ axis Both Оба @msg not a stored central record не является сохранённой центральной записью @msg not a valid plug-in module: {0} не является допустимым модулем: {0} @msg not an EMF or WMF file не является файлом EMF или WMF +@msg not an HP-GL file не является файлом HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` должен быть массивом из 1–255 цветов #rrggbb @msg not found не найдено @msg not in pattern editing mode не в режиме редактирования узора @msg finish editing the pattern first сначала завершите редактирование узора @@ -4630,6 +4705,14 @@ axis Both Оба @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} опорных точек, что больше, чем документ может плавно отобразить: увеличьте «Шум», уменьшите «Контуры» или «Цвета» либо выберите набор с меньшей точностью @msg select an envelope выделите оболочку @msg select an image выделите изображение +@msg `background` must be edges, corners or colors `background` должен быть edges, corners или colors +@msg `match` must be distance or channels `match` должен быть distance или channels +@msg `{key}` must be from 0 to 100 `{key}` должен быть от 0 до 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` должен содержать от 1 до 16 цветов, каждый в шестнадцатеричном виде (#rrggbb или #rgb) или как black, white, red, green или blue +@msg the linked image shows its preview: embed or relink it first связанное изображение показывает предпросмотр: сначала внедрите его или восстановите связь +@msg a CMYK image has no transparency to set у изображения CMYK нет прозрачности, которую можно задать +@msg every pixel matches the background: no image would be left каждый пиксель совпадает с фоном: от изображения ничего не осталось бы +@msg an image of {w} × {h} pixels is too large to change изображение размером {w} × {h} пикселей слишком велико для изменения @msg select an object in perspective выделите объект в перспективе @msg select artwork (or a colour group) to recolor выделите рисунок (или цветовую группу) для перекрашивания @msg Recolor completed; {locked} and {hidden} were left unchanged Перекрашивание завершено; без изменений: {locked} и {hidden} @@ -4736,7 +4819,7 @@ axis Both Оба @msg unknown format неизвестный формат @msg unknown format `{f}` (Save writes {_1}) неизвестный формат `{f}` (сохранение записывает {_1}) @msg unknown freeform mode `{m}` (points, lines) неизвестный режим произвольной формы `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) неизвестный тип градиента `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) неизвестный тип градиента `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` неизвестное выделение `{h}` @msg unknown option `{path}.{k}` неизвестный параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) неизвестные наложения `{o}` (preserve, simulate или discard) @@ -4964,6 +5047,8 @@ axis Both Оба @msg invalid object id {value}: expected a non-negative integer недопустимый идентификатор объекта {value}: ожидается неотрицательное целое число @msg `{key}` entry {index} is {value}, not a non-negative integer object id элемент {index} в `{key}` равен {value}, а не идентификатору объекта (неотрицательному целому числу) @msg no such object id {value} объект с идентификатором {value} не существует +@msg id {value} is a ruler guide, not an object идентификатор {value} принадлежит направляющей, а не объекту +@msg a ruler guide goes only directly in a layer or sublayer направляющая может находиться только непосредственно в слое или подслое @msg id {value} is a layer, not an object идентификатор {value} относится к слою, а не к объекту @msg id {value} is a layer, not an object; move layers with layer.move идентификатор {value} относится к слою, а не к объекту; перемещайте слои с помощью layer.move @msg automation filesystem access is not granted: read authority is absent: {path} у автоматизации нет доступа к файловой системе: нет права на чтение: {path} @@ -4993,7 +5078,13 @@ axis Both Оба @msg the HEIC or HEIF file holds a kind of image that can't be read файл HEIC или HEIF содержит изображение такого типа, которое не удается прочитать @msg HEIC and HEIF images can't be opened in this build изображения HEIC и HEIF нельзя открыть в этой сборке @msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.) -@msg zipped 32-bit PSD image data with prediction can't be read 32-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются +@msg zipped 1-bit PSD image data with prediction can't be read 1-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются +@msg the PSD file's layer data uses an unknown compression ({m}) данные слоёв файла PSD используют неизвестное сжатие ({m}) +@msg the PSD file's layer records are damaged записи слоёв файла PSD повреждены +@msg the PSD file's layer groups are nested too deeply группы слоёв файла PSD вложены слишком глубоко +@msg a layer of the PSD file is too large to read слой файла PSD слишком велик для чтения +@msg the PSD file's layers take more memory to read than allowed для чтения слоёв файла PSD нужно больше памяти, чем разрешено +@msg the layers can't be read ({e}): the file opened as its merged image не удаётся прочитать слои ({e}): файл открыт как сведённое изображение @msg {depth}-bit PSD files in this colour mode can't be read {depth}-битные файлы PSD в этом цветовом режиме не читаются @msg the PSD file is cut short файл PSD обрезан @msg the PSD file's header is damaged заголовок файла PSD повреждён @@ -5308,6 +5399,11 @@ lighting Light Свет Softness Мягкость Ambient Light Окружающий свет Light behind the object Свет позади объекта + Shadows Тени + Distance from Object Расстояние от объекта + Shadow Bounds Границы тени + Behind Object Позади объекта + Below Object Под объектом 3D Lighting Preset Предустановка 3D освещения Standard Стандартное Diffuse Рассеянное @@ -5375,7 +5471,7 @@ lighting Light Свет @msg span must be "object" or "selection", got {v} span должен быть "object" или "selection", а не {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 span: "selection" размещает линейный или радиальный градиент, а не произвольный +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" размещает линейный, радиальный, конический или ромбовидный градиент, а не произвольный @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" сам размещает градиент: уберите `start` и `end` (они уже задают его в координатах документа) Make Image Dynamic Сделать изображение динамическим Import Data Sets… Импортировать наборы данных… @@ -5560,6 +5656,7 @@ lighting Light Свет Ruby Руби Geometric Guides Геометрические направляющие Geometric Patterns Геометрические узоры + Grit Textures Зернистые текстуры Ease In Плавное начало Ease Out Плавное окончание Ease In Out Плавное начало и окончание @@ -5620,6 +5717,8 @@ axis Y Axis Ось Y Version: {version} Версия: {version} Install “{name}” in place of the plug-in with the same ID? Установить «{name}» вместо модуля с тем же ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Этот файл не является модулем, установленным ранее с этим ID. Он получит настройки и кэш, сохранённые для этого ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизация запросила установку этого модуля. Чтобы установить его, выберите «Объект › Модули › Установить модуль…» сами. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизация запросила установку этого модуля. Чтобы установить его, выберите «Объект › Модули › Установить модуль…» сами. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees «{name}» отличается от модуля с ID {_1} и получил бы сохранённые для него настройки и кэш: установите его с `replace: true`, когда пользователь согласится File SHA-256: {hash} SHA-256 файла: {hash} Read the objects it is given Читать переданные ему объекты @@ -5665,6 +5764,11 @@ axis Y Axis Ось Y @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет памяти (объекту {_1} нужно {size} байт входных данных, осталось {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет объектов (более {MAX_OBJECTS} объектов только для чтения) +@msg instruction budget бюджет инструкций +@msg time budget бюджет времени +@msg memory budget (the selection is too large to hand over) бюджет памяти (выделение слишком велико для передачи) +@msg output size ({what} is {len} bytes, limit {max}) размер вывода ({what}: {len} байт, предел {max}) +@msg the plug-in's grant can't be removed from the plug-in store разрешение модуля нельзя удалить из хранилища модулей @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it разрешение `{shown}` зарезервировано для будущего API модулей; этот хост его не выдаёт @msg unknown permission `{shown}` неизвестное разрешение `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants «{name}» запрашивает разрешения {asked}: их должен одобрить человек в настольном приложении, либо передайте `grant` в сеансе, запущенном с --allow-plugin-grants @@ -5677,6 +5781,12 @@ axis Y Axis Ось Y @msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` должен содержать 1-64 печатаемых символа @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: используйте id из 1-{MAX_COMMAND_ID} символов a-z 0-9 _, начинающийся с буквы @msg command {name}: {e} команда {name}: {e} +@msg manifest: {e} манифест: {e} +@msg manifest: {e} at line {line} column {column} манифест: {e} (строка {line}, столбец {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` должно быть списком команд, у каждой из которых есть `id` и `label` +@msg command {name} must be an object with an `id` and a `label` команда {name} должна быть объектом с `id` и `label` +@msg missing field `{key}` нет поля `{key}` +@msg duplicate field `{key}` поле `{key}` указано дважды @msg only a filter or a live effect declares `commands` `commands` объявляет только фильтр или динамический эффект @msg “{name}” › {label}: {e} «{name}» › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed у модуля не тот SHA-256, что указан в `hash`: ничего не установлено @@ -5701,6 +5811,16 @@ axis Y Axis Ось Y @msg message must be text message должно быть текстом @msg allowContinue must be true or false allowContinue должно быть true или false @msg Batch cannot play an action with a stop Пакет не может воспроизвести действие с остановкой + Insert Menu Item… Вставить пункт меню… + Insert Menu Item Вставить пункт меню + Menu Item: Пункт меню: + No menu item matches. Нет подходящих пунктов меню. + Several menu items match. Choose one from the list. Подходит несколько пунктов меню. Выберите один из списка. + Items that open a dialog, and File, Window and Help menu items, are not listed. Пункты, открывающие диалоговое окно, и пункты меню «Файл», «Окно» и «Справка» не показаны. +@msg command must be text command должно быть текстом +@msg no menu item that can be inserted runs this command ни один пункт меню, который можно вставить, не выполняет эту команду +@msg the action already has 10,000 steps в действии уже 10 000 шагов +@msg the action set would be larger than 8 MiB набор действий стал бы больше 8 MiB Playback Options Параметры воспроизведения Accelerated Ускоренно Step by Step Пошагово @@ -5739,6 +5859,12 @@ axis Y Axis Ось Y Crosshair Прицел Checkpoint Контрольная точка Inventory Icons Иконки инвентаря + Skill Icons Иконки навыков + Attack Атака + Defend Защита + Heal Лечение + Buff Усиление + Ult Ульт Sword Меч Shield Щит Potion Зелье @@ -5803,7 +5929,23 @@ axis Y Axis Ось Y Dash Trail Пунктирный след Speed Line Линия скорости Game Trails Игровые следы + Energy Beams Энергетические лучи + Laser Bolt Лазерный заряд + Plasma Arc Плазменная дуга + Charge Wave Волна заряда + Spark Trail Искра-след Calligraphic Nibs Каллиграфические перья + Bristle Brushes Щетинные кисти + Fine Liner Тонкий лайнер + Pointed Flat Заострённая плоская + Stubby Round Короткая круглая + Dry Scrub Сухое растирание + Soft Dome Мягкий купол + Filbert Кошачий язык + Angled Round Скошенная круглая + Angled Flat Скошенная плоская + Fan Blender Веер для растушёвки + Grass Fan Веер для травы Pattern Borders Узорные каймы Scatter Shapes Рассеянные фигуры Save Brush Library… Сохранить библиотеку кистей… @@ -6366,9 +6508,12 @@ anchor Points: Точки: @msg {label} must be a number {label} должно быть числом @msg {label} must be a number of at least 0.1 {label} должно быть числом не меньше 0,1 Advanced Character Formats Дополнительные форматы символов + Basic Paragraph Formats Основные форматы абзацев + Composition Компоновка Horizontal Scale Масштаб по горизонтали Vertical Scale Масштаб по вертикали @msg {label} must be a number from {min} to {max} {label} должно быть числом от {min} до {max} +@msg {label} must be a whole number from {min} to {max} {label} должно быть целым числом от {min} до {max} Character Color Цвет символов OpenType Features Функции OpenType Stylistic Sets Стилистические наборы @@ -6376,6 +6521,10 @@ anchor Points: Точки: @msg features lists at most {max} tags features содержит не более {max} тегов @msg unknown OpenType feature `{t}` неизвестная функция OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} должно быть числом больше 0 и не более {max} +@msg {label} must be at most {max} characters {label} должно содержать не более {max} символов +@msg {label} must be one character {label} должно быть одним символом +@msg at most {max} tab stops не более {max} позиций табуляции +@msg unknown align `{other}` неизвестное выравнивание `{other}` @msg no character style `{name}` Стиль символов `{name}` не найден # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6537,6 +6686,12 @@ breakText Glyphs Глифы Delete the selected brushes? Удалить выбранные кисти? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обводки используют одну или несколько из этих кистей. Убрать кисти с этих обводок и удалить кисти? Remove Strokes Убрать обводки + Place Brush Art Поместить рисунок кисти + Replace Brush Art Заменить рисунок кисти + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обводки используют эту кисть. Применить новый рисунок к этим обводкам или оставить их как есть и добавить копию кисти с новым рисунком? + Apply to Strokes Применить к обводкам + Leave Strokes Оставить обводки +@msg `{name}` has no art (only scatter, art and pattern brushes do) у `{name}` нет рисунка (он есть только у кистей-распылений, художественных и узорных кистей) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменты размещения Arrange in Grid… Разместить по сетке… @@ -6844,6 +6999,11 @@ shape Open Открытый @msg only an exporter or an importer declares `extensions` `extensions` объявляет только модуль экспорта или импорта @msg an importer always gets an import's budget: leave `budget` out модуль импорта всегда получает бюджет импорта: не указывайте `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Копировать сведения для устранения неполадок +@msg Copied the troubleshooting info Сведения для устранения неполадок скопированы +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Последний сеанс VectorCraft перестал отвечать перед закрытием. Справка › Копировать сведения для устранения неполадок копирует подробности для отчёта об ошибке + # Safe Mode Safe Mode… Безопасный режим… Safe Mode Безопасный режим @@ -6864,6 +7024,8 @@ shape Open Открытый # Align to Pixel Grid Align to Pixel Grid Выровнять по пиксельной сетке + Align New Objects to Pixel Grid Выравнивать новые объекты по пиксельной сетке + Not Aligned to Pixel Grid Не выровненные по пиксельной сетке @msg only paths and compound paths can be aligned to the pixel grid по пиксельной сетке можно выровнять только контуры и составные контуры @msg side is left or right, not `{s}` side — это left или right, а не `{s}` Ignore All Пропустить все @@ -6894,8 +7056,33 @@ shape Open Открытый @plural {n} line cut|{n} lines cut {n} строка обрезана|{n} строки обрезаны|{n} строк обрезано @msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` должны быть номерами строк, которые хранит консоль, причём `first` не позже `last` +# Learn panel + Learn Обучение + Explore tutorials Обзор уроков + For you Для вас + Skills Навыки + Get started Начало работы + Quick skill guide Краткое руководство по навыкам + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Короткие практические уроки по основным инструментам, сгруппированные по навыкам. Выберите навык, чтобы увидеть его уроки. + List Tutorials Перечислить уроки + Show Tutorial Показать урок +@msg missing `tutorial` (see learn.list) отсутствует `tutorial` (см. learn.list) +@msg unknown tutorial `{id}` (see learn.list) неизвестный урок `{id}` (см. learn.list) + # Deferred plug-in effects Refresh Deferred Effects Обновить отложенные эффекты Deferred Effects Отложенные эффекты @msg no plug-in effect is deferred нет отложенных эффектов модулей @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Открыто с {n} отложенным эффектом модуля. Эффект › Обновить отложенные эффекты выполнит его.|Открыто с {n} отложенными эффектами модулей. Эффект › Обновить отложенные эффекты выполнит их.|Открыто с {n} отложенными эффектами модулей. Эффект › Обновить отложенные эффекты выполнит их. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Инструменты резки + Stencil Bridges… Мостики трафарета… + Stencil Bridges Мостики трафарета + Shortest Crossing Кратчайшее пересечение + Direction Направление +@msg The selected art has no islands to bridge В выделенной графике нет островков для соединения +@msg No bridge of this width fits across the selected art Мостик такой ширины не помещается поперёк выделенной графики +@msg Some islands could not be joined to the area around the art Некоторые островки не удалось соединить с областью вокруг графики +@msg `width` must be from {lo} to {hi} pt `width` должно быть от {lo} до {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` должно быть целым числом от 1 до {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 60324bb91e..48d1cced76 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -251,6 +251,7 @@ font-technology Variable Variabla Asset Export Settings Inställningar för resursexport Assets Resurser Assign Tilldela + Assign Profile Tilldela profil Assign Profile… Tilldela profil… Assign: Tilldela: Attach to Active Plane Koppla till aktivt plan @@ -688,6 +689,15 @@ font-technology Variable Variabla Created: Skapad: Crop Beskär Crop Image Beskär bild + Image Tools Bildverktyg + Remove Background… Ta bort bakgrund… + Remove Background Ta bort bakgrund + Background Bakgrund + Edge Color Kantfärg + Picked Colors Valda färger + Corner Color Hörnfärg + Contiguous Sammanhängande + Each Channel Varje kanal Edit Path Redigera bana Mask Maskera Crop Marks Skärmärken @@ -1122,6 +1132,8 @@ font-technology Variable Variabla Extrude & Bevel… Extrudera och fasa… 3D (Classic) 3D (klassisk) Extrude & Bevel (Classic)… Extrudera och fasa (klassisk)… + Revolve (Classic)… Rotera runt axel (klassisk)… + Rotate (Classic)… Rotera (klassisk)… Surface Yta Wireframe Trådram No Shading Ingen skuggning @@ -1402,6 +1414,14 @@ font-technology Variable Variabla Hair Space Hårfint blanksteg Hand Tool Handverktyg Hand-Drawn Handritad + Painted and Sketched Målat och skissat + Washed Blue Urtvättad blå + Bristle Ochre Borstockra + Pastel Heather Pastelljung + Charcoal Shade Kolskugga + Ink Contour Tuschkontur + Wet Ink Våt tusch + Fine Pen Fin penna Handles Handtag Hard Light Hårt ljus Hard Mix Hård blandning @@ -1617,6 +1637,7 @@ font-technology Variable Variabla Include Linked Files Inkludera länkade filer Include Metadata Inkludera metadata Include non-printing layers Inkludera lager som inte skrivs ut + Write pages longer than 200 in at full size in points Skriv sidor längre än 200 in i full storlek i punkter Include SVG Code Inkludera SVG-kod Include Swatches for Tints Inkludera färgrutor för nyanser Inflate… Blås upp… @@ -2273,12 +2294,23 @@ font-technology Variable Variabla Open… Öppna… Optical Optisk Optical Margin Alignment Optisk marginaljustering + Dynamic Text Dynamisk text + Dynamic Text Presets Förinställningar för dynamisk text + Arch Valv +@msg select point type or type on a path markera punkttext eller text på bana +@msg type on a path in a thread cannot use Dynamic Text: {frames} text på bana i länkad text kan inte använda dynamisk text: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} text på en öppen eller sammansatt bana kan inte centreras överst eller nederst: {open} +@msg type on a path with no length or no height cannot be centered: {flat} text på en bana utan längd eller utan höjd kan inte centreras: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} text på bana i länkad text kan inte centreras överst eller nederst: {frames} +@msg select type on a closed path markera text på en sluten bana Optimize for fast web view Optimera för snabb webbvisning Optimized Optimerad Options Alternativ Options for Selection… Alternativ för markering… Options: Alternativ: Options… Alternativ… + Organic Fades Organiska toningar + Holographic Holografiska or more spaces with a tab eller fler blanksteg med en tabb Order: Ordning: Ordinals Ordningstal @@ -2468,6 +2500,7 @@ font-technology Variable Variabla Presets: Förinställningar: Press Tryck på Preview Förhandsgranskning + Preview: Förhandsgranskning: Preview All Layers Förhandsgranska alla lager Preview in Browser Förhandsgranska i webbläsare Preview in Browser needs the desktop app (the web downloads files instead) Förhandsgranska i webbläsare kräver skrivbordsappen (webbversionen hämtar filerna i stället) @@ -2546,6 +2579,8 @@ digits Malayalam Malayalam Radial Radiell Radial Glows Radiellt sken Radial Gradient Radiell gradient + Conic Gradient Konisk gradient + Diamond Gradient Rombgradient Radius 1 Radie 1 Radius 2 Radie 2 Radius1 Radie1 @@ -2558,6 +2593,8 @@ digits Malayalam Malayalam Range: Omfång: Raster Effects Rastereffekter Raster File Format: Rasterfilformat: + Include Placed Images Inkludera placerade bilder + Include Fill Hatches Inkludera skrafferingar av fyllningar Raster Sample Size: Samplingsstorlek för raster: Raster/Vector Balance: Raster-/vektorbalans: Rasterize Rastrera @@ -2738,6 +2775,10 @@ digits Malayalam Malayalam Replace Font Ersätt typsnitt Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Ersätt den med en annan fil eller ignorera den: dess bilder fortsätter att visa förhandsgranskningen som sparats med dokumentet. Replace Spine Ersätt ryggrad + Create Spine Skapa ryggrad + Create Spine: Skapa ryggrad: + Always Alltid + Never Aldrig Replace Symbol Ersätt symbol Reset Transformation Återställ transformering Replace With Font Ersätt med typsnitt @@ -2816,6 +2857,9 @@ digits Malayalam Malayalam Rise… Stigning… Roman Baseline Baslinje (roman) Roman Hanging Punctuation Hängande interpunktion (roman) + Korean Line Break Anywhere Koreansk radbrytning var som helst + East Asian Composition Settings Inställningar för östasiatisk sättning + Korean Composition Settings Inställningar för koreansk sättning Rotate Rotera Rotate 90° CW Rotera 90° medurs Rotate Tool Rotationsverktyg @@ -3087,6 +3131,15 @@ digits Malayalam Malayalam Stun Pulse Bedövning Stealth Fade Smyga Shield Buff Sköld + Textures Texturer + Fine Grain Fin kornighet + Canvas Weave Kanvasväv + Burlap Sack Jutesäck + Cracked Glaze Krackelerad glasyr + Mosaic Floor Mosaikgolv + Quilted Squares Quiltade rutor + Leaded Glass Blyinfattat glas + Damp Paper Fuktigt papper Shape Form Shape Builder Formbyggare Shape Builder Regions Formbyggarområden @@ -3149,6 +3202,7 @@ digits Malayalam Malayalam Show Modified Visa ändrade Show Note Visa anteckning Show Options Visa alternativ + Show Recent Colors Visa senaste färger Show Original Path Visa ursprunglig bana Open this dialog with these settings next time Öppna den här dialogrutan med de här inställningarna nästa gång Auto-Simplify Förenkla automatiskt @@ -3451,6 +3505,8 @@ digits Malayalam Malayalam Scale at Center Skala från mitten Up/Down: Upp/ned: Left/Right: Vänster/höger: + Tate-chu-yoko Up/Down Tate-chu-yoko upp/ned + Tate-chu-yoko Left/Right Tate-chu-yoko vänster/höger Temperature Temperatur Temperature/Tint… Temperatur/färgton… Template Mall @@ -3520,6 +3576,8 @@ digits Malayalam Malayalam Toolbar: Single/Double Column Verktygsfält: En/två kolumner Toolbar: Add Tool Verktygsfält: Lägg till verktyg Toolbar: Remove Tool Verktygsfält: Ta bort verktyg + Add Tool… Lägg till verktyg… + Remove Tool Ta bort verktyg Toolbar: Reset Verktygsfält: Återställ Toolbars Verktygsfält Tools Verktyg @@ -3590,6 +3648,8 @@ digits Malayalam Malayalam Type on a Path Text på bana Type on a Path Options Alternativ för text på bana Type on a Path Options… Alternativ för text på bana… + Center on Top Centrera överst + Center on Bottom Centrera nederst Type on a Path Tool Verktyg för text på bana Type Orientation Textorientering Type stays text, and every stroke is a line with its lineweight and dashes. Text förblir text, och varje kontur blir en linje med sin linjetjocklek och sina streck. @@ -3783,6 +3843,7 @@ digits Malayalam Malayalam Windows Windows Working CMYK Arbets-CMYK Working CMYK (don't tag) Arbets-CMYK (tagga inte) + Working RGB (don't tag) Arbets-RGB (tagga inte) Workspace Arbetslayout Workspace {i} Arbetslayout {i} Wrinkle Tool Skrynkelverktyg @@ -3961,6 +4022,13 @@ axis Both Båda Dock Panel Docka panel Dock to Top Docka överst Dock to Bottom Docka nederst + Control Bar Options Alternativ för kontrollfältet + Tool Options Verktygsalternativ + Object Options Objektalternativ + Image Options Bildalternativ + Vertical Alignment Vertikal justering + Align and Distribute Justera och fördela + Document Options Dokumentalternativ Dock Control Bar Docka kontrollfältet Drag to float the toolbar Dra för att göra verktygsfältet flytande Drag to the window's left or right edge to dock Dra till fönstrets vänster- eller högerkant för att docka @@ -4107,10 +4175,13 @@ axis Both Båda @msg `groupColors` must be an array `groupColors` måste vara en array @msg `library` is a library id or name (see {list}) `library` är ett biblioteks-id eller biblioteksnamn (se {list}) @msg `mode` applies to freeform gradients `mode` gäller för fria gradienter +@msg a negative `aspect` applies to conic gradients ett negativt `aspect` gäller för koniska gradienter +@msg `focal` applies to radial gradients `focal` gäller för radiella gradienter @msg `preserve` must be an object `preserve` måste vara ett objekt @msg `globalAdjust` must be an object `globalAdjust` måste vara ett objekt @msg `sampleSize` must be 1, 3 or 5 `sampleSize` måste vara 1, 3 eller 5 @msg `stops` must be an array `stops` måste vara en array +@msg `{key}` must be an array `{key}` måste vara en array @msg `svg` must be an object of SVG options (see document.formats) `svg` måste vara ett objekt med SVG-alternativ (se document.formats) @msg `{_1}` is no save command `{_1}` är inget sparkommando @msg `{area}` is no recovery area name `{area}` är inget namn på ett återställningsområde @@ -4270,6 +4341,7 @@ axis Both Båda @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller sidan för rityta {n} är {size}, längre än PDF:s sidgräns på 14 400 pt (200 in): den skrivs med en UserUnit på {unit}, så appar som ignorerar UserUnit visar den så många gånger mindre @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in sidan för rityta {n} är {size}, längre än PDF:s sidgräns på 14 400 pt (200 in): {label}-sidor skrivs utan UserUnit, i punkter, och appar som håller sig till gränsen beskär sidan till 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 har ingen UserUnit, som en sida längre än 14 400 pt (200 in) behöver för att behålla sin storlek: filen skrivs som PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 har ingen UserUnit, som en sida längre än 14 400 pt (200 in) behöver för att hålla sig inom PDF/A-2:s sidgräns på 14 400 enheter: filen skrivs som PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units sidan för rityta {n} är {size}, för lång och smal för PDF:s sidlängder på 3 till 14 400 enheter: den skrivs med UserUnit {unit}, som håller den korta sidan på minst 3 enheter, och appar som följer gränsen klipper den långa sidan vid 14 400 enheter @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-filer rymmer reella tal upp till {max}, och sidan för rityta {n}, {side} pt lång, behöver större: välj PDF 1.6 eller senare utan PDF/X-standard, eller en mindre rityta @msg invalid image data for `{0}` ogiltiga bilddata för `{0}` @@ -4418,6 +4490,8 @@ axis Both Båda @msg not a stored central record inte en lagrad central post @msg not a valid plug-in module: {0} inte ett giltigt plugin: {0} @msg not an EMF or WMF file inte en EMF- eller WMF-fil +@msg not an HP-GL file inte en HP-GL-fil +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` måste vara en array med 1 till 255 färger i formatet #rrggbb @msg not found hittades inte @msg not in pattern editing mode inte i läget för mönsterredigering @msg finish editing the pattern first slutför redigeringen av mönstret först @@ -4491,6 +4565,14 @@ axis Both Båda @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 spårningen skulle ge fler än {max} ankarpunkter, fler än dokumentet kan visa smidigt: höj Brus, sänk Banor eller Färger, eller välj en förinställning med lägre återgivning @msg select an envelope markera ett kuvert @msg select an image markera en bild +@msg `background` must be edges, corners or colors `background` måste vara edges, corners eller colors +@msg `match` must be distance or channels `match` måste vara distance eller channels +@msg `{key}` must be from 0 to 100 `{key}` måste vara från 0 till 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` måste lista 1 till 16 färger, var och en hexadecimalt (#rrggbb eller #rgb) eller som black, white, red, green eller blue +@msg the linked image shows its preview: embed or relink it first den länkade bilden visar sin förhandsvisning: bädda in eller länka om den först +@msg a CMYK image has no transparency to set en CMYK-bild har ingen transparens att ställa in +@msg every pixel matches the background: no image would be left varje pixel matchar bakgrunden: ingen bild skulle bli kvar +@msg an image of {w} × {h} pixels is too large to change en bild på {w} × {h} pixlar är för stor för att ändras @msg select an object in perspective markera ett objekt i perspektiv @msg select artwork (or a colour group) to recolor markera grafik (eller en färggrupp) att färga om @msg Recolor completed; {locked} and {hidden} were left unchanged Omfärgning klar; utan ändring: {locked} och {hidden} @@ -4597,7 +4679,7 @@ axis Both Båda @msg unknown format okänt format @msg unknown format `{f}` (Save writes {_1}) okänt format `{f}` (Spara skriver {_1}) @msg unknown freeform mode `{m}` (points, lines) okänt fritt läge `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) okänd gradienttyp `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) okänd gradienttyp `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` okänd högdager `{h}` @msg unknown option `{path}.{k}` okänt alternativ `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) okänt värde för övertryck `{o}` (preserve, simulate eller discard) @@ -4841,6 +4923,8 @@ axis Both Båda @msg invalid object id {value}: expected a non-negative integer ogiltigt objekt-id {value}: ett icke-negativt heltal förväntades @msg `{key}` entry {index} is {value}, not a non-negative integer object id post {index} i `{key}` är {value}, inte ett objekt-id (ett icke-negativt heltal) @msg no such object id {value} det finns inget objekt med id {value} +@msg id {value} is a ruler guide, not an object id {value} tillhör en stödlinje, inte ett objekt +@msg a ruler guide goes only directly in a layer or sublayer en stödlinje kan bara ligga direkt i ett lager eller underlager @msg id {value} is a layer, not an object id {value} är ett lager, inte ett objekt @msg id {value} is a layer, not an object; move layers with layer.move id {value} är ett lager, inte ett objekt; flytta lager med layer.move @msg automation filesystem access is not granted: read authority is absent: {path} automatiseringen har inte fått åtkomst till filsystemet: läsbehörighet saknas: {path} @@ -4870,7 +4954,13 @@ axis Both Båda @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC- eller HEIF-filen innehåller en typ av bild som inte kan läsas @msg HEIC and HEIF images can't be opened in this build HEIC- och HEIF-bilder kan inte öppnas i den här versionen @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD-bilden är för stor för att läsas ({_1} × {_2} pixlar) -@msg zipped 32-bit PSD image data with prediction can't be read zippad 32-bitars PSD-bilddata med prediktion kan inte läsas +@msg zipped 1-bit PSD image data with prediction can't be read zippad 1-bitars PSD-bilddata med prediktion kan inte läsas +@msg the PSD file's layer data uses an unknown compression ({m}) PSD-filens lagerdata använder en okänd komprimering ({m}) +@msg the PSD file's layer records are damaged PSD-filens lagerposter är skadade +@msg the PSD file's layer groups are nested too deeply PSD-filens lagergrupper är kapslade för djupt +@msg a layer of the PSD file is too large to read ett lager i PSD-filen är för stort för att läsas +@msg the PSD file's layers take more memory to read than allowed PSD-filens lager kräver mer minne för att läsas än vad som tillåts +@msg the layers can't be read ({e}): the file opened as its merged image lagren kan inte läsas ({e}): filen öppnades som sin sammanslagna bild @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitars PSD-filer i det här färgläget kan inte läsas @msg the PSD file is cut short PSD-filen är avkortad @msg the PSD file's header is damaged PSD-filens huvud är skadat @@ -5602,6 +5692,11 @@ theme Appearance Utseende Softness Mjukhet Ambient Light Omgivande ljus Light behind the object Ljus bakom objektet + Shadows Skuggor + Distance from Object Avstånd från objektet + Shadow Bounds Skuggans gränser + Behind Object Bakom objektet + Below Object Under objektet 3D Lighting Preset Förinställning för 3D-belysning Standard Standard Diffuse Diffust @@ -5737,7 +5832,7 @@ theme Appearance Utseende @msg span must be "object" or "selection", got {v} span måste vara "object" eller "selection", fick {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" placerar en `gradient`, inte en färgruta @msg span: "selection" places a gradient: give `gradient` span: "selection" placerar en gradient: ange `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" placerar en linjär eller radiell gradient, inte en fri +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" placerar en linjär, radiell, konisk eller rombformad gradient, inte en fri @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" placerar själva gradienten: utelämna `start` och `end` (de placerar den redan i dokumentkoordinater) @msg the Color Picker is not open färgväljaren är inte öppen @msg the Simplify slider is not open Förenkla-reglaget är inte öppet @@ -5974,6 +6069,7 @@ font-script Japanese Japanska Ruby Ruby Geometric Guides Geometriska stödlinjer Geometric Patterns Geometriska mönster + Grit Textures Korniga texturer Ease In Långsam start Ease Out Långsamt slut Ease In Out Långsam start och slut @@ -6032,6 +6128,8 @@ axis Y Axis Y-axel Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? Installera ”{name}” i stället för det plugin som har samma id? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Den här filen är inte det plugin som tidigare installerades med detta id. Den får de inställningar och den cache som sparats för detta id. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. En automatisering bad om att installera det här pluginet. Välj själv Objekt › Plugins › Installera plugin… för att installera det. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. En automatisering bad om att installera det här pluginet. Välj själv Objekt › Plugins › Installera plugin… för att installera det. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees ”{name}” är en annan modul än pluginet med id {_1} och skulle få de inställningar och den cache som sparats för det: installera det med `replace: true` när användaren har godkänt File SHA-256: {hash} Filens SHA-256: {hash} Read the objects it is given Läsa objekten den får @@ -6077,6 +6175,7 @@ axis Y Axis Y-axel @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) minnesbudget (objekt {_1} behöver {size} byte indata, {left} återstår) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (fler än {MAX_OBJECTS} skrivskyddade objekt) +@msg the plug-in's grant can't be removed from the plug-in store pluginets behörighet kan inte tas bort ur pluginlagret @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it behörigheten `{shown}` är reserverad för ett senare plugin-API; den här värden beviljar den inte @msg unknown permission `{shown}` okänd behörighet `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants ”{name}” begär behörigheterna {asked}: en person måste godkänna dem i skrivbordsappen, eller skicka `grant` i en session som startats med --allow-plugin-grants @@ -6089,6 +6188,11 @@ axis Y Axis Y-axel @msg command {name}: `label` must be 1-64 printable characters kommando {name}: `label` måste ha 1-64 utskrivbara tecken @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommando {name}: använd ett id med 1-{MAX_COMMAND_ID} tecken av a-z 0-9 _ som börjar med en bokstav @msg command {name}: {e} kommando {name}: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} (rad {line}, kolumn {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` måste vara en lista med kommandon, vart och ett med `id` och `label` +@msg command {name} must be an object with an `id` and a `label` kommandot {name} måste vara ett objekt med `id` och `label` +@msg missing field `{key}` fältet `{key}` saknas +@msg duplicate field `{key}` fältet `{key}` förekommer två gånger @msg only a filter or a live effect declares `commands` bara ett filter eller en live-effekt deklarerar `commands` @msg “{name}” › {label}: {e} ”{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modulen har inte den SHA-256 som `hash` anger: ingenting installerades @@ -6113,6 +6217,16 @@ axis Y Axis Y-axel @msg message must be text message måste vara text @msg allowContinue must be true or false allowContinue måste vara true eller false @msg Batch cannot play an action with a stop Batch kan inte spela upp en åtgärd med ett stopp + Insert Menu Item… Infoga menyalternativ… + Insert Menu Item Infoga menyalternativ + Menu Item: Menyalternativ: + No menu item matches. Inget menyalternativ matchar. + Several menu items match. Choose one from the list. Flera menyalternativ matchar. Välj ett i listan. + Items that open a dialog, and File, Window and Help menu items, are not listed. Alternativ som öppnar en dialogruta och alternativ i menyerna Fil, Fönster och Hjälp visas inte. +@msg command must be text command måste vara text +@msg no menu item that can be inserted runs this command inget menyalternativ som kan infogas kör det här kommandot +@msg the action already has 10,000 steps åtgärden har redan 10 000 steg +@msg the action set would be larger than 8 MiB åtgärdsuppsättningen skulle bli större än 8 MiB Playback Options Uppspelningsalternativ Accelerated Accelererad Step by Step Steg för steg @@ -6151,6 +6265,12 @@ axis Y Axis Y-axel Crosshair Hårkors Checkpoint Kontrollpunkt Inventory Icons Inventarieikoner + Skill Icons Färdighetsikoner + Attack Attack + Defend Försvar + Heal Läkning + Buff Buff + Ult Ult Sword Svärd Shield Sköld Potion Dryck @@ -6215,7 +6335,23 @@ axis Y Axis Y-axel Dash Trail Streckat spår Speed Line Hastighetslinje Game Trails Spår från spel + Energy Beams Energistrålar + Laser Bolt Laserbult + Plasma Arc Plasmabåge + Charge Wave Laddningsvåg + Spark Trail Gnistsvår Calligraphic Nibs Kalligrafiska pennspetsar + Bristle Brushes Borstpenslar + Fine Liner Fin linje + Pointed Flat Spetsig platt + Stubby Round Kort rund + Dry Scrub Torr skrubbning + Soft Dome Mjuk kupol + Filbert Oval platt + Angled Round Sned rund + Angled Flat Sned platt + Fan Blender Blandande solfjäder + Grass Fan Grässolfjäder Pattern Borders Mönsterbårder Scatter Shapes Spridningsformer Save Brush Library… Spara penselbibliotek… @@ -6441,9 +6577,12 @@ shape Open Öppen @msg {label} must be a number {label} måste vara ett tal @msg {label} must be a number of at least 0.1 {label} måste vara ett tal på minst 0,1 Advanced Character Formats Avancerade teckenformat + Basic Paragraph Formats Grundläggande styckeformat + Composition Sättning Horizontal Scale Horisontell skala Vertical Scale Vertikal skala @msg {label} must be a number from {min} to {max} {label} måste vara ett tal från {min} till {max} +@msg {label} must be a whole number from {min} to {max} {label} måste vara ett heltal från {min} till {max} Character Color Teckenfärg OpenType Features OpenType-funktioner Stylistic Sets Stilistiska uppsättningar @@ -6451,6 +6590,9 @@ shape Open Öppen @msg features lists at most {max} tags features får innehålla högst {max} taggar @msg unknown OpenType feature `{t}` okänd OpenType-funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} måste vara ett tal över 0 och högst {max} +@msg {label} must be at most {max} characters {label} får innehålla högst {max} tecken +@msg {label} must be one character {label} måste vara ett tecken +@msg at most {max} tab stops högst {max} tabbstopp @msg no character style `{name}` Teckenformatet `{name}` hittades inte # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6612,6 +6754,12 @@ breakText Glyphs Glyfer Delete the selected brushes? Radera de valda penslarna? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturer använder en eller flera av de här penslarna. Ta bort penslarna från konturerna och radera penslarna? Remove Strokes Ta bort konturer + Place Brush Art Placera penselgrafik + Replace Brush Art Ersätt penselgrafik + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturer använder den här penseln. Använd den nya grafiken på konturerna, eller låt dem vara som de är och lägg till en kopia av penseln med den nya grafiken? + Apply to Strokes Använd på konturer + Leave Strokes Behåll konturer +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` har ingen grafik (bara spridnings-, konst- och mönsterpenslar har grafik) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Ordningsverktyg Arrange in Grid… Ordna i rutnät… @@ -7372,7 +7520,7 @@ digits Hindi Hindi @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 EPS Save writes all artwork: use document.export for selected-only EPS När du sparar som EPS skrivs allt bildmaterial: använd document.export för 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"} @@ -7390,7 +7538,7 @@ digits Hindi Hindi @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 fit must be none|autoHeight|shrinkText|block, got {id} fit måste vara none|autoHeight|shrinkText|block, 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) @@ -8240,6 +8388,11 @@ digits Hindi Hindi @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importfunktion anger 1 till {MAX_EXTENSIONS} `extensions` @msg an importer always gets an import's budget: leave `budget` out en importfunktion får alltid en imports budget: utelämna `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Kopiera felsökningsinformation +@msg Copied the troubleshooting info Kopierade felsökningsinformationen +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Den senaste VectorCraft-sessionen slutade svara innan den stängdes. Hjälp › Kopiera felsökningsinformation kopierar detaljerna till en felrapport + # Safe Mode Safe Mode… Felsäkert läge… Safe Mode Felsäkert läge @@ -8260,6 +8413,8 @@ digits Hindi Hindi # Align to Pixel Grid Align to Pixel Grid Justera mot pixelrutnät + Align New Objects to Pixel Grid Justera nya objekt mot pixelrutnät + Not Aligned to Pixel Grid Inte justerade mot pixelrutnät @msg only paths and compound paths can be aligned to the pixel grid bara banor och sammansatta banor kan justeras mot pixelrutnätet @msg side is left or right, not `{s}` side är left eller right, inte `{s}` Ignore All Ignorera alla @@ -8290,8 +8445,33 @@ digits Hindi Hindi @plural {n} line cut|{n} lines cut {n} rad avkortad|{n} rader avkortade @msg `first` and `last` must be numbers of lines the console holds, first before last `first` och `last` måste vara nummer på rader som konsolen har kvar, `first` före `last` +# Learn panel + Learn Lär dig + Explore tutorials Utforska självstudier + For you För dig + Skills Färdigheter + Get started Kom igång + Quick skill guide Snabbguide till färdigheter + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Korta praktiska självstudier för de viktigaste verktygen, ordnade efter färdighet. Välj en färdighet för att se dess självstudier. + List Tutorials Lista självstudier + Show Tutorial Visa självstudie +@msg missing `tutorial` (see learn.list) `tutorial` saknas (se learn.list) +@msg unknown tutorial `{id}` (see learn.list) okänd självstudie `{id}` (se learn.list) + # Deferred plug-in effects Refresh Deferred Effects Uppdatera uppskjutna effekter Deferred Effects Uppskjutna effekter @msg no plug-in effect is deferred ingen plugineffekt är uppskjuten @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Öppnades med {n} uppskjuten plugineffekt. Effekt › Uppdatera uppskjutna effekter kör den.|Öppnades med {n} uppskjutna plugineffekter. Effekt › Uppdatera uppskjutna effekter kör dem. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Skärverktyg + Stencil Bridges… Schablonbryggor… + Stencil Bridges Schablonbryggor + Shortest Crossing Kortaste korsning + Direction Riktning +@msg The selected art has no islands to bridge Den markerade teckningen har inga öar att förbinda +@msg No bridge of this width fits across the selected art Ingen brygga med den här bredden får plats över den markerade teckningen +@msg Some islands could not be joined to the area around the art Vissa öar kunde inte förbindas med området runt teckningen +@msg `width` must be from {lo} to {hi} pt `width` måste vara från {lo} till {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` måste vara ett heltal från 1 till {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 79cbd7a648..ade1efa8be 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -194,6 +194,37 @@ fn marquee_selection_labels_are_in_complete_catalogs() { } } +/// The Control bar panel menu's items, its groups of options and the edges, and the label of the +/// command that turns a group on or off. +#[test] +fn control_bar_panel_menu_labels_are_in_complete_catalogs() { + const LABELS: [&str; 18] = [ + "Snapping", + "Anchor Points", + "Tool Options", + "Object Options", + "Image Options", + "Fill and Stroke", + "Opacity", + "Graphic Style", + "Character", + "Paragraph", + "Vertical Alignment", + "Align and Distribute", + "Transform", + "Artboard Options", + "Document Options", + "Dock to Top", + "Dock to Bottom", + "Control Bar Options", + ]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in LABELS { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// The Character panel's Anti-aliasing Method label and its choices, with the Sharp method's /// own `antiAlias` row apart from the plain "Sharp" corner row. #[test] @@ -207,6 +238,41 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() { } } +/// The Painted and Sketched graphic style library's name and its styles' names have a row in every +/// bundled catalog. +#[test] +fn painted_and_sketched_style_names_are_in_every_catalog() { + let lib = vectorcraft_doc::style_libs::builtin_style_library("painted-sketched").expect("built in"); + let labels: Vec<&str> = std::iter::once(lib.name.as_str()).chain(lib.styles.iter().map(|g| g.name.as_str())).collect(); + assert_eq!(labels.len(), 8); + for lang in LANGUAGES.iter().filter(|lang| !lang.source.is_empty()) { + for label in &labels { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + +/// The names the EPS options' menus show (preview, overprints, flattener preset and PostScript +/// level), and Save As's Preview label. +#[test] +fn eps_option_menu_names_are_in_complete_catalogs() { + use vectorcraft_engine::cmd::FlattenOptions; + use vectorcraft_eps::{Level, Overprint, Preview}; + let names: Vec<&str> = Preview::ALL + .map(Preview::label) + .into_iter() + .chain(Overprint::ALL.map(Overprint::label)) + .chain(Level::ALL.map(Level::label)) + .chain(FlattenOptions::PRESETS.into_iter().filter_map(FlattenOptions::preset_label)) + .chain(["Preview:"]) + .collect(); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in &names { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Each language counts with its own plural rule: the form a count picks (`one`, then `few`, then /// `other`/`many`). #[test] @@ -1878,7 +1944,7 @@ fn width(p: &Value, cmd: &str, key: &str) -> Result { } "##; let engine: Vec<_> = ERROR_HELPERS.iter().filter(|(c, _, _)| *c == "engine").map(|&(_, call, before)| (call, before)).collect(); - let found = source_messages(code, &engine); + let found = source_messages(code, &engine, &Default::default()); for want in [ "`{key}` must be a number", "the width can't be negative", @@ -1897,7 +1963,7 @@ fn width(p: &Value, cmd: &str, key: &str) -> Result { } let named = |m: &String| m.contains("not an error") || m.contains("not.an.error") || m.contains("not.a.reason"); assert!(!found.iter().any(named), "{found:#?}"); - let elsewhere = source_messages(code, &[]); + let elsewhere = source_messages(code, &[], &Default::default()); let in_variants = ["nested", "manifest", "nothing to clear", "panel is locked"]; assert!(elsewhere.len() == 4 && elsewhere.iter().all(|m| in_variants.iter().any(|w| m.contains(w))), "{elsewhere:#?}"); // A message read this way matches its row: `{key}` keeps its name. @@ -1905,6 +1971,108 @@ fn width(p: &Value, cmd: &str, key: &str) -> Result { assert_eq!(c.message("`width` must be a number").map(|m| m.1), Some(vec![("key", "width")])); } +/// The scan reads a message that an error or a status takes from a `&str` constant, by its name or +/// by its path, with `.into()`, `.to_string()` or nothing after it, and the constant declared in +/// another file. It does not read a constant that no error takes, a call of a name that a constant +/// also has, or a constant in a comment. +#[test] +fn message_scan_reads_messages_held_in_constants() { + let declared = r#" +pub(crate) const TOO_LARGE: &str = "the selection is too large to hand over"; +pub const SLOW: &'static str = "time budget"; +const UNUSED: &str = "not an error: a constant no error takes"; +const fn NOT_A_STR() -> u32 { 0 } +// const COMMENTED: &str = "not an error: a constant in a comment"; +"#; + let code = r#" +fn run() -> Result<()> { + let _ = Error::Limit(crate::runtime::TOO_LARGE.into()); + let _ = Err(Error::Limit(SLOW.to_string())); + let _ = Err(COMMENTED); + let _ = Err(SLOW(3)); + Ok(()) +} +"#; + let mut consts = std::collections::BTreeMap::new(); + for (name, value) in str_consts(declared) { + consts.entry(name).or_insert_with(Vec::new).push(value); + } + assert_eq!(consts.keys().collect::>(), ["SLOW", "TOO_LARGE", "UNUSED"]); + let found: std::collections::BTreeSet = source_messages(code, &[], &consts).into_iter().collect(); + assert_eq!(found.iter().collect::>(), ["the selection is too large to hand over", "time budget"]); + assert!(source_messages(code, &[], &Default::default()).is_empty()); +} + +/// The limits a plug-in run can exceed, and the error of a removal that leaves the plug-in's grant +/// in the plug-in store, are translated in every language that translates every message, as the +/// status bar shows them. +#[test] +fn plugin_limit_errors_are_translated() { + use vectorcraft_plugins::Error; + let scanned = message_literals(); + let grant = "the plug-in's grant can't be removed from the plug-in store"; + let templates = [ + "instruction budget", + "time budget", + "memory budget (the selection is too large to hand over)", + "output size ({what} is {len} bytes, limit {max})", + grant, + ]; + for template in templates { + assert!(scanned.contains(template), "{template}"); + } + let limits = [ + "instruction budget", + "time budget", + "memory budget (the selection is too large to hand over)", + "output size (the result is 9000 bytes, limit 4096)", + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for limit in limits { + let shown = message(lang, limit); + assert_ne!(shown, limit, "{code}"); + let whole = message(lang, &Error::Limit(limit.into()).to_string()); + assert!(whole.contains(&shown) && !whole.contains("exceeded"), "{code}: {whole}"); + } + let shown = message(lang, limits[3]); + assert!(shown.contains("9000") && shown.contains("4096") && !shown.contains("output size"), "{code}: {shown}"); + assert_ne!(message(lang, grant), grant, "{code}"); + } +} + +/// A manifest whose `commands` value has the wrong shape is refused with an error that every +/// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the +/// manifest included. +#[test] +fn wrongly_shaped_plugin_commands_errors_are_translated() { + let many: Vec = (0..=32).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect(); + let commands = [ + r#"{"id":"x"}"#.to_string(), + r#""x""#.to_string(), + "[1]".to_string(), + r#"[{"id":1,"label":"A"}]"#.to_string(), + r#"[{"id":"x","label":true}]"#.to_string(), + r#"[{"label":"B"}]"#.to_string(), + r#"[{"id":"x"}]"#.to_string(), + r#"[{"id":"x","id":"y","label":"A"}]"#.to_string(), + format!("[{}]", many.join(",")), + ]; + let english = ["must", "list", "missing", "field", "duplicate", "object", "line", "column", "each", "with", "invalid", "expected"]; + for value in &commands { + let manifest = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#); + let e = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap_err().to_string(); + let numbers: Vec<&str> = e.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &e); + // Backticked names stay in English; the words around them are translated. + let words: String = shown.split('`').step_by(2).collect(); + assert!(words.split(|c: char| !c.is_alphabetic()).all(|w| !english.contains(&w)), "{code}: {e} -> {shown}"); + assert!(numbers.iter().all(|n| shown.contains(n)), "{code}: {e} -> {shown}"); + } + } +} + /// The warnings of an Image Trace with keepColors, which the status bar shows and the scan above /// doesn't read, are translated in each language of [`COMPLETE_MESSAGES`], with the colors kept. #[test] @@ -2476,7 +2644,7 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("scale must be a number from {_1} to {_2}, not {_3}", &["scale"]), ("scale must be a number from {_1} to {_2}, not {s}", &["scale"]), ("show must be true or false", &["show"]), - ("span: \"selection\" places a linear or radial gradient, not a freeform one", &["span"]), + ("span: \"selection\" places a linear, radial, conic or diamond gradient, not a freeform one", &["span"]), ("thickness must be from 0.01 to 5000 pt", &["thickness"]), ("title can't be empty", &["title"]), ("view is required", &["view"]), @@ -2510,6 +2678,61 @@ fn translated_messages_keep_the_keys_and_values_their_english_names() { assert!(missing.is_empty(), "{} rows drop a key or value their English names:\n{}", missing.len(), missing.join("\n")); } +/// The command ids that `s` names outside its backticked spans, such as `assets.list` or +/// `window.panel.dock`: words of two or more dot-separated parts, each an ASCII letter or digit +/// run that starts with a lowercase letter. +fn command_ids(s: &str) -> Vec<&str> { + let mut ids = Vec::new(); + for part in s.split('`').step_by(2) { + for word in part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '.' || c == '_')) { + let word = word.trim_end_matches('.'); + let segments: Vec<&str> = word.split('.').collect(); + let dotted = segments.len() > 1 + && segments + .iter() + .all(|seg| seg.chars().next().is_some_and(|c| c.is_ascii_lowercase()) && seg.chars().all(|c| c.is_ascii_alphanumeric())); + if dotted && word != "e.g" && word != "i.e" { + ids.push(word); + } + } + } + ids +} + +#[test] +fn command_ids_finds_dotted_ids_outside_backticks() { + assert_eq!(command_ids("no slice {n} in the image (see slice.list)"), ["slice.list"]); + assert_eq!(command_ids("use window.panel.dock."), ["window.panel.dock"]); + assert_eq!(command_ids("output.destination: {e}"), ["output.destination"]); + assert_eq!(command_ids("(assets.list.old देखें)"), ["assets.list.old"]); + assert_eq!(command_ids("see `plugin.list`, e.g. 1.5 or {name}.svg"), Vec::<&str>::new()); +} + +/// A translated status or error message keeps each command id its English text names without +/// backticks, spelled as the English spells it, since that is the id a script or the command +/// palette runs. +#[test] +fn translated_messages_keep_the_command_ids_their_english_names() { + let mut missing = Vec::new(); + for l in &LANGUAGES { + let (entries, _) = parse_entries(l.source); + for (ctx, src, tr) in entries.iter().filter(|(ctx, _, _)| ctx == "@msg" || ctx == "@msgplural") { + let plural = ctx == "@msgplural"; + let english = if plural { src.rsplit('|').next().unwrap_or(src) } else { src.as_str() }; + let forms: Vec<&str> = if plural { tr.split('|').collect() } else { vec![tr.as_str()] }; + for form in forms { + let kept: Vec<&str> = command_ids(form).into_iter().chain(backticked(form)).collect(); + for id in command_ids(english) { + if !kept.contains(&id) { + missing.push(format!("{}: {id} in {src:?} -> {form:?}", l.code)); + } + } + } + } + } + assert!(missing.is_empty(), "{} rows drop a command id their English names:\n{}", missing.len(), missing.join("\n")); +} + /// Languages whose catalogs translate status and error messages; [`untranslated_report`] lists /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ @@ -2545,6 +2768,7 @@ const NOT_MESSAGES: &[&str] = &["quit", "cancelled"]; pub fn message_literals() -> std::collections::BTreeSet { let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); let mut out = std::collections::BTreeSet::new(); + let mut files = vec![]; let mut stack: Vec<_> = MESSAGE_CRATES.iter().map(|c| crates.join(c).join("src")).collect(); while let Some(d) = stack.pop() { for entry in std::fs::read_dir(&d).into_iter().flatten().flatten() { @@ -2558,22 +2782,61 @@ pub fn message_literals() -> std::collections::BTreeSet { // Control replies are English protocol data, never status-bar messages // (see i18n's module contract). Engine messages are scanned in their own crates. let text = std::fs::read_to_string(&path).unwrap_or_default(); - let helpers: Vec<_> = - ERROR_HELPERS.iter().filter(|(c, _, _)| path.starts_with(crates.join(c))).map(|&(_, call, before)| (call, before)).collect(); - out.extend(source_messages(without_test_module(&text), &helpers)); + files.push((path, text)); } } } + let mut consts = std::collections::BTreeMap::new(); + for (_, text) in &files { + for (name, value) in str_consts(without_test_module(text)) { + consts.entry(name).or_insert_with(Vec::new).push(value); + } + } + for (path, text) in &files { + let helpers: Vec<_> = + ERROR_HELPERS.iter().filter(|(c, _, _)| path.starts_with(crates.join(c))).map(|&(_, call, before)| (call, before)).collect(); + out.extend(source_messages(without_test_module(text), &helpers, &consts)); + } out } +/// The `&str` constants `code` declares outside its comments (`const NAME: &str = "…";`), with +/// their text, escapes resolved. +fn str_consts(code: &str) -> Vec<(String, String)> { + let code = &without_comments(code); + code.match_indices("const ") + .filter(|&(at, _)| !code[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_')) + .filter_map(|(at, m)| { + let rest = &code[at + m.len()..]; + let (name, rest) = rest.split_at(rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_')?); + let rest = rest.trim_start().strip_prefix(':')?.trim_start(); + let rest = rest.strip_prefix("&'static str").or_else(|| rest.strip_prefix("&str"))?.trim_start(); + let value = string_literal(rest.strip_prefix('=')?.trim_start().strip_prefix('"')?)?; + Some((name.to_string(), value)) + }) + .collect() +} + +/// The text of the constant that `rest` starts with, by name or by path (`TIME_BUDGET`, +/// `crate::runtime::SELECTION_TOO_LARGE.into()`), when `consts` holds it: every text, when crates +/// declare constants of that name with different texts. +fn named_const<'a>(rest: &str, consts: &'a std::collections::BTreeMap>) -> &'a [String] { + let path = &rest[..rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != ':').unwrap_or(rest.len())]; + let after = &rest[path.len()..]; + let used = [")", ",", ".into()", ".to_string()", ".to_owned()"].iter().any(|end| after.starts_with(end)); + let name = path.rsplit("::").next().unwrap_or(""); + let upper = name.starts_with(|c: char| c.is_ascii_uppercase()) && name.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'); + if used && upper { consts.get(name).map_or(&[], Vec::as_slice) } else { &[] } +} + /// The message literals in `code` outside its comments, as catalog templates (see /// [`message_literals`]): the literal after each of [`MESSAGE_MARKERS`], the message argument of an /// error enum's variant (the first, as in `PsError::Limit(…)` and `Error::Manifest(…)`, or the one /// [`LATER_MESSAGE_VARIANTS`] gives; not [`NAME_VARIANTS`]), /// and the message argument of each call in `helpers` (a call and the number of arguments before -/// its message), a literal or a `format!` string. -fn source_messages(code: &str, helpers: &[(&str, usize)]) -> Vec { +/// its message), a literal, a `format!` string or the name of one of `consts` (see +/// [`str_consts`]). +fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collections::BTreeMap>) -> Vec { let code = &without_comments(code); let after_markers = MESSAGE_MARKERS.iter().flat_map(|marker| code.match_indices(marker).map(|(at, _)| &code[at + marker.len()..])); let in_variants = code.match_indices("Error::").filter_map(|(at, m)| { @@ -2592,10 +2855,15 @@ fn source_messages(code: &str, helpers: &[(&str, usize)]) -> Vec { for rest in after_markers.chain(in_variants).chain(in_helpers) { let rest = rest.trim_start(); let rest = rest.strip_prefix("format!(").map_or(rest, str::trim_start); - let Some(lit) = rest.strip_prefix('"').and_then(string_literal) else { continue }; - let has_word = lit.as_bytes().windows(3).any(|w| w.iter().all(u8::is_ascii_lowercase)); - if has_word && !NOT_MESSAGES.contains(&lit.as_str()) { - out.push(as_template(&lit)); + let lits = match rest.strip_prefix('"') { + Some(quoted) => string_literal(quoted).into_iter().collect(), + None => named_const(rest, consts).to_vec(), + }; + for lit in lits { + let has_word = lit.as_bytes().windows(3).any(|w| w.iter().all(u8::is_ascii_lowercase)); + if has_word && !NOT_MESSAGES.contains(&lit.as_str()) { + out.push(as_template(&lit)); + } } } out diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 496dba8cf5..82fcc9364c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -247,6 +247,7 @@ font-technology Variable Değişken Asset Export Settings Varlık Dışa Aktarma Ayarları Assets Varlıklar Assign Ata + Assign Profile Profil Ata Assign Profile… Profil Ata… Assign: Ata: Attach to Active Plane Etkin Düzlem'e Ekle @@ -680,6 +681,15 @@ font-technology Variable Değişken Created: Oluşturuldu: Crop Kırpma Crop Image Resmi Kırp + Image Tools Resim Araçları + Remove Background… Arka Planı Kaldır… + Remove Background Arka Planı Kaldır + Background Arka Plan + Edge Color Kenar Rengi + Picked Colors Seçilen Renkler + Corner Color Köşe Rengi + Contiguous Bitişik + Each Channel Her Kanal Mask Maske Crop Marks Kırpma İşaretleri Crop To Kırpma Hedefi @@ -1114,6 +1124,8 @@ font-technology Variable Değişken Extrude & Bevel… Ekstrüzyon ve Eğim… 3D (Classic) 3D (Klasik) Extrude & Bevel (Classic)… Ekstrüzyon ve Eğim (Klasik)… + Revolve (Classic)… Döndür (Klasik)… + Rotate (Classic)… Çevir (Klasik)… Surface Yüzey Wireframe Tel Kafes No Shading Gölgeleme Yok @@ -1366,6 +1378,14 @@ font-technology Variable Değişken Hair Space Saç Alanı Hand Tool El Aracı Hand-Drawn elle çizilmiş + Painted and Sketched Boyanmış ve Eskiz + Washed Blue Soluk Mavi + Bristle Ochre Fırça Darbeli Toprak Sarısı + Pastel Heather Pastel Funda + Charcoal Shade Kömür Gölge + Ink Contour Mürekkep Kontur + Wet Ink Islak Mürekkep + Fine Pen İnce Kalem Handles Kollar Hard Light Sert Işık Harmony Rules: Uyum Kuralları: @@ -1497,6 +1517,7 @@ font-technology Variable Değişken Include Linked Files Bağlantılı Dosyaları Ekle Include Metadata Meta Verileri Ekle Include non-printing layers Yazdırılmayan katmanları dahil et + Write pages longer than 200 in at full size in points 200 in'den uzun sayfaları tam boyutta, punto olarak yaz Include SVG Code SVG Kodunu Ekle Include Swatches for Tints Renk Tonları için Renk Örneklerini Ekle Inflate… Şişir… @@ -2145,12 +2166,23 @@ shape Open Açık Open… Aç… Optical Optik Optical Margin Alignment Optik Kenar Boşluğu Hizalaması + Dynamic Text Dinamik Metin + Dynamic Text Presets Dinamik Metin Hazır Ayarları + Arch Kemer +@msg select point type or type on a path nokta metni veya yol üzerindeki yazıyı seçin +@msg type on a path in a thread cannot use Dynamic Text: {frames} zincirli metindeki yol üzerindeki yazı dinamik metin kullanamaz: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} açık veya bileşik bir yol üzerindeki yazı üstte veya altta ortalanamaz: {open} +@msg type on a path with no length or no height cannot be centered: {flat} uzunluğu ya da yüksekliği olmayan yol üzerindeki yazı ortalanamaz: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} zincirli metindeki yol üzerindeki yazı üstte veya altta ortalanamaz: {frames} +@msg select type on a closed path kapalı bir yol üzerindeki yazıyı seçin Optimize for fast web view Hızlı web görünümü için optimize edin Optimized Optimize edilmiş Options Seçenekler Options for Selection… Seçim Seçenekleri… Options: Seçenekler: Options… Seçenekler… + Organic Fades Organik Solmalar + Holographic Holografik or more spaces with a tab veya sekmeli daha fazla alan Order: Sipariş: Ordinals Sıra Sayıları @@ -2341,6 +2373,7 @@ shape Open Açık Presets: Ön ayarlar: Press Basın Preview Önizleme + Preview: Önizleme: Preview All Layers Tüm Katmanları Önizle Preview in Browser Tarayıcıda Önizleme Preview in Browser needs the desktop app (the web downloads files instead) Tarayıcıdaki önizleme için masaüstü uygulaması gerekir (bunun yerine web, dosyaları indirir) @@ -2418,6 +2451,8 @@ digits Malayalam Malayalam Radial Radyal Radial Glows Radyal Parıltılar Radial Gradient Radyal Gradyan + Conic Gradient Konik Gradyan + Diamond Gradient Elmas Gradyan Radius 1 Yarıçap 1 Radius 2 Yarıçap 2 Radius1 Yarıçap1 @@ -2430,6 +2465,8 @@ digits Malayalam Malayalam Range: Aralık: Raster Effects Raster Efektleri Raster File Format: Raster Dosya Formatı: + Include Placed Images Yerleştirilen Görüntüleri Dahil Et + Include Fill Hatches Dolgu Taramalarını Dahil Et Raster Sample Size: Raster Örnek Boyutu: Raster/Vector Balance: Raster/Vektör Dengesi: Rasterize Rasterleştir @@ -2607,6 +2644,10 @@ digits Malayalam Malayalam Replace Font Yazı Tipini Değiştir Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Onu başka bir dosyayla değiştirin veya yok sayın: resimleri, belgeyle birlikte kaydedilen önizlemeyi göstermeye devam eder. Replace Spine Omurgayı Değiştir + Create Spine Omurga Oluştur + Create Spine: Omurga Oluştur: + Always Her Zaman + Never Asla Replace Symbol Sembolü Değiştir Reset Transformation Dönüşümü Sıfırla Replace With Font Yazı Tipiyle Değiştir @@ -2683,6 +2724,9 @@ digits Malayalam Malayalam Rise… Yüksel… Roman Baseline Roma Taban Çizgisi Roman Hanging Punctuation Roma Asılı Noktalama İşaretleri + Korean Line Break Anywhere Korece Satırı Her Yerde Kes + East Asian Composition Settings Doğu Asya Dizgi Ayarları + Korean Composition Settings Korece Dizgi Ayarları Rotate Döndür Rotate 90° CW 90° CW döndür Rotate Tool Döndürme Aracı @@ -2991,6 +3035,15 @@ digits Malayalam Malayalam Stun Pulse Sersemletme Stealth Fade Gizlilik Shield Buff Kalkan + Textures Dokular + Fine Grain İnce Gren + Canvas Weave Kanvas Dokuma + Burlap Sack Çuval Bezi + Cracked Glaze Çatlak Sır + Mosaic Floor Mozaik Zemin + Quilted Squares Kapitone Kareler + Leaded Glass Kurşunlu Cam + Damp Paper Nemli Kâğıt Shape Şekil Shape Builder Şekil Oluşturucu Shape Builder Regions Şekil Oluşturucu Bölgeleri @@ -3053,6 +3106,7 @@ digits Malayalam Malayalam Show Modified Değiştirilenleri Göster Show Note Notu Göster Show Options Seçenekleri Göster + Show Recent Colors Son Renkleri Göster Show Original Path Orijinal Yolu Göster Color Panel Options Renk Paneli Seçenekleri Show Package Paketi Göster @@ -3342,6 +3396,8 @@ digits Malayalam Malayalam Scale at Center Merkezden Ölçekle Up/Down: Yukarı/Aşağı: Left/Right: Sol/Sağ: + Tate-chu-yoko Up/Down Tate-chu-yoko Yukarı/Aşağı + Tate-chu-yoko Left/Right Tate-chu-yoko Sol/Sağ Temperature Sıcaklık Temperature/Tint… Sıcaklık/Renk Tonu… Template Şablon @@ -3409,6 +3465,8 @@ digits Malayalam Malayalam Toolbar: Single/Double Column Araç Çubuğu: Tek/Çift Sütun Toolbar: Add Tool Araç Çubuğu: Araç Ekle Toolbar: Remove Tool Araç Çubuğu: Aracı Kaldır + Add Tool… Araç Ekle… + Remove Tool Aracı Kaldır Toolbar: Reset Araç Çubuğu: Sıfırla Toolbars Araç çubukları Tools Araçlar @@ -3478,6 +3536,8 @@ digits Malayalam Malayalam Type on a Path Bir Yola Yazın Type on a Path Options Yol Seçenekleri Üzerine Yazma Type on a Path Options… Yol Seçenekleri Üzerine Yazma… + Center on Top Üstte ortala + Center on Bottom Altta ortala Type on a Path Tool Yola Yazma Aracı Type Orientation Tip Yönü Type stays text, and every stroke is a line with its lineweight and dashes. Yazı metin olarak kalır ve her kontur, çizgi kalınlığı ve tireleriyle birlikte bir çizgidir. @@ -3669,6 +3729,7 @@ digits Malayalam Malayalam Windows Windows Working CMYK CMYK'de çalışıyor Working CMYK (don't tag) CMYK çalışıyor (etiketlemeyin) + Working RGB (don't tag) Çalışan RGB (etiketlemeyin) Workspace Çalışma Alanı Workspace {i} Çalışma Alanı {i} Wrinkle Tool Kırışıklık Aracı @@ -3847,6 +3908,13 @@ axis Both Her İkisi Dock Panel Bağlantı İstasyonu Paneli Dock to Top Üste yerleştir Dock to Bottom Alta yerleştir + Control Bar Options Kontrol Çubuğu Seçenekleri + Tool Options Araç Seçenekleri + Object Options Nesne Seçenekleri + Image Options Resim Seçenekleri + Vertical Alignment Dikey Hizalama + Align and Distribute Hizala ve Dağıt + Document Options Belge Seçenekleri Dock Control Bar Kontrol çubuğunu yerleştir Drag to float the toolbar Araç çubuğunu ayırmak için sürükleyin Drag to the window's left or right edge to dock Sabitlemek için pencerenin sol veya sağ kenarına sürükleyin @@ -3987,10 +4055,13 @@ axis Both Her İkisi @msg `groupColors` must be an array `groupColors` bir dizi olmalıdır @msg `library` is a library id or name (see {list}) `library` bir kitaplık kimliği veya adıdır (bkz. {list}) @msg `mode` applies to freeform gradients `mode` serbest biçimli degradeler için geçerlidir +@msg a negative `aspect` applies to conic gradients negatif `aspect` konik degradeler için geçerlidir +@msg `focal` applies to radial gradients `focal` radyal degradeler için geçerlidir @msg `preserve` must be an object `preserve` bir nesne olmalıdır @msg `globalAdjust` must be an object `globalAdjust` bir nesne olmalıdır @msg `sampleSize` must be 1, 3 or 5 `sampleSize` 1, 3 veya 5 olmalıdır @msg `stops` must be an array `stops` bir dizi olmalıdır +@msg `{key}` must be an array `{key}` bir dizi olmalıdır @msg `svg` must be an object of SVG options (see document.formats) `svg`, SVG seçeneklerinin bir nesnesi olmalıdır (bkz. document.formats) @msg `{_1}` is no save command `{_1}` kaydetme komutu değil @msg `{area}` is no recovery area name `{area}`, kurtarma alanı adı değildir @@ -4001,6 +4072,7 @@ axis Both Her İkisi @msg `{key}` must be a #rrggbb colour `{key}` bir #rrggbb rengi olmalıdır @msg `{key}` must be a number `{key}` bir sayı olmalıdır @msg `{key}` must be a string `{key}` bir dize olmalıdır +@msg `{key}` must be a profile name or null `{key}` bir profil adı ya da null olmalıdır @msg `{key}` must be a whole number `{key}` bir tam sayı olmalıdır @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}`, {min} ile {max} arasında bir tam sayı olmalıdır ({x}'yi aldı) @msg `{key}` must be between {min} and {max} (got {x}) `{key}`, {min} ile {max} arasında olmalıdır ({x}'yi aldı) @@ -4129,6 +4201,7 @@ axis Both Her İkisi @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller {n} çalışma yüzeyinin sayfası {size}, PDF'nin 14.400 pt (200 in) sayfa sınırından uzun: {unit} UserUnit değeriyle yazılır, bu yüzden UserUnit'i yok sayan uygulamalar onu o kadar kat küçük gösterir @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in {n} çalışma yüzeyinin sayfası {size}, PDF'nin 14.400 pt (200 in) sayfa sınırından uzun: {label} sayfaları UserUnit olmadan, punto cinsinden yazılır ve sınıra uyan uygulamalar sayfayı 200 in'de keser @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5'te, 14.400 pt (200 in) uzunluğunu aşan bir sayfanın boyutunu koruması için gereken UserUnit yoktur: dosya PDF 1.6 olarak yazılır +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4'te, 14.400 pt (200 in) uzunluğunu aşan bir sayfanın PDF/A-2'nin 14.400 birimlik sayfa sınırı içinde kalması için gereken UserUnit yoktur: dosya PDF 1.6 olarak yazılır @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units {n} çalışma yüzeyinin sayfası {size}, PDF'nin 3 ile 14.400 birim arasındaki sayfa kenarları için fazla uzun ve dar: kısa kenarı en az 3 birimde tutan {unit} UserUnit değeriyle yazılır ve sınıra uyan uygulamalar uzun kenarı 14.400 birimde keser @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} dosyaları en fazla {max} değerinde gerçek sayı tutar ve {n} çalışma yüzeyinin {side} pt uzunluğundaki sayfası daha büyüklerini gerektiriyor: PDF/X standardı olmadan PDF 1.6 veya sonrasını ya da daha küçük bir çalışma yüzeyi seçin @msg invalid image data for `{0}` `{0}` için geçersiz resim verileri @@ -4272,6 +4345,8 @@ axis Both Her İkisi @msg not a stored central record saklanan merkezi bir kayıt değil @msg not a valid plug-in module: {0} geçerli bir eklenti modülü değil: {0} @msg not an EMF or WMF file EMF veya WMF dosyası değil +@msg not an HP-GL file HP-GL dosyası değil +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` 1 ile 255 arasında #rrggbb renginden oluşan bir dizi olmalıdır @msg not an RTF file: it doesn't start with {\\rtf bir RTF dosyası değil: {\\rtf ile başlamıyor @msg not found bulunamadı @msg not in pattern editing mode desen düzenleme modunda değil @@ -4343,6 +4418,14 @@ axis Both Her İkisi @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 bu iz, {max} bağlantı noktalarından daha fazlasını, yani belgenin düzgün bir şekilde gösterebileceğinden daha fazlasını oluşturur: Gürültüyü artırın, Yolları veya Renkleri düşürün veya aslına uygunluğu daha düşük bir ön ayar seçin @msg select an envelope bir zarf seç @msg select an image bir resim seç +@msg `background` must be edges, corners or colors `background` edges, corners veya colors olmalıdır +@msg `match` must be distance or channels `match` distance veya channels olmalıdır +@msg `{key}` must be from 0 to 100 `{key}` 0 ile 100 arasında olmalıdır +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors`, her biri onaltılık (#rrggbb veya #rgb) ya da black, white, red, green veya blue olarak yazılmış 1 ile 16 arasında renk içermelidir +@msg the linked image shows its preview: embed or relink it first bağlantılı resim önizlemesini gösteriyor: önce gömün veya yeniden bağlayın +@msg a CMYK image has no transparency to set CMYK görüntüsünde ayarlanacak saydamlık yok +@msg every pixel matches the background: no image would be left her piksel arka planla eşleşiyor: hiç görüntü kalmaz +@msg an image of {w} × {h} pixels is too large to change {w} × {h} piksellik bir görüntü değiştirilemeyecek kadar büyük @msg select an object in perspective perspektifte bir nesne seç @msg select artwork (or a colour group) to recolor yeniden renklendirilecek resmi (veya bir renk grubunu) seçin @msg Recolor completed; {locked} and {hidden} were left unchanged Yeniden renklendirme tamamlandı; değiştirilmeden kalan: {locked} ve {hidden} @@ -4446,7 +4529,7 @@ axis Both Her İkisi @msg unknown format bilinmeyen format @msg unknown format `{f}` (Save writes {_1}) bilinmeyen format `{f}` (Kaydet, {_1} yazar) @msg unknown freeform mode `{m}` (points, lines) bilinmeyen serbest biçimli mod `{m}` (noktalar, çizgiler) -@msg unknown gradient kind `{k}` (linear, radial, freeform) bilinmeyen gradyan türü `{k}` (doğrusal, radyal, serbest biçimli) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) bilinmeyen gradyan türü `{k}` (doğrusal, radyal, konik, elmas, serbest biçimli) @msg unknown highlight `{h}` bilinmeyen vurgu `{h}` @msg unknown option `{path}.{k}` bilinmeyen seçenek `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) bilinmeyen üst baskılar `{o}` (koru, benzet veya at) @@ -4468,7 +4551,7 @@ axis Both Her İkisi @msg `prefs.import` runs on its own, not as a batch step `prefs.import` tek başına çalışır, toplu iş adımı olarak değil @msg unknown preset (one of {_1}) bilinmeyen ön ayar ({_1}'den biri) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) bilinmeyen ön ayar `{name}` (yüksek, orta, düşük veya kaydedilmiş bir ayar: bkz. flattener.presets.list) -@msg unknown preset `{name}` (see flattener.presets.list) bilinmeyen ön ayar `{name}` (bkz. düzleştirici.presets.list) +@msg unknown preset `{name}` (see flattener.presets.list) bilinmeyen ön ayar `{name}` (bkz. flattener.presets.list) @msg unknown preset `{name}` (see webExport.presets.list) bilinmeyen ön ayar `{name}` (bkz. webExport.presets.list) @msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) bilinmeyen ön ayar `{name}`: yerleşik ya da kayıtlı bir ön ayar değil (bkz. imageTrace.presets) @msg unknown side `{other}` (left|right|top|bottom) bilinmeyen taraf `{other}` (sol|sağ|üst|alt) @@ -4701,7 +4784,13 @@ axis Both Her İkisi @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC veya HEIF dosyası okunamayan türde bir görüntü içeriyor @msg HEIC and HEIF images can't be opened in this build HEIC ve HEIF görüntüleri bu derlemede açılamıyor @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD görüntüsü okunamayacak kadar büyük ({_1} × {_2} piksel) -@msg zipped 32-bit PSD image data with prediction can't be read Tahmin içeren sıkıştırılmış 32 bit PSD görüntü verileri okunamıyor +@msg zipped 1-bit PSD image data with prediction can't be read Tahmin içeren sıkıştırılmış 1 bit PSD görüntü verileri okunamıyor +@msg the PSD file's layer data uses an unknown compression ({m}) PSD dosyasının katman verileri bilinmeyen bir sıkıştırma kullanıyor ({m}) +@msg the PSD file's layer records are damaged PSD dosyasının katman kayıtları hasarlı +@msg the PSD file's layer groups are nested too deeply PSD dosyasının katman grupları çok derin iç içe geçmiş +@msg a layer of the PSD file is too large to read PSD dosyasının bir katmanı okunamayacak kadar büyük +@msg the PSD file's layers take more memory to read than allowed PSD dosyasının katmanlarını okumak izin verilenden fazla bellek gerektiriyor +@msg the layers can't be read ({e}): the file opened as its merged image katmanlar okunamıyor ({e}): dosya birleştirilmiş görüntüsü olarak açıldı @msg {depth}-bit PSD files in this colour mode can't be read Bu renk modunda {depth}-bit PSD dosyaları okunamaz @msg the PSD file is cut short PSD dosyası kısa kesildi @msg the PSD file's header is damaged PSD dosyasının başlığı hasarlı @@ -5394,6 +5483,11 @@ theme Appearance Görünüm Softness Yumuşaklık Ambient Light Ortam Işığı Light behind the object Nesnenin arkasındaki ışık + Shadows Gölgeler + Distance from Object Nesneden uzaklık + Shadow Bounds Gölge sınırları + Behind Object Nesnenin arkasında + Below Object Nesnenin altında Registration: Kayıt: Dimension Boyut Drawing : real size — 1:10 labels 1 unit on the page as 10. Çizim : Gerçek boyut — 1:10 etiketler sayfada 10 adet olarak 1 adettir. @@ -5446,7 +5540,7 @@ theme Appearance Görünüm @msg span must be "object" or "selection", got {v} span "object" veya "selection" olmalıdır, {v} değil @msg span: "selection" places a `gradient`, not a swatch span: "selection" bir renk örneği değil, bir `gradient` yerleştirir @msg span: "selection" places a gradient: give `gradient` span: "selection" bir degrade yerleştirir: `gradient` verin -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" serbest biçimli bir degrade değil, doğrusal veya radyal bir degrade yerleştirir +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" serbest biçimli bir degrade değil, doğrusal, radyal, konik veya elmas bir degrade yerleştirir @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" degradenin kendisini yerleştirir: `start` ve `end` değerlerini vermeyin (bunlar degradeyi zaten belge koordinatlarına yerleştirir) Make Image Dynamic Görüntüyü Dinamik Hale Getirin Import Data Sets… Veri Kümelerini İçe Aktar… @@ -5672,6 +5766,8 @@ theme Appearance Görünüm @msg invalid object id {value}: expected a non-negative integer geçersiz nesne kimliği {value}: negatif olmayan bir tam sayı bekleniyordu @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}` içindeki {index} dizinli öğe {value}, negatif olmayan tam sayı bir nesne kimliği değil @msg no such object id {value} böyle bir nesne kimliği yok: {value} +@msg id {value} is a ruler guide, not an object bu kimlik bir nesneye değil, bir kılavuza ait: {value} +@msg a ruler guide goes only directly in a layer or sublayer bir kılavuz yalnızca doğrudan bir katmanda veya alt katmanda bulunabilir @msg id {value} is a layer, not an object {value} kimliği bir katmana ait, bir nesneye değil @msg id {value} is a layer, not an object; move layers with layer.move {value} kimliği bir katmana ait, bir nesneye değil; katmanları layer.move ile taşıyın @msg {key} must be Unix seconds (an integer) or null {key}, Unix saniyesi (bir tam sayı) veya null olmalıdır @@ -5946,6 +6042,7 @@ axis Y Axis Y ekseni Snap to Perpendicular Dikeye Yasla Geometric Guides Geometrik Kılavuzlar Geometric Patterns Geometrik Desenler + Grit Textures Grenli Dokular @msg `method` must be classic or perceptual `method` classic veya perceptual olmalıdır # Heavy plug-in filters (plugin.inspect, plug-in runs) Install “{name}”, which asks for a heavy budget? Büyük bir hesaplama bütçesi isteyen “{name}” yüklensin mi? @@ -5965,6 +6062,8 @@ axis Y Axis Y ekseni Version: {version} Sürüm: {version} Install “{name}” in place of the plug-in with the same ID? Aynı kimliğe sahip eklentinin yerine “{name}” yüklensin mi? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Bu dosya, daha önce bu kimlikle yüklenen eklenti değil. O kimlik için saklanan ayarları ve önbelleği alır. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Bir otomasyon bu eklentinin yüklenmesini istedi. Yüklemek için Nesne › Eklentiler › Eklentiyi Yükle… komutunu kendiniz seçin. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Bir otomasyon bu eklentinin yüklenmesini istedi. Yüklemek için Nesne › Eklentiler › Eklentiyi Yükle… komutunu kendiniz seçin. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}”, {_1} kimlikli eklentiden farklı bir modül ve onun için saklanan ayarları ve önbelleği alacak: kullanıcı onayladıktan sonra `replace: true` ile yükleyin File SHA-256: {hash} Dosya SHA-256: {hash} Read the objects it is given Kendisine verilen nesneleri okuma @@ -6010,6 +6109,11 @@ axis Y Axis Y ekseni @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir @msg memory budget (object {_1} needs {size} bytes of input, {left} left) bellek bütçesi (nesne {_1} için {size} bayt girdi gerekiyor, {left} kaldı) @msg object budget (more than {MAX_OBJECTS} read-only objects) nesne bütçesi ({MAX_OBJECTS} adetten fazla salt okunur nesne) +@msg instruction budget talimat bütçesi +@msg time budget zaman bütçesi +@msg memory budget (the selection is too large to hand over) bellek bütçesi (seçim aktarılamayacak kadar büyük) +@msg output size ({what} is {len} bytes, limit {max}) çıktı boyutu ({what}: {len} bayt, sınır {max}) +@msg the plug-in's grant can't be removed from the plug-in store eklentinin izni eklenti deposundan kaldırılamıyor @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` izni sonraki bir eklenti API’si için ayrılmıştır; bu ana bilgisayar bu izni vermez @msg unknown permission `{shown}` bilinmeyen izin `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” {asked} izinlerini istiyor: masaüstü uygulamasında bir kişinin onaylaması gerekir veya --allow-plugin-grants ile başlatılan bir oturumda `grant` geçirin @@ -6022,6 +6126,12 @@ axis Y Axis Y ekseni @msg command {name}: `label` must be 1-64 printable characters {name} komutu: `label` 1-64 yazdırılabilir karakter olmalıdır @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} komutu: a-z 0-9 _ karakterlerinden oluşan ve harfle başlayan 1-{MAX_COMMAND_ID} karakterlik bir kimlik kullanın @msg command {name}: {e} {name} komutu: {e} +@msg manifest: {e} bildirim: {e} +@msg manifest: {e} at line {line} column {column} bildirim: {e} (satır {line}, sütun {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands`, her biri `id` ve `label` içeren bir komut listesi olmalıdır +@msg command {name} must be an object with an `id` and a `label` {name} komutu `id` ve `label` içeren bir nesne olmalıdır +@msg missing field `{key}` `{key}` alanı eksik +@msg duplicate field `{key}` `{key}` alanı yinelenmiş @msg only a filter or a live effect declares `commands` `commands` yalnızca bir filtre veya canlı efekt tarafından bildirilir @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modül `hash` içinde verilen SHA-256 değerine sahip değil: hiçbir şey yüklenmedi @@ -6046,6 +6156,16 @@ axis Y Axis Y ekseni @msg message must be text "message" metin olmalıdır @msg allowContinue must be true or false "allowContinue" true veya false olmalıdır @msg Batch cannot play an action with a stop Toplu işlem durak içeren bir eylemi oynatamaz + Insert Menu Item… Menü Öğesi Ekle… + Insert Menu Item Menü Öğesi Ekle + Menu Item: Menü öğesi: + No menu item matches. Eşleşen menü öğesi yok. + Several menu items match. Choose one from the list. Birden çok menü öğesi eşleşiyor. Listeden birini seçin. + Items that open a dialog, and File, Window and Help menu items, are not listed. İletişim kutusu açan öğeler ile Dosya, Pencere ve Yardım menülerinin öğeleri listelenmez. +@msg command must be text "command" metin olmalıdır +@msg no menu item that can be inserted runs this command eklenebilen hiçbir menü öğesi bu komutu çalıştırmaz +@msg the action already has 10,000 steps eylemde zaten 10.000 adım var +@msg the action set would be larger than 8 MiB eylem seti 8 MiB'tan büyük olurdu Playback Options Oynatma Seçenekleri Accelerated Hızlandırılmış Step by Step Adım Adım @@ -6084,6 +6204,12 @@ axis Y Axis Y ekseni Crosshair Nişangah Checkpoint Kontrol noktası Inventory Icons Envanter Simgeleri + Skill Icons Yetenek Simgeleri + Attack Saldırı + Defend Savunma + Heal İyileştirme + Buff Güçlendirme + Ult Ult Sword Kılıç Shield Kalkan Potion İksir @@ -6148,7 +6274,23 @@ axis Y Axis Y ekseni Dash Trail Kesik iz Speed Line Hız çizgisi Game Trails Oyun izleri + Energy Beams Enerji Işınları + Laser Bolt Lazer Mermisi + Plasma Arc Plazma Yayı + Charge Wave Şarj Dalgası + Spark Trail Kıvılcım İzi Calligraphic Nibs Kaligrafi Uçları + Bristle Brushes Kıl Fırçalar + Fine Liner İnce Çizgi + Pointed Flat Sivri Düz + Stubby Round Kısa Yuvarlak + Dry Scrub Kuru Ovma + Soft Dome Yumuşak Kubbe + Filbert Kedi Dili + Angled Round Eğik Yuvarlak + Angled Flat Eğik Düz + Fan Blender Harmanlama Yelpazesi + Grass Fan Çim Yelpazesi Pattern Borders Desen Kenarlıkları Scatter Shapes Dağılım Şekilleri Save Brush Library… Fırça Kitaplığını Kaydet… @@ -6345,9 +6487,12 @@ anchor Points: Noktalar: @msg {label} must be a number {label} bir sayı olmalıdır @msg {label} must be a number of at least 0.1 {label} en az 0,1 olan bir sayı olmalıdır Advanced Character Formats Gelişmiş karakter biçimleri + Basic Paragraph Formats Temel paragraf biçimleri + Composition Dizgi Horizontal Scale Yatay Ölçek Vertical Scale Dikey Ölçek @msg {label} must be a number from {min} to {max} {label} {min} ile {max} arasında bir sayı olmalıdır +@msg {label} must be a whole number from {min} to {max} {label} {min} ile {max} arasında bir tam sayı olmalıdır Character Color Karakter Rengi OpenType Features OpenType Özellikleri Stylistic Sets Stilistik Setler @@ -6355,6 +6500,10 @@ anchor Points: Noktalar: @msg features lists at most {max} tags features en fazla {max} etiket içerebilir @msg unknown OpenType feature `{t}` bilinmeyen OpenType özelliği `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0'ın üzerinde ve en fazla {max} olan bir sayı olmalıdır +@msg {label} must be at most {max} characters {label} en fazla {max} karakter olmalıdır +@msg {label} must be one character {label} tek bir karakter olmalıdır +@msg at most {max} tab stops en fazla {max} sekme durağı +@msg unknown align `{other}` bilinmeyen hizalama `{other}` @msg no character style `{name}` `{name}` karakter stili bulunamadı # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6516,6 +6665,12 @@ breakText Glyphs Glifler Delete the selected brushes? Seçili fırçalar silinsin mi? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Konturlar bu fırçalardan birini veya daha fazlasını kullanıyor. Fırçalar bu konturlardan kaldırılsın ve fırçalar silinsin mi? Remove Strokes Konturları Kaldır + Place Brush Art Fırça Çizimini Yerleştir + Replace Brush Art Fırça Çizimini Değiştir + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturlar bu fırçayı kullanıyor. Yeni çizim bu konturlara uygulansın mı, yoksa konturlar olduğu gibi bırakılıp fırçanın yeni çizimli bir kopyası mı eklensin? + Apply to Strokes Konturlara Uygula + Leave Strokes Konturları Bırak +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` fırçasının çizimi yok (yalnızca serpme, resim ve desen fırçalarının çizimi vardır) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Düzenleme Araçları Arrange in Grid… Izgarada Düzenle… @@ -6711,6 +6866,11 @@ breakText Glyphs Glifler @msg only an exporter or an importer declares `extensions` `extensions` yalnızca dışa veya içe aktarma eklentisi bildirir @msg an importer always gets an import's budget: leave `budget` out içe aktarma eklentisi her zaman bir içe aktarmanın bütçesini alır: `budget` değerini çıkarın +# Copy Troubleshooting Info + Copy Troubleshooting Info Sorun Giderme Bilgilerini Kopyala +@msg Copied the troubleshooting info Sorun giderme bilgileri kopyalandı +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report VectorCraft'ın son oturumu kapanmadan önce yanıt vermeyi durdurdu. Yardım › Sorun Giderme Bilgilerini Kopyala, hata raporu için ayrıntıları kopyalar + # Safe Mode Safe Mode… Güvenli Mod… Safe Mode Güvenli Mod @@ -6731,6 +6891,8 @@ breakText Glyphs Glifler # Align to Pixel Grid Align to Pixel Grid Piksel Izgarasına Hizala + Align New Objects to Pixel Grid Yeni Nesneleri Piksel Izgarasına Hizala + Not Aligned to Pixel Grid Piksel Izgarasına Hizalanmamış @msg only paths and compound paths can be aligned to the pixel grid piksel ızgarasına yalnızca yollar ve bileşik yollar hizalanabilir @msg side is left or right, not `{s}` side left veya right olmalıdır, `{s}` değil Ignore All Tümünü Yoksay @@ -6761,8 +6923,33 @@ breakText Glyphs Glifler @plural {n} line cut|{n} lines cut {n} satır kesildi @msg `first` and `last` must be numbers of lines the console holds, first before last `first` ve `last`, konsolun tuttuğu satırların numaraları olmalı ve `first`, `last` değerinden önce gelmeli +# Learn panel + Learn Öğren + Explore tutorials Öğreticileri Keşfet + For you Sizin için + Skills Beceriler + Get started Başlarken + Quick skill guide Hızlı beceri rehberi + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Temel araçlar için becerilere göre gruplanmış kısa uygulamalı öğreticiler. Öğreticilerini görmek için bir beceri seçin. + List Tutorials Öğreticileri Listele + Show Tutorial Öğreticiyi Göster +@msg missing `tutorial` (see learn.list) `tutorial` eksik (bkz. learn.list) +@msg unknown tutorial `{id}` (see learn.list) bilinmeyen öğretici `{id}` (bkz. learn.list) + # Deferred plug-in effects Refresh Deferred Effects Ertelenen Efektleri Yenile Deferred Effects Ertelenen Efektler @msg no plug-in effect is deferred ertelenen eklenti efekti yok @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. {n} eklenti efekti ertelenerek açıldı. Efekt › Ertelenen Efektleri Yenile bunları çalıştırır. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Kesim Araçları + Stencil Bridges… Şablon Köprüleri… + Stencil Bridges Şablon Köprüleri + Shortest Crossing En kısa geçiş + Direction Yön +@msg The selected art has no islands to bridge Seçili çizimde köprüyle bağlanacak ada yok +@msg No bridge of this width fits across the selected art Bu genişlikte bir köprü seçili çizime sığmıyor +@msg Some islands could not be joined to the area around the art Bazı adalar çizimin çevresindeki alana bağlanamadı +@msg `width` must be from {lo} to {hi} pt `width` {lo} ile {hi} pt arasında olmalıdır +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 1 ile {MAX_BRIDGES_PER_ISLAND} arasında bir tam sayı olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c1b1c3bdaf..d91ba40226 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -256,6 +256,7 @@ font-technology Variable Варіативні Asset Export Settings Параметри експорту ресурсів Assets Ресурси Assign Призначити + Assign Profile Призначити профіль Assign Profile… Призначити профіль… Assign: Призначити: Attach to Active Plane Прикріпити до активної площини @@ -694,6 +695,15 @@ font-technology Variable Варіативні Created: Створено: Crop Обрізати Crop Image Обрізати зображення + Image Tools Інструменти зображення + Remove Background… Видалити фон… + Remove Background Видалити фон + Background Фон + Edge Color Колір краю + Picked Colors Вибрані кольори + Corner Color Колір кутів + Contiguous Суміжні + Each Channel Кожен канал Edit Path Редагувати контур Mask Маска Crop Marks Мітки обрізання @@ -813,6 +823,14 @@ font-technology Variable Варіативні Disable Auto Add/Delete Вимкнути авто-додавання/видалення Disable Opacity Mask Вимкнути маску непрозорості Discard Відкинути + Preserve Зберігати + TIFF (Black & White) TIFF (чорно-білий) + TIFF (8-bit Color) TIFF (8-бітний колір) + High Resolution Висока роздільна здатність + Medium Resolution Середня роздільна здатність + Low Resolution Низька роздільна здатність + Language Level 2 Рівень мови 2 + Language Level 3 Рівень мови 3 Discard Empty Type Видалити порожній текст Discard Recovered Documents Відкинути відновлені документи Discard White Overprint in Output Скасувати накладення білого під час виведення @@ -1138,6 +1156,8 @@ font-technology Variable Варіативні Extrude & Bevel… Видавлювання та фаска… 3D (Classic) 3D (класичні) Extrude & Bevel (Classic)… Видавлювання та фаска (класичне)… + Revolve (Classic)… Обертання (класичне)… + Rotate (Classic)… Поворот (класичний)… Surface Поверхня Wireframe Каркас No Shading Без затінення @@ -1450,6 +1470,14 @@ file-filter Templates Шаблони Hair Space Волосяна шпація Hand Tool Інструмент «Рука» Hand-Drawn Намальований від руки + Painted and Sketched Мальовані та ескізні + Washed Blue Розмитий синій + Bristle Ochre Охра пензлем + Pastel Heather Пастельний верес + Charcoal Shade Тінь вугіллям + Ink Contour Контур тушшю + Wet Ink Мокра туш + Fine Pen Тонке перо Handles Маркери Hard Light Жорстке світло Hard Mix Жорстке накладання @@ -1680,6 +1708,7 @@ file-filter Templates Шаблони Include Linked Files Включати пов’язані файли Include Metadata Включати метадані Include non-printing layers Включати недруковані шари + Write pages longer than 200 in at full size in points Записувати сторінки, довші за 200 in, у повному розмірі, у пунктах Include SVG Code Вмикати код SVG Include Swatches for Tints Включати зразки для відтінків Inflate… Надування… @@ -2356,12 +2385,23 @@ file-filter Templates Шаблони Open… Відкрити… Optical Оптичний Optical Margin Alignment Оптичне вирівнювання полів + Dynamic Text Динамічний текст + Dynamic Text Presets Набори параметрів динамічного тексту + Arch Арка +@msg select point type or type on a path виберіть точковий текст або текст за контуром +@msg type on a path in a thread cannot use Dynamic Text: {frames} текст за контуром у пов’язаному тексті не може використовувати динамічний текст: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} не можна центрувати вгорі чи внизу текст за незамкненим або складеним контуром: {open} +@msg type on a path with no length or no height cannot be centered: {flat} не можна центрувати текст за контуром без довжини або без висоти: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} не можна центрувати вгорі чи внизу текст за контуром у пов’язаному тексті: {frames} +@msg select type on a closed path виділіть текст за замкненим контуром Optimize for fast web view Оптимізувати для швидкого перегляду web Optimized Оптимізовано Options Параметри Options for Selection… Параметри виділення… Options: Параметри: Options… Параметри… + Organic Fades Органічні згасання + Holographic Голографічні or more spaces with a tab або більше прогалин на табуляцію Order: Порядок: Ordinals Порядкові числівники @@ -2555,6 +2595,7 @@ diagnostics ui інтерфейс Presets: Набори: Press Натисніть Preview Перегляд + Preview: Перегляд: Preview All Layers Переглянути всі шари Preview in Browser Переглянути у браузері Preview in Browser needs the desktop app (the web downloads files instead) Перегляд у браузері вимагає настільної програми (web-версія завантажує файли) @@ -2635,6 +2676,8 @@ digits Malayalam Малаялам Radial Радіальний Radial Glows Радіальні світіння Radial Gradient Радіальний градієнт + Conic Gradient Конічний градієнт + Diamond Gradient Ромбоподібний градієнт Radius 1 Радіус 1 Radius 2 Радіус 2 Radius1 Радіус1 @@ -2647,6 +2690,8 @@ digits Malayalam Малаялам Range: Діапазон: Raster Effects Растрові ефекти Raster File Format: Формат растрового файлу: + Include Placed Images Включати розміщені зображення + Include Fill Hatches Включати штрихування заливок Raster Sample Size: Розмір растрового зразка: Raster/Vector Balance: Баланс растрових/векторних: Rasterize Растеризувати @@ -2828,6 +2873,10 @@ digits Malayalam Малаялам Replace Font Замінити шрифт Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Замініть його іншим файлом або ігноруйте: зображення продовжать показувати попередній перегляд, збережений з документом. Replace Spine Замінити вісь + Create Spine Створити вісь + Create Spine: Створити вісь: + Always Завжди + Never Ніколи Replace Symbol Замінити символ Reset Transformation Скинути трансформацію Replace With Font Замінити шрифтом @@ -2907,6 +2956,9 @@ digits Malayalam Малаялам Rise… Підйом… Roman Baseline Римська базова лінія Roman Hanging Punctuation Римська висяча пунктуація + Korean Line Break Anywhere Перенесення корейського тексту будь-де + East Asian Composition Settings Параметри східноазійського набору + Korean Composition Settings Параметри корейського набору Rotate Повернути Rotate 90° CW Повернути на 90° за годинниковою стрілкою Rotate Tool Інструмент «Поворот» @@ -3192,6 +3244,15 @@ digits Malayalam Малаялам Stun Pulse Оглушення Stealth Fade Невидимість Shield Buff Щит + Textures Текстури + Fine Grain Дрібне зерно + Canvas Weave Полотняне плетіння + Burlap Sack Мішковина + Cracked Glaze Потріскана глазур + Mosaic Floor Мозаїчна підлога + Quilted Squares Стьобані квадрати + Leaded Glass Вітражне скло + Damp Paper Вологий папір Shape Фігура Shape Builder Створення фігур Shape Builder Regions Області створення фігур @@ -3254,6 +3315,7 @@ digits Malayalam Малаялам Show Modified Показати змінені Show Note Показати примітку Show Options Показати параметри + Show Recent Colors Показати останні кольори Show Original Path Показати початковий контур Open this dialog with these settings next time Наступного разу відкривати це діалогове вікно з цими параметрами Auto-Simplify Автоматичне спрощення @@ -3559,6 +3621,8 @@ effect Points Точки Scale at Center Масштабувати від центру Up/Down: Вгору/вниз: Left/Right: Ліворуч/праворуч: + Tate-chu-yoko Up/Down Tate-chu-yoko вгору/вниз + Tate-chu-yoko Left/Right Tate-chu-yoko ліворуч/праворуч Temperature Температура Temperature/Tint… Температура/відтінок… Template Шаблон @@ -3629,6 +3693,8 @@ effect Points Точки Toolbar: Single/Double Column Панель інструментів: один/два стовпці Toolbar: Add Tool Панель інструментів: додати інструмент Toolbar: Remove Tool Панель інструментів: вилучити інструмент + Add Tool… Додати інструмент… + Remove Tool Вилучити інструмент Toolbar: Reset Панель інструментів: скинути Toolbars Панелі інструментів Tools Інструменти @@ -3700,6 +3766,8 @@ effect Points Точки Type on a Path Текст за контуром Type on a Path Options Параметри тексту за контуром Type on a Path Options… Параметри тексту за контуром… + Center on Top Центрувати вгорі + Center on Bottom Центрувати внизу Type on a Path Tool Інструмент «Текст за контуром» Type Orientation Орієнтація тексту Type stays text, and every stroke is a line with its lineweight and dashes. Текст залишається текстом, і кожне обведення — лінія з її товщиною та штрихами. @@ -3893,6 +3961,7 @@ effect Points Точки Windows Windows Working CMYK Робочий CMYK Working CMYK (don't tag) Робочий CMYK (без позначки) + Working RGB (don't tag) Робочий RGB (без позначки) Workspace Робоче середовище Workspace {i} Робоче середовище {i} Wrinkle Tool Інструмент «Зморшки» @@ -4077,6 +4146,13 @@ axis Both Обидві Dock Panel Прикріпити панель Dock to Top Прикріпити вгорі Dock to Bottom Прикріпити внизу + Control Bar Options Параметри панелі керування + Tool Options Параметри інструменту + Object Options Параметри об’єкта + Image Options Параметри зображення + Vertical Alignment Вертикальне вирівнювання + Align and Distribute Вирівняти та розподілити + Document Options Параметри документа Dock Control Bar Прикріпити панель керування Drag to float the toolbar Перетягніть, щоб від’єднати панель інструментів Drag to the window's left or right edge to dock Перетягніть до лівого або правого краю вікна для прикріплення @@ -4224,10 +4300,13 @@ axis Both Обидві @msg `groupColors` must be an array `groupColors` має бути масивом @msg `library` is a library id or name (see {list}) `library` — це ідентифікатор або ім’я бібліотеки (див. {list}) @msg `mode` applies to freeform gradients `mode` застосовується до довільних градієнтів +@msg a negative `aspect` applies to conic gradients від’ємний `aspect` застосовується до конічних градієнтів +@msg `focal` applies to radial gradients `focal` застосовується до радіальних градієнтів @msg `preserve` must be an object `preserve` має бути об’єктом @msg `globalAdjust` must be an object `globalAdjust` має бути об’єктом @msg `sampleSize` must be 1, 3 or 5 `sampleSize` має бути 1, 3 або 5 @msg `stops` must be an array `stops` має бути масивом +@msg `{key}` must be an array `{key}` має бути масивом @msg `svg` must be an object of SVG options (see document.formats) `svg` має бути об’єктом параметрів SVG (див. document.formats) @msg `{_1}` is no save command `{_1}` не є командою збереження @msg `{area}` is no recovery area name `{area}` не є ім’ям області відновлення @@ -4241,6 +4320,7 @@ axis Both Обидві @msg `{key}` must be a number, not {v} `{key}` має бути числом, а не {v} @msg {key} must be Unix seconds (an integer) or null {key} має бути часом Unix у секундах (цілим числом) або null @msg `{key}` must be a string `{key}` має бути рядком +@msg `{key}` must be a profile name or null `{key}` має бути назвою профілю або null @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 between {min} and {max} (got {x}) `{key}` має бути від {min} до {max} (отримано {x}) @@ -4393,6 +4473,7 @@ axis Both Обидві @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller сторінка монтажної області {n} має розмір {size}, що більше за обмеження PDF на розмір сторінки в 14 400 pt (200 in): її записано з UserUnit {unit}, тому застосунки, які ігнорують UserUnit, показують її в стільки ж разів меншою @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in сторінка монтажної області {n} має розмір {size}, що більше за обмеження PDF на розмір сторінки в 14 400 pt (200 in): сторінки {label} записуються без UserUnit, у пунктах, і застосунки, що дотримуються обмеження, обрізають сторінку до 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 у PDF 1.5 немає UserUnit, який потрібен сторінці, довшій за 14 400 pt (200 in), щоб зберегти розмір: файл записується як PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 у PDF 1.4 немає UserUnit, який потрібен сторінці, довшій за 14 400 pt (200 in), щоб вкластися в межу сторінки PDF/A-2 у 14 400 одиниць: файл записується як PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units сторінка монтажної області {n} має розмір {size} і задовга та завузька для сторін сторінки PDF від 3 до 14 400 одиниць: її записано з UserUnit {unit}, що тримає коротку сторону не менше 3 одиниць, а застосунки, які дотримуються межі, обрізають довгу сторону до 14 400 одиниць @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файли {label} вміщують дійсні числа до {max}, а сторінці монтажної області {n} завдовжки {side} pt потрібні більші: виберіть PDF 1.6 або новіший без стандарту PDF/X чи меншу монтажну область @msg invalid image data for `{0}` неприпустимі дані зображення для `{0}` @@ -4541,6 +4622,8 @@ axis Both Обидві @msg not a stored central record не є збереженим центральним записом @msg not a valid plug-in module: {0} не є допустимим модулем: {0} @msg not an EMF or WMF file не є файлом EMF або WMF +@msg not an HP-GL file не є файлом HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` має бути масивом із 1–255 кольорів #rrggbb @msg not found не знайдено @msg not in pattern editing mode не в режимі редагування візерунка @msg finish editing the pattern first спочатку завершіть редагування візерунка @@ -4620,6 +4703,14 @@ axis Both Обидві @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} опорних точок, що більше, ніж документ може плавно відобразити: збільште «Шум», зменште «Контури» або «Кольори» або виберіть набір з меншою точністю @msg select an envelope виділіть оболонку @msg select an image виділіть зображення +@msg `background` must be edges, corners or colors `background` має бути edges, corners або colors +@msg `match` must be distance or channels `match` має бути distance або channels +@msg `{key}` must be from 0 to 100 `{key}` має бути від 0 до 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` має містити від 1 до 16 кольорів, кожен у шістнадцятковому вигляді (#rrggbb або #rgb) або як black, white, red, green чи blue +@msg the linked image shows its preview: embed or relink it first пов’язане зображення показує попередній перегляд: спочатку вбудуйте його або відновіть зв’язок +@msg a CMYK image has no transparency to set зображення CMYK не має прозорості, яку можна задати +@msg every pixel matches the background: no image would be left кожен піксель збігається з фоном: від зображення нічого не залишилося б +@msg an image of {w} × {h} pixels is too large to change зображення розміром {w} × {h} пікселів завелике для зміни @msg select an object in perspective виділіть об’єкт у перспективі @msg select artwork (or a colour group) to recolor виділіть малюнок (або колірну групу) для перефарбовування @msg Recolor completed; {locked} and {hidden} were left unchanged Перефарбовування завершено; без змін: {locked} і {hidden} @@ -4726,7 +4817,7 @@ axis Both Обидві @msg unknown format невідомий формат @msg unknown format `{f}` (Save writes {_1}) невідомий формат `{f}` (збереження записує {_1}) @msg unknown freeform mode `{m}` (points, lines) невідомий режим довільної форми `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) невідомий тип градієнта `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) невідомий тип градієнта `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` невідоме виділення `{h}` @msg unknown option `{path}.{k}` невідомий параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) невідомі накладення `{o}` (preserve, simulate або discard) @@ -4952,6 +5043,8 @@ axis Both Обидві @msg invalid object id {value}: expected a non-negative integer неприпустимий ідентифікатор об’єкта {value}: очікується невід’ємне ціле число @msg `{key}` entry {index} is {value}, not a non-negative integer object id елемент {index} у `{key}` дорівнює {value}, а не ідентифікатору об’єкта (невід’ємному цілому числу) @msg no such object id {value} об’єкт з ідентифікатором {value} не існує +@msg id {value} is a ruler guide, not an object ідентифікатор {value} належить напрямній, а не об’єкту +@msg a ruler guide goes only directly in a layer or sublayer напрямна може бути лише безпосередньо в шарі або підшарі @msg id {value} is a layer, not an object ідентифікатор {value} належить шару, а не об’єкту @msg id {value} is a layer, not an object; move layers with layer.move ідентифікатор {value} належить шару, а не об’єкту; переміщуйте шари за допомогою layer.move @msg automation filesystem access is not granted: read authority is absent: {path} автоматизація не має доступу до файлової системи: немає права на читання: {path} @@ -4981,7 +5074,13 @@ axis Both Обидві @msg the HEIC or HEIF file holds a kind of image that can't be read файл HEIC або HEIF містить зображення такого типу, яке не вдається прочитати @msg HEIC and HEIF images can't be opened in this build зображення HEIC і HEIF не можна відкрити в цій збірці @msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.) -@msg zipped 32-bit PSD image data with prediction can't be read 32-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються +@msg zipped 1-bit PSD image data with prediction can't be read 1-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються +@msg the PSD file's layer data uses an unknown compression ({m}) дані шарів файлу PSD використовують невідоме стиснення ({m}) +@msg the PSD file's layer records are damaged записи шарів файлу PSD пошкоджено +@msg the PSD file's layer groups are nested too deeply групи шарів файлу PSD вкладено надто глибоко +@msg a layer of the PSD file is too large to read шар файлу PSD завеликий для читання +@msg the PSD file's layers take more memory to read than allowed для читання шарів файлу PSD потрібно більше пам’яті, ніж дозволено +@msg the layers can't be read ({e}): the file opened as its merged image не вдається прочитати шари ({e}): файл відкрито як зведене зображення @msg {depth}-bit PSD files in this colour mode can't be read {depth}-бітні файли PSD у цьому колірному режимі не читаються @msg the PSD file is cut short файл PSD обрізаний @msg the PSD file's header is damaged заголовок файлу PSD пошкоджено @@ -5294,6 +5393,11 @@ lighting Light Світло Softness М'якість Ambient Light Навколишнє світло Light behind the object Світло позаду об'єкта + Shadows Тіні + Distance from Object Відстань від об'єкта + Shadow Bounds Межі тіні + Behind Object Позаду об'єкта + Below Object Під об'єктом 3D Lighting Preset Попереднє налаштування 3D освітлення Standard Стандартне Diffuse Розсіяне @@ -5361,7 +5465,7 @@ lighting Light Світло @msg span must be "object" or "selection", got {v} span має бути "object" або "selection", а не {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 span: "selection" розміщує лінійний або радіальний градієнт, а не довільний +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" розміщує лінійний, радіальний, конічний або ромбоподібний градієнт, а не довільний @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" сам розміщує градієнт: приберіть `start` і `end` (вони вже задають його в координатах документа) Make Image Dynamic Зробити зображення динамічним Import Data Sets… Імпортувати набори даних… @@ -5546,6 +5650,7 @@ lighting Light Світло Ruby Рубі Geometric Guides Геометричні напрямні Geometric Patterns Геометричні візерунки + Grit Textures Зернисті текстури Ease In Плавний початок Ease Out Плавне завершення Ease In Out Плавний початок і завершення @@ -5606,6 +5711,8 @@ axis Y Axis Вісь Y Version: {version} Версія: {version} Install “{name}” in place of the plug-in with the same ID? Встановити «{name}» замість модуля з тим самим ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Цей файл не є модулем, установленим раніше з цим ID. Він отримає налаштування й кеш, збережені для цього ID. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизація попросила встановити цей модуль. Щоб установити його, виберіть «Об’єкт › Модулі › Встановити модуль…» самостійно. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизація попросила встановити цей модуль. Щоб установити його, виберіть «Об’єкт › Модулі › Встановити модуль…» самостійно. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees «{name}» відрізняється від модуля з ID {_1} і отримав би збережені для нього налаштування й кеш: встановіть його з `replace: true`, коли користувач погодиться File SHA-256: {hash} SHA-256 файлу: {hash} Read the objects it is given Читати передані йому об’єкти @@ -5651,6 +5758,11 @@ axis Y Axis Вісь Y @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет пам’яті (об’єкту {_1} потрібно {size} байтів вхідних даних, залишилося {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет об’єктів (понад {MAX_OBJECTS} об’єктів лише для читання) +@msg instruction budget бюджет інструкцій +@msg time budget бюджет часу +@msg memory budget (the selection is too large to hand over) бюджет пам’яті (виділення завелике для передавання) +@msg output size ({what} is {len} bytes, limit {max}) розмір виводу ({what}: {len} байтів, межа {max}) +@msg the plug-in's grant can't be removed from the plug-in store дозвіл модуля не вдається вилучити зі сховища модулів @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it дозвіл `{shown}` зарезервовано для пізнішого API модулів; цей хост його не надає @msg unknown permission `{shown}` невідомий дозвіл `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants «{name}» запитує дозволи {asked}: їх має схвалити людина в настільному застосунку, або передайте `grant` у сеансі, запущеному з --allow-plugin-grants @@ -5663,6 +5775,12 @@ axis Y Axis Вісь Y @msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` має містити 1-64 друковані символи @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: використайте id з 1-{MAX_COMMAND_ID} символів a-z 0-9 _, що починається з літери @msg command {name}: {e} команда {name}: {e} +@msg manifest: {e} маніфест: {e} +@msg manifest: {e} at line {line} column {column} маніфест: {e} (рядок {line}, стовпець {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` має бути списком команд, кожна з `id` і `label` +@msg command {name} must be an object with an `id` and a `label` команда {name} має бути об'єктом з `id` і `label` +@msg missing field `{key}` немає поля `{key}` +@msg duplicate field `{key}` поле `{key}` вказано двічі @msg only a filter or a live effect declares `commands` `commands` оголошує лише фільтр або динамічний ефект @msg “{name}” › {label}: {e} «{name}» › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed модуль має не той SHA-256, що вказаний у `hash`: нічого не встановлено @@ -5687,6 +5805,16 @@ axis Y Axis Вісь Y @msg message must be text message має бути текстом @msg allowContinue must be true or false allowContinue має бути true або false @msg Batch cannot play an action with a stop Пакет не може відтворити дію із зупинкою + Insert Menu Item… Вставити пункт меню… + Insert Menu Item Вставити пункт меню + Menu Item: Пункт меню: + No menu item matches. Немає відповідних пунктів меню. + Several menu items match. Choose one from the list. Відповідає кілька пунктів меню. Виберіть один зі списку. + Items that open a dialog, and File, Window and Help menu items, are not listed. Пункти, що відкривають діалогове вікно, і пункти меню «Файл», «Вікно» та «Довідка» не показано. +@msg command must be text command має бути текстом +@msg no menu item that can be inserted runs this command жоден пункт меню, який можна вставити, не виконує цю команду +@msg the action already has 10,000 steps дія вже має 10 000 кроків +@msg the action set would be larger than 8 MiB набір дій став би більшим за 8 MiB Playback Options Параметри відтворення Accelerated Прискорено Step by Step Покроково @@ -5725,6 +5853,12 @@ axis Y Axis Вісь Y Crosshair Приціл Checkpoint Контрольна точка Inventory Icons Піктограми інвентарю + Skill Icons Іконки навичок + Attack Атака + Defend Захист + Heal Лікування + Buff Посилення + Ult Ульт Sword Меч Shield Щит Potion Зілля @@ -5789,7 +5923,23 @@ axis Y Axis Вісь Y Dash Trail Пунктирний слід Speed Line Лінія швидкості Game Trails Ігрові сліди + Energy Beams Енергетичні промені + Laser Bolt Лазерний заряд + Plasma Arc Плазмова дуга + Charge Wave Хвиля заряду + Spark Trail Слід іскор Calligraphic Nibs Каліграфічні пера + Bristle Brushes Щетинні пензлі + Fine Liner Тонкий лайнер + Pointed Flat Загострений плаский + Stubby Round Короткий круглий + Dry Scrub Сухе розтирання + Soft Dome М'який купол + Filbert Котячий язик + Angled Round Скошений круглий + Angled Flat Скошений плаский + Fan Blender Віяло для розтушовування + Grass Fan Віяло для трави Pattern Borders Візерункові облямівки Scatter Shapes Розсіяні фігури Save Brush Library… Зберегти бібліотеку пензлів… @@ -5989,9 +6139,12 @@ anchor Points: Точки: @msg {label} must be a number {label} має бути числом @msg {label} must be a number of at least 0.1 {label} має бути числом не менше 0,1 Advanced Character Formats Додаткові формати символів + Basic Paragraph Formats Основні формати абзацу + Composition Компонування Horizontal Scale Масштаб по горизонталі Vertical Scale Масштаб за вертикаллю @msg {label} must be a number from {min} to {max} {label} має бути числом від {min} до {max} +@msg {label} must be a whole number from {min} to {max} {label} має бути цілим числом від {min} до {max} Character Color Колір символів OpenType Features Функції OpenType Stylistic Sets Стилістичні набори @@ -5999,6 +6152,10 @@ anchor Points: Точки: @msg features lists at most {max} tags features містить не більше {max} тегів @msg unknown OpenType feature `{t}` невідома функція OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} має бути числом більше 0 і не більше {max} +@msg {label} must be at most {max} characters {label} має містити не більше {max} символів +@msg {label} must be one character {label} має бути одним символом +@msg at most {max} tab stops не більше {max} позицій табуляції +@msg unknown align `{other}` невідоме вирівнювання `{other}` @msg no character style `{name}` Стиль символів `{name}` не знайдено # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6161,6 +6318,12 @@ breakText Glyphs Гліфи Delete the selected brushes? Видалити вибрані пензлі? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Обведення використовують один або кілька з цих пензлів. Забрати пензлі з цих обведень і видалити пензлі? Remove Strokes Забрати обведення + Place Brush Art Розмістити малюнок пензля + Replace Brush Art Замінити малюнок пензля + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обведення використовують цей пензель. Застосувати новий малюнок до цих обведень чи залишити їх як є і додати копію пензля з новим малюнком? + Apply to Strokes Застосувати до обведень + Leave Strokes Залишити обведення +@msg `{name}` has no art (only scatter, art and pattern brushes do) у `{name}` немає малюнка (він є лише в пензлів-розпорошень, художніх і візерункових пензлів) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Інструменти розміщення Arrange in Grid… Розмістити сіткою… @@ -6356,6 +6519,11 @@ breakText Glyphs Гліфи @msg only an exporter or an importer declares `extensions` `extensions` оголошує лише модуль експорту або імпорту @msg an importer always gets an import's budget: leave `budget` out модуль імпорту завжди отримує бюджет імпорту: не вказуйте `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Копіювати відомості для усунення несправностей +@msg Copied the troubleshooting info Відомості для усунення несправностей скопійовано +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Останній сеанс VectorCraft перестав відповідати перед закриттям. Довідка › Копіювати відомості для усунення несправностей копіює подробиці для звіту про помилку + # Safe Mode Safe Mode… Безпечний режим… Safe Mode Безпечний режим @@ -6376,6 +6544,8 @@ breakText Glyphs Гліфи # Align to Pixel Grid Align to Pixel Grid Вирівняти за піксельною сіткою + Align New Objects to Pixel Grid Вирівнювати нові об’єкти за піксельною сіткою + Not Aligned to Pixel Grid Не вирівняні за піксельною сіткою @msg only paths and compound paths can be aligned to the pixel grid за піксельною сіткою можна вирівняти лише контури і складені контури @msg side is left or right, not `{s}` side — це left або right, а не `{s}` Ignore All Пропустити все @@ -6406,8 +6576,33 @@ breakText Glyphs Гліфи @plural {n} line cut|{n} lines cut {n} рядок обрізано|{n} рядки обрізано|{n} рядків обрізано @msg `first` and `last` must be numbers of lines the console holds, first before last `first` і `last` мають бути номерами рядків, які зберігає консоль, причому `first` не пізніше `last` +# Learn panel + Learn Навчання + Explore tutorials Переглянути уроки + For you Для вас + Skills Навички + Get started Початок роботи + Quick skill guide Короткий посібник із навичок + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Короткі практичні уроки з основних інструментів, згруповані за навичками. Виберіть навичку, щоб побачити її уроки. + List Tutorials Перелічити уроки + Show Tutorial Показати урок +@msg missing `tutorial` (see learn.list) відсутній `tutorial` (див. learn.list) +@msg unknown tutorial `{id}` (see learn.list) невідомий урок `{id}` (див. learn.list) + # Deferred plug-in effects Refresh Deferred Effects Оновити відкладені ефекти Deferred Effects Відкладені ефекти @msg no plug-in effect is deferred немає відкладених ефектів модулів @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Відкрито з {n} відкладеним ефектом модуля. Ефект › Оновити відкладені ефекти виконає його.|Відкрито з {n} відкладеними ефектами модулів. Ефект › Оновити відкладені ефекти виконає їх.|Відкрито з {n} відкладеними ефектами модулів. Ефект › Оновити відкладені ефекти виконає їх. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Інструменти різання + Stencil Bridges… Містки трафарету… + Stencil Bridges Містки трафарету + Shortest Crossing Найкоротший перетин + Direction Напрямок +@msg The selected art has no islands to bridge У виділеній графіці немає острівців для з’єднання +@msg No bridge of this width fits across the selected art Місток такої ширини не вміщується впоперек виділеної графіки +@msg Some islands could not be joined to the area around the art Деякі острівці не вдалося з’єднати з областю навколо графіки +@msg `width` must be from {lo} to {hi} pt `width` має бути від {lo} до {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` має бути цілим числом від 1 до {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d458c348ee..b14c946cb8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -289,6 +289,7 @@ font-technology Variable Biến thiên Asset Export Settings Cài đặt xuất asset Assets Asset Assign Gán + Assign Profile Gán hồ sơ màu Assign Profile… Gán hồ sơ màu… Assign: Gán: Attach to Active Plane Gắn vào mặt phẳng đang hoạt động @@ -801,6 +802,15 @@ font-technology Variable Biến thiên Created: Ngày tạo: Crop Cắt xén Crop Image Cắt xén ảnh + Image Tools Công cụ hình ảnh + Remove Background… Xóa nền… + Remove Background Xóa nền + Background Nền + Edge Color Màu cạnh + Picked Colors Màu đã chọn + Corner Color Màu góc + Contiguous Liền kề + Each Channel Từng kênh Edit Path Sửa đường dẫn Crop Marks Dấu cắt xén Crop To Cắt xén đến @@ -954,6 +964,14 @@ font-technology Variable Biến thiên Disable Auto Add/Delete Tắt tự động thêm/xóa Disable Opacity Mask Tắt mặt nạ độ mờ Discard Loại bỏ + Preserve Bảo lưu + TIFF (Black & White) TIFF (Đen trắng) + TIFF (8-bit Color) TIFF (Màu 8 bit) + High Resolution Độ phân giải cao + Medium Resolution Độ phân giải vừa + Low Resolution Độ phân giải thấp + Language Level 2 Cấp ngôn ngữ 2 + Language Level 3 Cấp ngôn ngữ 3 Discard Empty Type Loại bỏ chữ trống Discard Recovered Documents Loại bỏ tài liệu đã phục hồi Discard White Overprint in Output Loại bỏ in chồng màu trắng khi xuất @@ -988,6 +1006,13 @@ font-technology Variable Biến thiên Dock Panel Neo bảng Dock to Top Neo lên trên Dock to Bottom Neo xuống dưới + Control Bar Options Tùy chọn thanh điều khiển + Tool Options Tùy chọn công cụ + Object Options Tùy chọn đối tượng + Image Options Tùy chọn hình ảnh + Vertical Alignment Căn chỉnh dọc + Align and Distribute Căn chỉnh và phân bố + Document Options Tùy chọn tài liệu Dock Control Bar Neo thanh điều khiển Document Tài liệu Document Color Mode Chế độ màu tài liệu @@ -1304,6 +1329,8 @@ font-technology Variable Biến thiên Extrude & Bevel… Kéo dài & vát… 3D (Classic) 3D (cổ điển) Extrude & Bevel (Classic)… Kéo dài & vát (cổ điển)… + Revolve (Classic)… Xoay tròn (cổ điển)… + Rotate (Classic)… Xoay (cổ điển)… Surface Bề mặt Wireframe Khung dây No Shading Không tô bóng @@ -1670,6 +1697,14 @@ file-filter Templates Mẫu Halo Vầng hào quang Hand Tool Công cụ Bàn tay Hand-Drawn Vẽ tay + Painted and Sketched Vẽ màu và phác thảo + Washed Blue Xanh nhạt nhòa + Bristle Ochre Vàng đất cọ khô + Pastel Heather Tím phấn màu + Charcoal Shade Bóng than + Ink Contour Đường viền mực + Wet Ink Mực ướt + Fine Pen Bút mảnh Handles Tay nắm Hard Cứng Hard Light Ánh sáng mạnh @@ -1950,6 +1985,7 @@ digits Hindi Hindi Include Linked Files Bao gồm tệp được liên kết Include Metadata Bao gồm siêu dữ liệu Include non-printing layers Bao gồm các lớp không in + Write pages longer than 200 in at full size in points Ghi các trang dài hơn 200 in ở kích thước đầy đủ, theo điểm Include SVG Code Bao gồm mã SVG Include Swatches for Tints Bao gồm mẫu màu cho sắc pha Increase Font Size Tăng cỡ chữ @@ -2634,6 +2670,15 @@ digits Hindi Hindi Open… Mở… Optical Quang học Optical Margin Alignment Căn lề quang học + Dynamic Text Văn bản động + Dynamic Text Presets Thiết lập sẵn văn bản động + Arch Vòm +@msg select point type or type on a path chọn chữ điểm hoặc chữ trên đường dẫn +@msg type on a path in a thread cannot use Dynamic Text: {frames} chữ trên đường dẫn trong văn bản chuỗi không thể dùng văn bản động: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} không thể căn giữa ở trên hoặc ở dưới chữ trên đường dẫn mở hoặc đường dẫn phức: {open} +@msg type on a path with no length or no height cannot be centered: {flat} không thể căn giữa chữ trên đường dẫn không có độ dài hoặc không có chiều cao: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} không thể căn giữa ở trên hoặc ở dưới chữ trên đường dẫn trong văn bản chuỗi: {frames} +@msg select type on a closed path hãy chọn chữ trên một đường dẫn khép kín Optimize for fast web view Tối ưu để xem web nhanh Optimized Đã tối ưu Options Tùy chọn @@ -2857,6 +2902,7 @@ diagnostics ui giao diện Press Nhấn Pressure Áp lực Preview Xem trước + Preview: Xem trước: Preview All Layers Xem trước tất cả lớp Preview in Browser Xem trước trong trình duyệt Preview in Browser needs the desktop app (the web downloads files instead) Xem trước trong trình duyệt cần ứng dụng máy tính để bàn (web sẽ tải tệp xuống thay thế) @@ -2931,7 +2977,11 @@ mark-style Japanese Kiểu Nhật Radial Blur… Mờ hướng tâm… Radial Dividers: Đường chia hướng tâm: Radial Glows Ánh sáng hướng tâm + Organic Fades Mờ dần tự nhiên + Holographic Ảnh ba chiều Radial Gradient Chuyển sắc hướng tâm + Conic Gradient Chuyển sắc hình nón + Diamond Gradient Chuyển sắc hình thoi Radius Bán kính Radius 1 Bán kính 1 Radius 2 Bán kính 2 @@ -2946,6 +2996,8 @@ mark-style Japanese Kiểu Nhật Range: Phạm vi: Raster Effects Hiệu ứng raster Raster File Format: Định dạng tệp raster: + Include Placed Images Bao gồm ảnh đã đặt + Include Fill Hatches Bao gồm mẫu gạch của vùng tô Raster Sample Size: Kích thước mẫu raster: Raster/Vector Balance: Cân bằng raster/vector: Rasterize Raster hóa @@ -3103,6 +3155,10 @@ mark-style Japanese Kiểu Nhật Replace Font Thay thế phông chữ Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Thay thế bằng tệp khác hoặc bỏ qua: ảnh của nó vẫn hiển thị bản xem trước đã lưu cùng tài liệu. Replace Spine Thay thế trục + Create Spine Tạo trục + Create Spine: Tạo trục: + Always Luôn luôn + Never Không bao giờ Replace Symbol Thay thế ký hiệu Reset Transformation Đặt lại biến đổi Replace With Font Thay thế bằng phông chữ @@ -3204,6 +3260,9 @@ mark-style Japanese Kiểu Nhật Rise… Nâng lên… Roman Baseline Đường cơ sở Roman Roman Hanging Punctuation Dấu câu treo Roman + Korean Line Break Anywhere Ngắt dòng tiếng Hàn ở bất kỳ đâu + East Asian Composition Settings Cài đặt dàn trang Đông Á + Korean Composition Settings Cài đặt dàn trang tiếng Hàn Rotate Xoay Rotate 90° CW Xoay 90° theo chiều kim đồng hồ Rotate Tool Công cụ Xoay @@ -3524,6 +3583,15 @@ mark-style Japanese Kiểu Nhật Stun Pulse Choáng Stealth Fade Ẩn thân Shield Buff Khiên + Textures Kết cấu + Fine Grain Hạt mịn + Canvas Weave Vải canvas + Burlap Sack Bao bố + Cracked Glaze Men rạn + Mosaic Floor Sàn khảm + Quilted Squares Ô chần bông + Leaded Glass Kính chì + Damp Paper Giấy ẩm Shape Hình dạng Shape Builder Tạo hình dạng Shape Builder Regions Vùng Tạo hình dạng @@ -3594,6 +3662,7 @@ mark-style Japanese Kiểu Nhật Show Modified Hiện đã sửa đổi Show Note Hiện ghi chú Show Options Hiện tùy chọn + Show Recent Colors Hiện màu gần đây Show Original Path Hiện đường dẫn gốc Open this dialog with these settings next time Lần sau mở hộp thoại này với các cài đặt này Auto-Simplify Tự động đơn giản hóa @@ -3893,6 +3962,8 @@ mark-style Japanese Kiểu Nhật Scale at Center Co giãn từ tâm Up/Down: Lên/Xuống: Left/Right: Trái/Phải: + Tate-chu-yoko Up/Down Tate-chu-yoko lên/xuống + Tate-chu-yoko Left/Right Tate-chu-yoko trái/phải Temperature Nhiệt độ màu Temperature/Tint… Nhiệt độ màu/Tông… Template Mẫu @@ -3985,6 +4056,8 @@ mark-style Japanese Kiểu Nhật Toolbar: Add Tool Thanh công cụ: Thêm công cụ Toolbar: Advanced / Basic Thanh công cụ: Nâng cao / Cơ bản Toolbar: Remove Tool Thanh công cụ: Gỡ công cụ + Add Tool… Thêm công cụ… + Remove Tool Gỡ công cụ Toolbar: Reset Thanh công cụ: Đặt lại Toolbar: Single/Double Column Thanh công cụ: Một/Hai cột Toolbars Thanh công cụ @@ -4076,6 +4149,8 @@ mark-style Japanese Kiểu Nhật Type on a Path Chữ trên đường dẫn Type on a Path Options Tùy chọn chữ trên đường dẫn Type on a Path Options… Tùy chọn chữ trên đường dẫn… + Center on Top Căn giữa ở trên + Center on Bottom Căn giữa ở dưới Type on a Path Tool Công cụ Chữ trên đường dẫn Type Orientation Hướng chữ Type stays text, and every stroke is a line with its lineweight and dashes. Chữ vẫn là văn bản, và mỗi nét là đường thẳng với độ dày và nét đứt. @@ -4256,6 +4331,7 @@ mark-style Japanese Kiểu Nhật Windows Windows Working CMYK CMYK làm việc Working CMYK (don't tag) CMYK làm việc (không gắn thẻ) + Working RGB (don't tag) RGB làm việc (không gắn thẻ) Workspace Không gian làm việc Workspace {i} Không gian làm việc {i} Wrinkle Tool Công cụ nhăn @@ -4358,10 +4434,13 @@ theme Appearance Giao diện @msg `colors` must be an array of colors, not {v} `colors` phải là mảng màu, không phải {v} @msg `library` is a library id or name (see {list}) `library` là id hoặc tên thư viện (xem {list}) @msg `mode` applies to freeform gradients `mode` áp dụng cho chuyển sắc tự do +@msg a negative `aspect` applies to conic gradients `aspect` âm áp dụng cho chuyển sắc hình nón +@msg `focal` applies to radial gradients `focal` áp dụng cho chuyển sắc xuyên tâm @msg `preserve` must be an object `preserve` phải là một đối tượng @msg `globalAdjust` must be an object `globalAdjust` phải là một đối tượng @msg `sampleSize` must be 1, 3 or 5 `sampleSize` phải là 1, 3 hoặc 5 @msg `stops` must be an array `stops` phải là một mảng +@msg `{key}` must be an array `{key}` phải là một mảng @msg `svg` must be an object of SVG options (see document.formats) `svg` phải là đối tượng tùy chọn SVG (xem document.formats) @msg `to` must be "corner" or "smooth" `to` phải là "corner" hoặc "smooth" @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` phải là "emBox", "capHeight", "xHeight" hoặc "icfBox" @@ -4377,6 +4456,7 @@ theme Appearance Giao diện @msg `{key}` must be a number, not {v} `{key}` phải là một số, không phải {v} @msg {key} must be Unix seconds (an integer) or null {key} phải là thời gian Unix tính bằng giây (số nguyên) hoặc null @msg `{key}` must be a string `{key}` phải là một chuỗi +@msg `{key}` must be a profile name or null `{key}` phải là tên hồ sơ màu hoặc null @msg `{key}` must be a whole number `{key}` phải là số nguyên @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` phải là số nguyên từ {min} đến {max} (nhận được {x}) @msg `{key}` must be between {min} and {max} (got {x}) `{key}` phải nằm trong khoảng {min} đến {max} (nhận được {x}) @@ -4652,6 +4732,7 @@ theme Appearance Giao diện @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller trang của bảng vẽ {n} có kích thước {size}, dài hơn giới hạn trang PDF 14.400 pt (200 in): trang được ghi với UserUnit là {unit}, nên các ứng dụng bỏ qua UserUnit sẽ hiển thị nó nhỏ đi bấy nhiêu lần @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in trang của bảng vẽ {n} có kích thước {size}, dài hơn giới hạn trang PDF 14.400 pt (200 in): các trang {label} được ghi không có UserUnit, theo đơn vị điểm, và các ứng dụng tuân theo giới hạn sẽ cắt trang ở 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 không có UserUnit, thứ mà trang dài hơn 14.400 pt (200 in) cần để giữ kích thước: tệp được ghi dưới dạng PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 không có UserUnit, thứ mà trang dài hơn 14.400 pt (200 in) cần để nằm trong giới hạn trang 14.400 đơn vị của PDF/A-2: tệp được ghi dưới dạng PDF 1.6 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units trang của bảng vẽ {n} có kích thước {size}, quá dài và hẹp so với cạnh trang PDF từ 3 đến 14.400 đơn vị: trang được ghi với UserUnit {unit}, giữ cạnh ngắn từ 3 đơn vị trở lên, và các ứng dụng tuân theo giới hạn sẽ cắt cạnh dài ở 14.400 đơn vị @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard tệp {label} chỉ chứa số thực tối đa {max}, còn trang của bảng vẽ {n} dài {side} pt cần số lớn hơn: hãy chọn PDF 1.6 trở lên không theo tiêu chuẩn PDF/X, hoặc một bảng vẽ nhỏ hơn @msg invalid restored panel group nhóm bảng được phục hồi không hợp lệ @@ -4854,6 +4935,8 @@ theme Appearance Giao diện @msg not a shortcut set: the text doesn't start with a slash name and an opening brace không phải bộ phím tắt: văn bản không bắt đầu bằng một tên có dấu gạch chéo và một dấu ngoặc nhọn mở @msg This shortcut file is in a form VectorCraft can't read. Tệp phím tắt này có dạng mà VectorCraft không đọc được. @msg not an EMF or WMF file không phải tệp EMF hoặc WMF +@msg not an HP-GL file không phải tệp HP-GL +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` phải là mảng từ 1 đến 255 màu #rrggbb @msg not found không tìm thấy @msg not in pattern editing mode không ở chế độ chỉnh sửa họa tiết @msg finish editing the pattern first hãy hoàn tất chỉnh sửa họa tiết trước @@ -4877,6 +4960,8 @@ theme Appearance Giao diện @msg invalid object id {value}: expected a non-negative integer id đối tượng {value} không hợp lệ: cần một số nguyên không âm @msg `{key}` entry {index} is {value}, not a non-negative integer object id mục {index} của `{key}` là {value}, không phải id đối tượng (số nguyên không âm) @msg no such object id {value} không có đối tượng nào có id {value} +@msg id {value} is a ruler guide, not an object id {value} là của đường căn, không phải của đối tượng +@msg a ruler guide goes only directly in a layer or sublayer đường căn chỉ có thể nằm trực tiếp trong lớp hoặc lớp con @msg id {value} is a layer, not an object id {value} là một lớp, không phải đối tượng @msg id {value} is a layer, not an object; move layers with layer.move id {value} là một lớp, không phải đối tượng; hãy di chuyển lớp bằng layer.move @msg object {0} cannot have children đối tượng {0} không thể có phần tử con @@ -4997,6 +5082,14 @@ theme Appearance Giao diện @msg a symbol can't hold an instance of itself ký hiệu không thể chứa đối tượng của chính nó @msg select an envelope hãy chọn một Envelope @msg select an image hãy chọn ảnh +@msg `background` must be edges, corners or colors `background` phải là edges, corners hoặc colors +@msg `match` must be distance or channels `match` phải là distance hoặc channels +@msg `{key}` must be from 0 to 100 `{key}` phải nằm trong khoảng 0 đến 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` phải liệt kê từ 1 đến 16 màu, mỗi màu viết dạng hex (#rrggbb hoặc #rgb) hoặc là black, white, red, green hay blue +@msg the linked image shows its preview: embed or relink it first hình ảnh được liên kết đang hiển thị bản xem trước: hãy nhúng hoặc liên kết lại trước +@msg a CMYK image has no transparency to set ảnh CMYK không có độ trong suốt để đặt +@msg every pixel matches the background: no image would be left mọi điểm ảnh đều khớp với nền: sẽ không còn lại ảnh nào +@msg an image of {w} × {h} pixels is too large to change ảnh {w} × {h} điểm ảnh quá lớn nên không thể thay đổi @msg select an Image Trace object hãy chọn đối tượng vector hóa ảnh @msg select an object in perspective hãy chọn đối tượng trong phối cảnh @msg select artwork (or a colour group) to recolor hãy chọn tác phẩm (hoặc nhóm màu) để tô lại @@ -5170,7 +5263,7 @@ theme Appearance Giao diện @msg unknown format định dạng không xác định @msg unknown format `{f}` (Save writes {_1}) định dạng không xác định `{f}` (Lưu ghi {_1}) @msg unknown freeform mode `{m}` (points, lines) chế độ tự do không xác định `{m}` (points, lines) -@msg unknown gradient kind `{k}` (linear, radial, freeform) loại chuyển sắc không xác định `{k}` (linear, radial, freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) loại chuyển sắc không xác định `{k}` (linear, radial, conic, diamond, freeform) @msg unknown highlight `{h}` tô sáng không xác định `{h}` @msg unknown option `{path}.{k}` tùy chọn không xác định `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) chế độ in đè không xác định `{o}` (preserve, simulate hoặc discard) @@ -5229,7 +5322,13 @@ theme Appearance Giao diện @msg x and y must be provided together x và y phải được cung cấp cùng nhau @msg x and y must both be numbers x và y đều phải là số @msg Your unsaved changes are kept in this browser: reload the page to get them back. Các thay đổi chưa lưu được giữ trong trình duyệt này: tải lại trang để lấy lại. -@msg zipped 32-bit PSD image data with prediction can't be read dữ liệu ảnh PSD 32-bit nén với dự đoán không thể đọc được +@msg zipped 1-bit PSD image data with prediction can't be read dữ liệu ảnh PSD 1-bit nén với dự đoán không thể đọc được +@msg the PSD file's layer data uses an unknown compression ({m}) dữ liệu lớp của tệp PSD dùng nén không xác định ({m}) +@msg the PSD file's layer records are damaged bản ghi lớp của tệp PSD bị hỏng +@msg the PSD file's layer groups are nested too deeply các nhóm lớp của tệp PSD lồng nhau quá sâu +@msg a layer of the PSD file is too large to read một lớp của tệp PSD quá lớn để đọc +@msg the PSD file's layers take more memory to read than allowed các lớp của tệp PSD cần nhiều bộ nhớ để đọc hơn mức cho phép +@msg the layers can't be read ({e}): the file opened as its merged image không thể đọc các lớp ({e}): tệp được mở dưới dạng ảnh đã gộp @msg zone must be a string zone phải là chuỗi @msg zone must be tab, center, left, right, top or bottom zone phải là tab, center, left, right, top hoặc bottom @msg {_1} failed: {e} {_1} thất bại: {e} @@ -5297,6 +5396,11 @@ theme Appearance Giao diện Softness Độ mềm Ambient Light Ánh sáng môi trường Light behind the object Ánh sáng phía sau đối tượng + Shadows Bóng đổ + Distance from Object Khoảng cách từ đối tượng + Shadow Bounds Giới hạn bóng + Behind Object Phía sau đối tượng + Below Object Bên dưới đối tượng 3D Lighting Preset Thiết lập sẵn ánh sáng 3D Standard Tiêu chuẩn Diffuse Khuếch tán @@ -5362,7 +5466,7 @@ theme Appearance Giao diện @msg span must be "object" or "selection", got {v} span phải là "object" hoặc "selection", không phải {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" đặt một `gradient`, không phải mẫu màu @msg span: "selection" places a gradient: give `gradient` span: "selection" đặt một dải chuyển màu: hãy cung cấp `gradient` -@msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" đặt dải chuyển màu tuyến tính hoặc xuyên tâm, không phải dạng tự do +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" đặt dải chuyển màu tuyến tính, xuyên tâm, hình nón hoặc hình thoi, không phải dạng tự do @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" tự đặt dải chuyển màu: hãy bỏ `start` và `end` (chúng đã đặt nó theo tọa độ tài liệu) Make Image Dynamic Tạo hình ảnh động Import Data Sets… Nhập tập dữ liệu… @@ -5547,6 +5651,7 @@ theme Appearance Giao diện Ruby Ruby Geometric Guides Đường dẫn hình học Geometric Patterns Họa tiết hình học + Grit Textures Kết cấu hạt Ease In Chậm lúc đầu Ease Out Chậm lúc cuối Ease In Out Chậm lúc đầu và cuối @@ -5607,6 +5712,8 @@ axis Y Axis Trục Y Version: {version} Phiên bản: {version} Install “{name}” in place of the plug-in with the same ID? Cài đặt “{name}” thay cho plug-in có cùng ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tệp này không phải là plug-in đã cài đặt trước đây với ID này. Tệp sẽ nhận cài đặt và bộ nhớ đệm được lưu cho ID đó. + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Một tác vụ tự động đã yêu cầu cài đặt plug-in này. Để cài đặt, hãy tự mình chọn lệnh Đối tượng › Plug-in › Cài đặt plug-in… trong menu. +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Một tác vụ tự động đã yêu cầu cài đặt plug-in này. Để cài đặt, hãy tự mình chọn lệnh Đối tượng › Plug-in › Cài đặt plug-in… trong menu. @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}” là mô-đun khác với plug-in có ID {_1} và sẽ nhận cài đặt và bộ nhớ đệm được lưu cho plug-in đó: hãy cài đặt với `replace: true` khi người dùng đồng ý File SHA-256: {hash} SHA-256 của tệp: {hash} Read the objects it is given Đọc các đối tượng được trao cho nó @@ -5652,6 +5759,11 @@ axis Y Axis Trục Y @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) ngân sách bộ nhớ (đối tượng {_1} cần {size} byte đầu vào, còn lại {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) ngân sách đối tượng (hơn {MAX_OBJECTS} đối tượng chỉ đọc) +@msg instruction budget ngân sách lệnh +@msg time budget ngân sách thời gian +@msg memory budget (the selection is too large to hand over) ngân sách bộ nhớ (vùng chọn quá lớn để chuyển giao) +@msg output size ({what} is {len} bytes, limit {max}) kích thước đầu ra ({what} là {len} byte, giới hạn {max}) +@msg the plug-in's grant can't be removed from the plug-in store không thể xóa quyền của plug-in khỏi kho plug-in @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it quyền `{shown}` được dành cho một API plug-in sau này; máy chủ này không cấp quyền đó @msg unknown permission `{shown}` quyền không xác định `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” yêu cầu các quyền {asked}: cần một người phê duyệt trong ứng dụng máy tính, hoặc truyền `grant` trong phiên khởi động bằng --allow-plugin-grants @@ -5664,6 +5776,12 @@ axis Y Axis Trục Y @msg command {name}: `label` must be 1-64 printable characters lệnh {name}: `label` phải có 1-64 ký tự in được @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter lệnh {name}: hãy dùng id gồm 1-{MAX_COMMAND_ID} ký tự từ a-z 0-9 _ và bắt đầu bằng một chữ cái @msg command {name}: {e} lệnh {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} (dòng {line}, cột {column}) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` phải là một danh sách lệnh, mỗi lệnh có `id` và `label` +@msg command {name} must be an object with an `id` and a `label` lệnh {name} phải là một đối tượng có `id` và `label` +@msg missing field `{key}` thiếu trường `{key}` +@msg duplicate field `{key}` trường `{key}` bị lặp @msg only a filter or a live effect declares `commands` chỉ bộ lọc hoặc hiệu ứng trực tiếp mới khai báo `commands` @msg “{name}” › {label}: {e} “{name}” › {label}: {e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed mô-đun không có SHA-256 mà `hash` cho biết: không có gì được cài đặt @@ -5688,6 +5806,16 @@ axis Y Axis Trục Y @msg message must be text message phải là văn bản @msg allowContinue must be true or false allowContinue phải là true hoặc false @msg Batch cannot play an action with a stop Hàng loạt không thể phát hành động có điểm dừng + Insert Menu Item… Chèn mục menu… + Insert Menu Item Chèn mục menu + Menu Item: Mục menu: + No menu item matches. Không có mục menu nào khớp. + Several menu items match. Choose one from the list. Có nhiều mục menu khớp. Hãy chọn một mục trong danh sách. + Items that open a dialog, and File, Window and Help menu items, are not listed. Các mục mở hộp thoại và các mục trong menu Tệp, Cửa sổ và Trợ giúp không được liệt kê. +@msg command must be text command phải là văn bản +@msg no menu item that can be inserted runs this command không có mục menu nào có thể chèn chạy lệnh này +@msg the action already has 10,000 steps hành động đã có 10.000 bước +@msg the action set would be larger than 8 MiB bộ hành động sẽ lớn hơn 8 MiB Playback Options Tùy chọn phát lại Accelerated Tăng tốc Step by Step Từng bước @@ -5726,6 +5854,12 @@ axis Y Axis Trục Y Crosshair Tâm ngắm Checkpoint Điểm kiểm tra Inventory Icons Biểu tượng túi đồ + Skill Icons Biểu tượng kỹ năng + Attack Tấn công + Defend Phòng thủ + Heal Hồi máu + Buff Buff + Ult Ult Sword Kiếm Shield Khiên Potion Thuốc @@ -5790,7 +5924,23 @@ axis Y Axis Trục Y Dash Trail Vệt đứt đoạn Speed Line Đường tốc độ Game Trails Vệt game + Energy Beams Chùm năng lượng + Laser Bolt Tia laser + Plasma Arc Cung plasma + Charge Wave Sóng nạp + Spark Trail Vệt tia lửa Calligraphic Nibs Ngòi bút thư pháp + Bristle Brushes Bộ cọ lông + Fine Liner Nét mảnh + Pointed Flat Cọ dẹt nhọn + Stubby Round Cọ tròn ngắn + Dry Scrub Chà khô + Soft Dome Vòm mềm + Filbert Cọ lưỡi mèo + Angled Round Cọ tròn xiên + Angled Flat Cọ dẹt xiên + Fan Blender Cọ quạt hòa trộn + Grass Fan Cọ quạt vẽ cỏ Pattern Borders Viền họa tiết Scatter Shapes Hình phân tán Save Brush Library… Lưu thư viện cọ… @@ -5990,9 +6140,12 @@ anchor Points: Điểm: @msg {label} must be a number {label} phải là một số @msg {label} must be a number of at least 0.1 {label} phải là một số ít nhất bằng 0,1 Advanced Character Formats Định dạng ký tự nâng cao + Basic Paragraph Formats Định dạng đoạn văn cơ bản + Composition Dàn trang Horizontal Scale Tỷ lệ ngang Vertical Scale Tỷ lệ dọc @msg {label} must be a number from {min} to {max} {label} phải là một số từ {min} đến {max} +@msg {label} must be a whole number from {min} to {max} {label} phải là một số nguyên từ {min} đến {max} Character Color Màu ký tự OpenType Features Tính năng OpenType Stylistic Sets Bộ phong cách @@ -6000,6 +6153,10 @@ anchor Points: Điểm: @msg features lists at most {max} tags features chứa tối đa {max} thẻ @msg unknown OpenType feature `{t}` tính năng OpenType không xác định `{t}` @msg {label} must be a number above 0 and at most {max} {label} phải là một số lớn hơn 0 và tối đa {max} +@msg {label} must be at most {max} characters {label} chỉ được có tối đa {max} ký tự +@msg {label} must be one character {label} phải là một ký tự +@msg at most {max} tab stops tối đa {max} điểm dừng tab +@msg unknown align `{other}` căn chỉnh không xác định `{other}` @msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6162,6 +6319,12 @@ breakText Glyphs Glyph Delete the selected brushes? Xóa các cọ đã chọn? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Có nét đang dùng một hoặc nhiều cọ này. Gỡ cọ khỏi các nét đó và xóa cọ? Remove Strokes Gỡ nét + Place Brush Art Đặt đối tượng của cọ + Replace Brush Art Thay đối tượng của cọ + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Có nét đang dùng cọ này. Áp dụng đối tượng mới cho các nét đó, hay giữ nguyên chúng và thêm một bản sao của cọ với đối tượng mới? + Apply to Strokes Áp dụng cho nét + Leave Strokes Giữ nguyên nét +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` không có đối tượng (chỉ cọ phân tán, cọ bản vẽ và cọ họa tiết mới có) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Công cụ sắp xếp Arrange in Grid… Sắp xếp theo lưới… @@ -6357,6 +6520,11 @@ breakText Glyphs Glyph @msg only an exporter or an importer declares `extensions` chỉ plug-in xuất hoặc nhập mới khai báo `extensions` @msg an importer always gets an import's budget: leave `budget` out plug-in nhập luôn nhận ngân sách của một lần nhập: hãy bỏ `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info Sao chép thông tin khắc phục sự cố +@msg Copied the troubleshooting info Đã sao chép thông tin khắc phục sự cố +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Phiên VectorCraft trước đã ngừng phản hồi trước khi đóng. Trợ giúp › Sao chép thông tin khắc phục sự cố sẽ sao chép chi tiết cho báo cáo lỗi + # Safe Mode Safe Mode… Chế độ an toàn… Safe Mode Chế độ an toàn @@ -6377,6 +6545,8 @@ breakText Glyphs Glyph # Align to Pixel Grid Align to Pixel Grid Căn theo lưới pixel + Align New Objects to Pixel Grid Căn đối tượng mới theo lưới pixel + Not Aligned to Pixel Grid Chưa căn theo lưới pixel @msg only paths and compound paths can be aligned to the pixel grid chỉ đường dẫn và đường dẫn phức mới căn theo lưới pixel được @msg side is left or right, not `{s}` side là left hoặc right, không phải `{s}` Ignore All Bỏ qua tất cả @@ -6407,8 +6577,33 @@ breakText Glyphs Glyph @plural {n} line cut|{n} lines cut đã cắt {n} dòng @msg `first` and `last` must be numbers of lines the console holds, first before last `first` và `last` phải là số thứ tự của các dòng mà bảng điều khiển đang giữ, `first` đứng trước `last` +# Learn panel + Learn Học + Explore tutorials Khám phá hướng dẫn + For you Dành cho bạn + Skills Kỹ năng + Get started Bắt đầu + Quick skill guide Hướng dẫn nhanh về kỹ năng + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. Các hướng dẫn thực hành ngắn cho những công cụ thiết yếu, xếp theo kỹ năng. Chọn một kỹ năng để xem các hướng dẫn của nó. + List Tutorials Liệt kê hướng dẫn + Show Tutorial Hiện hướng dẫn +@msg missing `tutorial` (see learn.list) thiếu `tutorial` (xem learn.list) +@msg unknown tutorial `{id}` (see learn.list) hướng dẫn không xác định `{id}` (xem learn.list) + # Deferred plug-in effects Refresh Deferred Effects Làm mới hiệu ứng bị hoãn Deferred Effects Hiệu ứng bị hoãn @msg no plug-in effect is deferred không có hiệu ứng plug-in nào bị hoãn @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Đã mở với {n} hiệu ứng plug-in bị hoãn. Hiệu ứng › Làm mới hiệu ứng bị hoãn sẽ chạy chúng. + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools Công cụ cắt + Stencil Bridges… Cầu nối khuôn tô… + Stencil Bridges Cầu nối khuôn tô + Shortest Crossing Đường cắt ngắn nhất + Direction Hướng +@msg The selected art has no islands to bridge Hình vẽ đã chọn không có đảo nào cần nối +@msg No bridge of this width fits across the selected art Không có cầu nối nào rộng như vậy vừa với hình vẽ đã chọn +@msg Some islands could not be joined to the area around the art Không thể nối một số đảo với vùng xung quanh hình vẽ +@msg `width` must be from {lo} to {hi} pt `width` phải từ {lo} đến {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` phải là số nguyên từ 1 đến {MAX_BRIDGES_PER_ISLAND} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 028bd60571..4f34af93dd 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -207,6 +207,7 @@ antiAlias Sharp 锐利 Asset Export Settings 资源导出设置 Assets 资源 Assign 指定 + Assign Profile 指定配置文件 Assign Profile… 指定配置文件… Assign: 指定: Attach to Active Plane 附加到活动平面 @@ -645,6 +646,15 @@ antiAlias Sharp 锐利 Created: 创建时间: Crop 裁剪 Crop Image 裁剪图像 + Image Tools 图像工具 + Remove Background… 移除背景… + Remove Background 移除背景 + Background 背景 + Edge Color 边缘颜色 + Picked Colors 选取的颜色 + Corner Color 转角颜色 + Contiguous 连续 + Each Channel 每个通道 Edit Path 编辑路径 Mask 蒙版 Crop Marks 裁切标记 @@ -1084,6 +1094,8 @@ antiAlias Sharp 锐利 Extrude & Bevel… 突出与斜角… 3D (Classic) 3D (经典) Extrude & Bevel (Classic)… 突出与斜角 (经典)… + Revolve (Classic)… 回转 (经典)… + Rotate (Classic)… 旋转 (经典)… Surface 表面 Wireframe 线框 No Shading 无底纹 @@ -1393,6 +1405,14 @@ file-filter Templates 模板 Hair Space 极细空格 Hand Tool 抓手工具 Hand-Drawn 手绘 + Painted and Sketched 绘画与素描 + Washed Blue 水洗蓝 + Bristle Ochre 干刷土黄 + Pastel Heather 粉彩淡紫 + Charcoal Shade 炭笔阴影 + Ink Contour 墨线轮廓 + Wet Ink 湿墨 + Fine Pen 细笔 Handles 手柄 Hard Light 强光 Hard Mix 实色混合 @@ -1613,6 +1633,7 @@ file-filter Templates 模板 Include Linked Files 包含链接文件 Include Metadata 包含元数据 Include non-printing layers 包含非打印图层 + Write pages longer than 200 in at full size in points 以实际尺寸(点)写入长于 200 in 的页面 Include SVG Code 包含 SVG 代码 Include Swatches for Tints 包含淡色色板 Inflate… 膨胀… @@ -2232,11 +2253,22 @@ file-filter Templates 模板 Open… 打开… Optical 视觉 Optical Margin Alignment 视觉边界对齐 + Dynamic Text 动态文本 + Dynamic Text Presets 动态文本预设 + Arch 拱形 +@msg select point type or type on a path 请选择点文字或路径文字 +@msg type on a path in a thread cannot use Dynamic Text: {frames} 串接文本中的路径文字不能使用动态文本:{frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} 开放路径或复合路径上的路径文字无法在顶部或底部居中:{open} +@msg type on a path with no length or no height cannot be centered: {flat} 路径没有长度或没有高度时,其路径文字无法居中:{flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} 串接文本中的路径文字无法在顶部或底部居中:{frames} +@msg select type on a closed path 请选择闭合路径上的路径文字 Optimize for fast web view 优化快速 Web 查看 Optimized 优化 Options 选项 Options: 选项: Options… 选项… + Organic Fades 自然渐隐 + Holographic 全息 or more spaces with a tab 或多个空格加一个制表符 Order: 顺序: Ordinals 序数字 @@ -2429,6 +2461,7 @@ diagnostics ui 界面 Presets: 预设: Press 按 Preview 预览 + Preview: 预览: Preview in Browser 在浏览器中预览 Preview in Browser needs the desktop app (the web downloads files instead) 在浏览器中预览需要桌面版应用程序 (网页版会改为下载文件) Preview Mode 预览模式 @@ -2511,6 +2544,8 @@ digits Malayalam 马拉雅拉姆数字 Radial 径向 Radial Glows 径向光晕 Radial Gradient 径向渐变 + Conic Gradient 圆锥渐变 + Diamond Gradient 菱形渐变 Radius 1 半径 1 Radius 2 半径 2 Radius1 半径1 @@ -2523,6 +2558,8 @@ digits Malayalam 马拉雅拉姆数字 Range: 范围: Raster Effects 栅格效果 Raster File Format: 栅格文件格式: + Include Placed Images 包含置入的图像 + Include Fill Hatches 包含填色的图案填充 Raster Sample Size: 栅格取样大小: Raster/Vector Balance: 栅格/矢量平衡: Rasterize 栅格化 @@ -2702,6 +2739,10 @@ digits Malayalam 马拉雅拉姆数字 Replace Font 替换字体 Replace it with another file, or ignore it: its images keep showing the preview saved with the document. 将其替换为其他文件,或忽略:其图像继续显示随文档保存的预览。 Replace Spine 替换脊线 + Create Spine 创建脊线 + Create Spine: 创建脊线: + Always 始终 + Never 从不 Replace Symbol 替换符号 Reset Transformation 重置变换 Replace With Font 替换为字体 @@ -2779,6 +2820,9 @@ digits Malayalam 马拉雅拉姆数字 Rise… 上升… Roman Baseline 罗马基线 Roman Hanging Punctuation 西文悬挂标点 + Korean Line Break Anywhere 韩文任意位置换行 + East Asian Composition Settings 东亚排版设置 + Korean Composition Settings 韩文排版设置 Rotate 旋转 Rotate 90° CW 顺时针旋转 90° Rotate Tool 旋转工具 @@ -3030,6 +3074,15 @@ digits Malayalam 马拉雅拉姆数字 Stun Pulse 眩晕 Stealth Fade 隐身 Shield Buff 护盾 + Textures 纹理 + Fine Grain 细颗粒 + Canvas Weave 帆布纹 + Burlap Sack 麻布袋 + Cracked Glaze 裂纹釉 + Mosaic Floor 马赛克地面 + Quilted Squares 绗缝方格 + Leaded Glass 铅条玻璃 + Damp Paper 湿纸 Shape 形状 Shape Builder 形状生成器 Shape Builder Regions 形状生成器区域 @@ -3090,6 +3143,7 @@ digits Malayalam 马拉雅拉姆数字 Show Modified 显示已修改 Show Note 显示注解 Show Options 显示选项 + Show Recent Colors 显示最近使用的颜色 Show Original Path 显示原始路径 Open this dialog with these settings next time 下次以这些设置打开此对话框 Auto-Simplify 自动简化 @@ -3394,6 +3448,8 @@ digits Malayalam 马拉雅拉姆数字 Scale at Center 从中心缩放 Up/Down: 上/下: Left/Right: 左/右: + Tate-chu-yoko Up/Down 纵中横上/下 + Tate-chu-yoko Left/Right 纵中横左/右 Temperature 色温 Temperature/Tint… 色温/色调… Template 模板 @@ -3462,6 +3518,8 @@ digits Malayalam 马拉雅拉姆数字 Toolbar: Single/Double Column 工具列:单列/双列 Toolbar: Add Tool 工具栏:添加工具 Toolbar: Remove Tool 工具栏:移除工具 + Add Tool… 添加工具… + Remove Tool 移除工具 Toolbar: Reset 工具栏:重置 Toolbars 工具栏 Tools 工具 @@ -3535,6 +3593,8 @@ digits Malayalam 马拉雅拉姆数字 Type on a Path 路径文字 Type on a Path Options 路径文字选项 Type on a Path Options… 路径文字选项… + Center on Top 在顶部居中 + Center on Bottom 在底部居中 Type on a Path Tool 路径文字工具 Type Orientation 文字方向 Type stays text, and every stroke is a line with its lineweight and dashes. 文字维持为文字,每个描边都是带有线宽与虚线的线条。 @@ -3744,6 +3804,7 @@ digits Malayalam 马拉雅拉姆数字 Windows Windows Working CMYK 工作 CMYK Working CMYK (don't tag) 工作 CMYK (不加标签) + Working RGB (don't tag) 工作 RGB (不加标签) Workspace 工作区 Workspace {i} 工作区 {i} Wrinkle Tool 褶皱工具 @@ -4062,16 +4123,19 @@ imageTrace Outline 轮廓 @msg `gradient` must be an object `gradient` 必须是对象 @msg `groupColors` must be an array `groupColors` 必须是数组 @msg `mode` applies to freeform gradients `mode` 仅适用于任意形状渐变 +@msg a negative `aspect` applies to conic gradients 负的 `aspect` 仅适用于圆锥渐变 +@msg `focal` applies to radial gradients `focal` 仅适用于径向渐变 @msg `preserve` must be an object `preserve` 必须是对象 @msg `globalAdjust` must be an object `globalAdjust` 必须是对象 @msg `stops` must be an array `stops` 必须是数组 +@msg `{key}` must be an array `{key}` 必须是数组 @msg `{k}` must be [x, y] `{k}` 必须是 [x, y] @msg a gradient needs at least two stops 渐变至少需要两个色标 @msg give both `start` and `end` [x, y] (or neither) 请同时给出 `start` 和 `end` [x, y] (或都不给出) @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 unknown gradient kind `{k}` (linear, radial, freeform) 未知的渐变类型 `{k}` (linear、radial、freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) 未知的渐变类型 `{k}` (linear、radial、conic、diamond、freeform) @msg the art could not be sampled 无法对图稿取样 @msg the art is too light for any dots 图稿太浅,无法生成任何网点 @msg the document has no symbols 文档中没有符号 @@ -4163,6 +4227,7 @@ imageTrace Outline 轮廓 @msg `{key}` must be `auto` or a language code such as `en` or `zh-hant` `{key}` 必须是 `auto` 或语言代码,例如 `en` 或 `zh-hant` @msg `{key}` must be a #rrggbb colour `{key}` 必须是 #rrggbb 颜色 @msg `{key}` must be a string `{key}` 必须是字符串 +@msg `{key}` must be a profile name or null `{key}` 必须是配置文件名称或 null @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 between {min} and {max} (got {x}) `{key}` 必须介于 {min} 和 {max} 之间 (实际为 {x}) @@ -4341,6 +4406,8 @@ imageTrace Outline 轮廓 @msg the image's pixels don't match its size 图像的像素与其尺寸不符 @msg {bpp}-bit bitmaps can't be read 无法读取 {bpp} 位位图 @msg not an EMF or WMF file 不是 EMF 或 WMF 文件 +@msg not an HP-GL file 不是 HP-GL 文件 +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` 必须是由 1 到 255 个 #rrggbb 格式颜色组成的数组 @msg its layers use {_1}, which aren't read yet 其图层使用了 {_1},尚不能读取 @msg the EMF header is damaged EMF 文件头已损坏 @msg damaged 已损坏 @@ -4357,6 +4424,7 @@ imageTrace Outline 轮廓 @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 画板 {n} 的页面为 {size},超过 PDF 的页面上限 14,400 pt (200 in):它以 UserUnit {unit} 写入,因此忽略 UserUnit 的应用会将其显示为缩小相应倍数 @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 画板 {n} 的页面为 {size},超过 PDF 的页面上限 14,400 pt (200 in):{label} 页面不带 UserUnit,以点为单位写入,遵守上限的应用会将页面裁切为 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 没有 UserUnit,而长于 14,400 pt (200 in) 的页面需要它来保持尺寸:文件将以 PDF 1.6 写入 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 没有 UserUnit,而长于 14,400 pt (200 in) 的页面需要它来保持在 PDF/A-2 的 14,400 单位页面上限之内:文件将以 PDF 1.6 写入 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 画板 {n} 的页面为 {size},对 PDF 3 至 14,400 单位的页面边长而言过长过窄:以 UserUnit {unit} 写入,使短边保持 3 单位以上,遵守上限的应用会把长边裁到 14,400 单位 @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 文件的实数最大为 {max},而画板 {n} 的页面长 {side} pt,需要更大的数:请选择不带 PDF/X 标准的 PDF 1.6 或更高版本,或使用更小的画板 @msg page {0} does not exist (the PDF has {1}) 页面 {0} 不存在 (该 PDF 有 {1} 页) @@ -4545,6 +4613,14 @@ imageTrace Outline 轮廓 @msg no such view 没有此视图 @msg printing isn't available here 此处无法打印 @msg select an image 请选择一个图像 +@msg `background` must be edges, corners or colors `background` 必须为 edges、corners 或 colors +@msg `match` must be distance or channels `match` 必须为 distance 或 channels +@msg `{key}` must be from 0 to 100 `{key}` 必须介于 0 到 100 之间 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` 必须列出 1 到 16 种颜色,每种写为十六进制(#rrggbb 或 #rgb)或 black、white、red、green、blue +@msg the linked image shows its preview: embed or relink it first 链接图像显示的是预览:请先嵌入或重新链接 +@msg a CMYK image has no transparency to set CMYK 图像没有可设置的透明度 +@msg every pixel matches the background: no image would be left 每个像素都与背景匹配:不会留下任何图像 +@msg an image of {w} × {h} pixels is too large to change {w} × {h} 像素的图像过大,无法更改 @msg the document has no artboards 文档没有画板 @msg tool (a tool id) is required 需要 tool (工具 id) @msg unknown tool `{t}` 未知工具 `{t}` @@ -4713,6 +4789,8 @@ imageTrace Outline 轮廓 @msg invalid object id {value}: expected a non-negative integer 无效的对象 id {value}:应为非负整数 @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}` 中索引 {index} 处的项为 {value},不是非负整数对象 id @msg no such object id {value} 没有 id 为 {value} 的对象 +@msg id {value} is a ruler guide, not an object id {value} 是参考线,不是对象 +@msg a ruler guide goes only directly in a layer or sublayer 参考线只能直接位于图层或子图层中 @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} 是图层,不是对象;请使用 layer.move 移动图层 @msg automation filesystem access is not granted: read authority is absent: {path} 未授予自动化文件系统访问权限:缺少读取权限:{path} @@ -4742,7 +4820,13 @@ imageTrace Outline 轮廓 @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC 或 HEIF 文件包含无法读取的图像类型 @msg HEIC and HEIF images can't be opened in this build 此版本无法打开 HEIC 和 HEIF 图像 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 图像过大,无法读取 ({_1} × {_2} 像素) -@msg zipped 32-bit PSD image data with prediction can't be read 无法读取带预测的 ZIP 压缩 32 位 PSD 图像数据 +@msg zipped 1-bit PSD image data with prediction can't be read 无法读取带预测的 ZIP 压缩 1 位 PSD 图像数据 +@msg the PSD file's layer data uses an unknown compression ({m}) PSD 文件的图层数据使用了未知的压缩方式 ({m}) +@msg the PSD file's layer records are damaged PSD 文件的图层记录已损坏 +@msg the PSD file's layer groups are nested too deeply PSD 文件的图层组嵌套过深 +@msg a layer of the PSD file is too large to read PSD 文件的某个图层过大,无法读取 +@msg the PSD file's layers take more memory to read than allowed 读取 PSD 文件的图层所需内存超过允许值 +@msg the layers can't be read ({e}): the file opened as its merged image 无法读取图层 ({e}):文件已作为合并图像打开 @msg {depth}-bit PSD files in this colour mode can't be read 无法读取此颜色模式下的 {depth} 位 PSD 文件 @msg the PSD file is cut short PSD 文件不完整 @msg the PSD file's header is damaged PSD 文件头已损坏 @@ -4807,7 +4891,7 @@ imageTrace Outline 轮廓 @msg span must be "object" or "selection", got {v} span 必须是 "object" 或 "selection",实际为 {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 span: "selection" 放置线性或径向渐变,而不是任意形状渐变 +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" 放置线性、径向、圆锥或菱形渐变,而不是任意形状渐变 @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" 自行放置渐变:请省略 `start` 和 `end` (它们已按文档坐标放置渐变) @msg Batch: {count} processed 批处理:已处理 {count} 个 @msg Batch: {count} processed, {failed} failed 批处理:已处理 {count} 个,失败 {failed} 个 @@ -5220,6 +5304,13 @@ axis Both 两者 Dock Panel 停放面板 Dock to Top 停放到顶部 Dock to Bottom 停放到底部 + Control Bar Options 控制栏选项 + Tool Options 工具选项 + Object Options 对象选项 + Image Options 图像选项 + Vertical Alignment 垂直对齐 + Align and Distribute 对齐和分布 + Document Options 文档选项 Dock Control Bar 停放控制栏 Drag to float the toolbar 拖动以浮动工具栏 Drag to the window's left or right edge to dock 拖到窗口左边缘或右边缘以停放 @@ -5576,6 +5667,11 @@ lighting Light 光源 Softness 柔和度 Ambient Light 环境光 Light behind the object 光源位于对象后方 + Shadows 阴影 + Distance from Object 与对象的距离 + Shadow Bounds 阴影边界 + Behind Object 对象后方 + Below Object 对象下方 3D Lighting Preset 3D 光照预设 Standard 标准 Diffuse 漫射 @@ -5788,6 +5884,7 @@ lighting Light 光源 Ruby 注音 Geometric Guides 几何参考线 Geometric Patterns 几何图案 + Grit Textures 颗粒纹理 Ease In 缓入 Ease Out 缓出 Ease In Out 缓入缓出 @@ -5847,6 +5944,8 @@ axis Y Axis Y 轴 Version: {version} 版本:{version} Install “{name}” in place of the plug-in with the same ID? 要安装“{name}”来替换具有相同 ID 的插件吗? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此文件不是之前以此 ID 安装的插件。它将获得为该 ID 保存的设置和缓存。 + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 自动化请求安装此增效工具。要安装它,请自行选择“对象 › 增效工具 › 安装增效工具…”。 +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 自动化请求安装此增效工具。要安装它,请自行选择“对象 › 增效工具 › 安装增效工具…”。 @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees “{name}”与 ID 为 {_1} 的插件是不同的模块,并会获得为其保存的设置和缓存:请在用户同意后使用 `replace: true` 安装 File SHA-256: {hash} 文件 SHA-256:{hash} Read the objects it is given 读取交给它的对象 @@ -5892,6 +5991,11 @@ axis Y Axis Y 轴 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 内存预算(对象 {_1} 需要 {size} 字节的输入,剩余 {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) 对象预算(超过 {MAX_OBJECTS} 个只读对象) +@msg instruction budget 指令预算 +@msg time budget 时间预算 +@msg memory budget (the selection is too large to hand over) 内存预算(所选内容太大,无法传递) +@msg output size ({what} is {len} bytes, limit {max}) 输出大小({what} 为 {len} 字节,上限 {max}) +@msg the plug-in's grant can't be removed from the plug-in store 无法从增效工具存储中移除该增效工具的授权 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 权限 `{shown}` 保留给以后的增效工具 API;此主机不授予该权限 @msg unknown permission `{shown}` 未知权限 `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}”需要权限 {asked}:需要有人在桌面应用中批准,或在以 --allow-plugin-grants 启动的会话中传入 `grant` @@ -5904,6 +6008,12 @@ axis Y Axis Y 轴 @msg command {name}: `label` must be 1-64 printable characters 命令 {name}:`label` 必须是 1-64 个可打印字符 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 命令 {name}:请使用由 a-z 0-9 _ 组成、以字母开头的 1-{MAX_COMMAND_ID} 个字符的 ID @msg command {name}: {e} 命令 {name}:{e} +@msg manifest: {e} 清单:{e} +@msg manifest: {e} at line {line} column {column} 清单:{e}(第 {line} 行,第 {column} 列) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` 必须是命令列表,每个命令都有 `id` 和 `label` +@msg command {name} must be an object with an `id` and a `label` 命令 {name} 必须是包含 `id` 和 `label` 的对象 +@msg missing field `{key}` 缺少字段 `{key}` +@msg duplicate field `{key}` 字段 `{key}` 重复 @msg only a filter or a live effect declares `commands` 只有滤镜或实时效果才能声明 `commands` @msg “{name}” › {label}: {e} “{name}” › {label}:{e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed 模块的 SHA-256 与 `hash` 给出的不符:未安装任何内容 @@ -5928,6 +6038,16 @@ axis Y Axis Y 轴 @msg message must be text message 必须是文本 @msg allowContinue must be true or false allowContinue 必须是 true 或 false @msg Batch cannot play an action with a stop 批处理无法播放含有停止的动作 + Insert Menu Item… 插入菜单项… + Insert Menu Item 插入菜单项 + Menu Item: 菜单项: + No menu item matches. 没有匹配的菜单项。 + Several menu items match. Choose one from the list. 有多个菜单项匹配。请从列表中选择一个。 + Items that open a dialog, and File, Window and Help menu items, are not listed. 未列出会打开对话框的项目,以及“文件”“窗口”和“帮助”菜单中的项目。 +@msg command must be text command 必须是文本 +@msg no menu item that can be inserted runs this command 没有可插入的菜单项运行此命令 +@msg the action already has 10,000 steps 该动作已有 10,000 个步骤 +@msg the action set would be larger than 8 MiB 动作组将超过 8 MiB Playback Options 播放选项 Accelerated 加速 Step by Step 逐步 @@ -5966,6 +6086,12 @@ axis Y Axis Y 轴 Crosshair 准星 Checkpoint 检查点 Inventory Icons 物品栏图标 + Skill Icons 技能图标 + Attack 攻击 + Defend 防御 + Heal 治疗 + Buff 增益 + Ult 终极技 Sword 剑 Shield 盾 Potion 药水 @@ -6030,7 +6156,23 @@ axis Y Axis Y 轴 Dash Trail 虚线轨迹 Speed Line 速度线 Game Trails 游戏轨迹 + Energy Beams 能量光束 + Laser Bolt 激光弹 + Plasma Arc 等离子弧 + Charge Wave 充能波 + Spark Trail 火花尾迹 Calligraphic Nibs 书法笔尖 + Bristle Brushes 鬃毛画笔集 + Fine Liner 细勾线笔 + Pointed Flat 尖头平笔 + Stubby Round 短圆笔 + Dry Scrub 干擦 + Soft Dome 柔和圆顶 + Filbert 榛形笔 + Angled Round 斜圆笔 + Angled Flat 斜平笔 + Fan Blender 混色扇形笔 + Grass Fan 画草扇形笔 Pattern Borders 图案边框 Scatter Shapes 散布形状 Save Brush Library… 保存画笔库… @@ -6230,9 +6372,12 @@ anchor Points: 点: @msg {label} must be a number {label} 必须是数字 @msg {label} must be a number of at least 0.1 {label} 必须是至少 0.1 的数字 Advanced Character Formats 高级字符格式 + Basic Paragraph Formats 基本段落格式 + Composition 排版 Horizontal Scale 水平缩放 Vertical Scale 垂直缩放 @msg {label} must be a number from {min} to {max} {label} 必须是 {min} 到 {max} 之间的数字 +@msg {label} must be a whole number from {min} to {max} {label} 必须是 {min} 到 {max} 之间的整数 Character Color 字符颜色 OpenType Features OpenType 特性 Stylistic Sets 风格集 @@ -6240,6 +6385,10 @@ anchor Points: 点: @msg features lists at most {max} tags features 最多包含 {max} 个标签 @msg unknown OpenType feature `{t}` 未知的 OpenType 特性 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必须是大于 0 且不超过 {max} 的数字 +@msg {label} must be at most {max} characters {label} 最多 {max} 个字符 +@msg {label} must be one character {label} 必须是一个字符 +@msg at most {max} tab stops 最多 {max} 个制表位 +@msg unknown align `{other}` 未知的对齐方式 `{other}` @msg no character style `{name}` 找不到字符样式 `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6401,6 +6550,12 @@ breakText Glyphs 字形 Delete the selected brushes? 删除选中的画笔吗? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有描边使用了其中一个或多个画笔。要从这些描边移除画笔并删除画笔吗? Remove Strokes 移除描边 + Place Brush Art 置入画笔图稿 + Replace Brush Art 替换画笔图稿 + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有描边使用了此画笔。要将新图稿应用到这些描边,还是保留描边不变并添加一个使用新图稿的画笔副本? + Apply to Strokes 应用于描边 + Leave Strokes 保留描边 +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` 没有图稿 (只有散布画笔、艺术画笔和图案画笔有图稿) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 按网格排列… @@ -6596,6 +6751,11 @@ breakText Glyphs 字形 @msg only an exporter or an importer declares `extensions` 只有导出或导入增效工具才声明 `extensions` @msg an importer always gets an import's budget: leave `budget` out 导入增效工具始终获得导入的预算:请省略 `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info 复制故障排除信息 +@msg Copied the troubleshooting info 已复制故障排除信息 +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report 上次的 VectorCraft 会话在关闭前停止了响应。帮助 › 复制故障排除信息 可复制用于错误报告的详细信息 + # Safe Mode Safe Mode… 安全模式… Safe Mode 安全模式 @@ -6616,6 +6776,8 @@ breakText Glyphs 字形 # Align to Pixel Grid Align to Pixel Grid 对齐像素网格 + Align New Objects to Pixel Grid 将新对象对齐像素网格 + Not Aligned to Pixel Grid 未对齐像素网格 @msg only paths and compound paths can be aligned to the pixel grid 只有路径和复合路径可以对齐像素网格 @msg side is left or right, not `{s}` side 应为 left 或 right,而不是 `{s}` Edit Custom Dictionary 编辑自定义词典 @@ -6643,8 +6805,33 @@ breakText Glyphs 字形 @plural {n} line cut|{n} lines cut 已截断 {n} 行 @msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必须是控制台保留的行号,且 `first` 不能在 `last` 之后 +# Learn panel + Learn 学习 + Explore tutorials 浏览教程 + For you 为你推荐 + Skills 技能 + Get started 入门 + Quick skill guide 快速技能指南 + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. 针对基本工具的简短实操教程,按技能分组。选择一项技能即可查看其教程。 + List Tutorials 列出教程 + Show Tutorial 显示教程 +@msg missing `tutorial` (see learn.list) 缺少 `tutorial` (请参阅 learn.list) +@msg unknown tutorial `{id}` (see learn.list) 未知教程 `{id}` (请参阅 learn.list) + # Deferred plug-in effects Refresh Deferred Effects 刷新延迟的效果 Deferred Effects 延迟的效果 @msg no plug-in effect is deferred 没有延迟的增效工具效果 @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 打开时延迟了 {n} 个增效工具效果。效果 › 刷新延迟的效果可运行它们。 + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools 切割工具 + Stencil Bridges… 镂空版连接桥… + Stencil Bridges 镂空版连接桥 + Shortest Crossing 最短跨越 + Direction 方向 +@msg The selected art has no islands to bridge 所选图稿没有需要连接的孤岛 +@msg No bridge of this width fits across the selected art 此宽度的连接桥无法放入所选图稿 +@msg Some islands could not be joined to the area around the art 部分孤岛无法连接到图稿周围的区域 +@msg `width` must be from {lo} to {hi} pt `width` 必须介于 {lo} 到 {hi} pt 之间 +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必须是 1 到 {MAX_BRIDGES_PER_ISLAND} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7cb218f99f..5b89ecda53 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -220,6 +220,7 @@ font-technology Variable 可變 Asset Export Settings 資產匯出設定 Assets 資產 Assign 指定 + Assign Profile 指定描述檔 Assign Profile… 指定描述檔… Assign: 指定: Attach to Active Plane 附加至作用中平面 @@ -662,6 +663,15 @@ font-technology Variable 可變 Created: 建立時間: Crop 裁切 Crop Image 裁切影像 + Image Tools 影像工具 + Remove Background… 移除背景… + Remove Background 移除背景 + Background 背景 + Edge Color 邊緣顏色 + Picked Colors 選取的顏色 + Corner Color 轉角顏色 + Contiguous 連續 + Each Channel 每個通道 Edit Path 編輯路徑 Mask 遮色片 Crop Marks 裁切標記 @@ -781,6 +791,14 @@ font-technology Variable 可變 Disable Auto Add/Delete 停用自動增加/刪除 Disable Opacity Mask 停用不透明度遮色片 Discard 捨棄 + Preserve 保留 + TIFF (Black & White) TIFF (黑白) + TIFF (8-bit Color) TIFF (8 位元色彩) + High Resolution 高解析度 + Medium Resolution 中解析度 + Low Resolution 低解析度 + Language Level 2 語言層級 2 + Language Level 3 語言層級 3 Discard Empty Type 捨棄空白文字 Discard Recovered Documents 捨棄已復原的文件 Discard White Overprint in Output 輸出時捨棄白色疊印 @@ -1108,6 +1126,8 @@ font-technology Variable 可變 Extrude & Bevel… 突出與斜角… 3D (Classic) 3D (經典) Extrude & Bevel (Classic)… 突出與斜角 (經典)… + Revolve (Classic)… 迴轉 (經典)… + Rotate (Classic)… 旋轉 (經典)… Surface 表面 Wireframe 線框 No Shading 無網底 @@ -1421,6 +1441,14 @@ file-filter Templates 範本 Hair Space 極細空格 Hand Tool 手形工具 Hand-Drawn 手繪 + Painted and Sketched 繪畫與素描 + Washed Blue 水洗藍 + Bristle Ochre 乾刷土黃 + Pastel Heather 粉彩淡紫 + Charcoal Shade 炭筆陰影 + Ink Contour 墨線輪廓 + Wet Ink 濕墨 + Fine Pen 細筆 Handles 控制把手 Hard Light 實光 Hard Mix 實色混合 @@ -1651,6 +1679,7 @@ file-filter Templates 範本 Include Linked Files 包含連結檔案 Include Metadata 包含中繼資料 Include non-printing layers 包含不列印的圖層 + Write pages longer than 200 in at full size in points 以實際尺寸(點)寫入長於 200 in 的頁面 Include SVG Code 包含 SVG 程式碼 Include Swatches for Tints 包含色調的色票 Inflate… 膨脹… @@ -1878,16 +1907,19 @@ file-filter Templates 範本 @msg `gradient` must be an object `gradient` 必須是物件 @msg `groupColors` must be an array `groupColors` 必須是陣列 @msg `mode` applies to freeform gradients `mode` 只適用於任意形狀漸層 +@msg a negative `aspect` applies to conic gradients 負的 `aspect` 只適用於圓錐漸層 +@msg `focal` applies to radial gradients `focal` 只適用於放射狀漸層 @msg `preserve` must be an object `preserve` 必須是物件 @msg `globalAdjust` must be an object `globalAdjust` 必須是物件 @msg `stops` must be an array `stops` 必須是陣列 +@msg `{key}` must be an array `{key}` 必須是陣列 @msg `{k}` must be [x, y] `{k}` 必須是 [x, y] @msg a gradient needs at least two stops 漸層至少需要兩個色標 @msg give both `start` and `end` [x, y] (or neither) 請同時提供 `start` 和 `end` [x, y] (或兩者都不提供) @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 unknown gradient kind `{k}` (linear, radial, freeform) 未知的漸層類型 `{k}` (linear、radial、freeform) +@msg unknown gradient kind `{k}` (linear, radial, conic, diamond, freeform) 未知的漸層類型 `{k}` (linear、radial、conic、diamond、freeform) @msg the art could not be sampled 無法對圖稿取樣 @msg the art is too light for any dots 圖稿太淡,無法產生任何網點 @msg the document has no symbols 文件中沒有符號 @@ -1979,6 +2011,7 @@ file-filter Templates 範本 @msg `{key}` must be `auto` or a language code such as `en` or `zh-hant` `{key}` 必須是 `auto` 或語言代碼,例如 `en` 或 `zh-hant` @msg `{key}` must be a #rrggbb colour `{key}` 必須是 #rrggbb 顏色 @msg `{key}` must be a string `{key}` 必須是字串 +@msg `{key}` must be a profile name or null `{key}` 必須是描述檔名稱或 null @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 between {min} and {max} (got {x}) `{key}` 必須介於 {min} 和 {max} 之間 (收到 {x}) @@ -2161,6 +2194,8 @@ file-filter Templates 範本 @msg the image's pixels don't match its size 影像的像素與其尺寸不符 @msg {bpp}-bit bitmaps can't be read 無法讀取 {bpp} 位元點陣圖 @msg not an EMF or WMF file 不是 EMF 或 WMF 檔案 +@msg not an HP-GL file 不是 HP-GL 檔案 +@msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` 必須是由 1 到 255 個 #rrggbb 格式顏色組成的陣列 @msg its layers use {_1}, which aren't read yet 其圖層使用了 {_1},目前尚無法讀取 @msg the EMF header is damaged EMF 檔頭已損毀 @msg damaged 已損毀 @@ -2177,6 +2212,7 @@ file-filter Templates 範本 @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 工作區域 {n} 的頁面為 {size},超過 PDF 的頁面上限 14,400 pt (200 in):它以 UserUnit {unit} 寫入,因此忽略 UserUnit 的應用程式會將其顯示為縮小相應倍數 @msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 工作區域 {n} 的頁面為 {size},超過 PDF 的頁面上限 14,400 pt (200 in):{label} 頁面不含 UserUnit,以點為單位寫入,遵守上限的應用程式會將頁面裁切為 200 in @msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 沒有 UserUnit,而長於 14,400 pt (200 in) 的頁面需要它來保持尺寸:檔案將以 PDF 1.6 寫入 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 沒有 UserUnit,而長於 14,400 pt (200 in) 的頁面需要它來保持在 PDF/A-2 的 14,400 單位頁面上限之內:檔案將以 PDF 1.6 寫入 @msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 工作區域 {n} 的頁面為 {size},對 PDF 3 至 14,400 單位的頁面邊長而言過長過窄:以 UserUnit {unit} 寫入,使短邊保持 3 單位以上,遵守上限的應用程式會把長邊裁到 14,400 單位 @msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 檔案的實數最大為 {max},而工作區域 {n} 的頁面長 {side} pt,需要更大的數:請選擇不含 PDF/X 標準的 PDF 1.6 或更新版本,或使用較小的工作區域 @msg page {0} does not exist (the PDF has {1}) 頁面 {0} 不存在 (此 PDF 有 {1} 頁) @@ -2364,6 +2400,14 @@ file-filter Templates 範本 @msg no such view 沒有這個檢視 @msg printing isn't available here 此處無法列印 @msg select an image 請選取影像 +@msg `background` must be edges, corners or colors `background` 必須為 edges、corners 或 colors +@msg `match` must be distance or channels `match` 必須為 distance 或 channels +@msg `{key}` must be from 0 to 100 `{key}` 必須介於 0 到 100 之間 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` 必須列出 1 到 16 種顏色,每種寫為十六進位(#rrggbb 或 #rgb)或 black、white、red、green、blue +@msg the linked image shows its preview: embed or relink it first 連結影像顯示的是預覽:請先嵌入或重新連結 +@msg a CMYK image has no transparency to set CMYK 影像沒有可設定的透明度 +@msg every pixel matches the background: no image would be left 每個像素都與背景相符:不會留下任何影像 +@msg an image of {w} × {h} pixels is too large to change {w} × {h} 像素的影像過大,無法變更 @msg the document has no artboards 文件沒有工作區域 @msg tool (a tool id) is required 需要 tool (工具 id) @msg unknown tool `{t}` 未知的工具 `{t}` @@ -2555,7 +2599,13 @@ file-filter Templates 範本 @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC 或 HEIF 檔案包含無法讀取的影像類型 @msg HEIC and HEIF images can't be opened in this build 此版本無法開啟 HEIC 和 HEIF 影像 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 影像過大,無法讀取 ({_1} × {_2} 像素) -@msg zipped 32-bit PSD image data with prediction can't be read 無法讀取使用預測的 ZIP 壓縮 32 位元 PSD 影像資料 +@msg zipped 1-bit PSD image data with prediction can't be read 無法讀取使用預測的 ZIP 壓縮 1 位元 PSD 影像資料 +@msg the PSD file's layer data uses an unknown compression ({m}) PSD 檔案的圖層資料使用了不明的壓縮方式 ({m}) +@msg the PSD file's layer records are damaged PSD 檔案的圖層記錄已損毀 +@msg the PSD file's layer groups are nested too deeply PSD 檔案的圖層群組巢狀過深 +@msg a layer of the PSD file is too large to read PSD 檔案的某個圖層過大,無法讀取 +@msg the PSD file's layers take more memory to read than allowed 讀取 PSD 檔案的圖層所需記憶體超過允許值 +@msg the layers can't be read ({e}): the file opened as its merged image 無法讀取圖層 ({e}):檔案已以合併影像開啟 @msg {depth}-bit PSD files in this colour mode can't be read 無法讀取此色彩模式的 {depth} 位元 PSD 檔案 @msg the PSD file is cut short PSD 檔案不完整 @msg the PSD file's header is damaged PSD 檔頭已損毀 @@ -2624,7 +2674,7 @@ file-filter Templates 範本 @msg span must be "object" or "selection", got {v} span 必須是 "object" 或 "selection",收到 {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 span: "selection" 放置線性或放射狀漸層,而非任意形狀漸層 +@msg span: "selection" places a linear, radial, conic or diamond gradient, not a freeform one span: "selection" 放置線性、放射狀、圓錐或菱形漸層,而非任意形狀漸層 @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" 會自行放置漸層:請不要提供 `start` 和 `end` (它們已依文件座標放置漸層) @msg Batch: {count} processed 批次:已處理 {count} 個 @msg Batch: {count} processed, {failed} failed 批次:已處理 {count} 個,失敗 {failed} 個 @@ -3304,12 +3354,23 @@ file-filter Templates 範本 Open… 開啟… Optical 視覺 Optical Margin Alignment 視覺邊界對齊 + Dynamic Text 動態文字 + Dynamic Text Presets 動態文字預設集 + Arch 拱形 +@msg select point type or type on a path 請選取點狀文字或路徑文字 +@msg type on a path in a thread cannot use Dynamic Text: {frames} 串連文字中的路徑文字無法使用動態文字:{frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} 開放路徑或複合路徑上的路徑文字無法在頂端或底端置中:{open} +@msg type on a path with no length or no height cannot be centered: {flat} 路徑沒有長度或沒有高度時,其路徑文字無法置中:{flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} 串連文字中的路徑文字無法在頂端或底端置中:{frames} +@msg select type on a closed path 請選取封閉路徑上的路徑文字 Optimize for fast web view 最佳化以便快速網頁檢視 Optimized 最佳化 Options 選項 Options for Selection… 選取範圍的選項… Options: 選項: Options… 選項… + Organic Fades 自然漸隱 + Holographic 全像 or more spaces with a tab 個以上的空格取代為定位字元 Order: 順序: Ordinals 序數字 @@ -3504,6 +3565,7 @@ diagnostics ui 介面 Presets: 預設集: Press 按下 Preview 預覽 + Preview: 預覽: Preview All Layers 預覽所有圖層 Preview in Browser 在瀏覽器中預覽 Preview in Browser needs the desktop app (the web downloads files instead) 在瀏覽器中預覽需要桌面版應用程式 (網頁版會改為下載檔案) @@ -3587,6 +3649,8 @@ digits Malayalam 馬來亞拉姆數字 Radial 放射狀 Radial Glows 放射狀光暈 Radial Gradient 放射狀漸層 + Conic Gradient 圓錐漸層 + Diamond Gradient 菱形漸層 Radius 1 半徑 1 Radius 2 半徑 2 Radius1 半徑1 @@ -3599,6 +3663,8 @@ digits Malayalam 馬來亞拉姆數字 Range: 範圍: Raster Effects 點陣效果 Raster File Format: 點陣檔案格式: + Include Placed Images 包含置入的影像 + Include Fill Hatches 包含填色的圖案填充 Raster Sample Size: 點陣取樣大小: Raster/Vector Balance: 點陣/向量平衡: Rasterize 點陣化 @@ -3780,6 +3846,10 @@ digits Malayalam 馬來亞拉姆數字 Replace Font 取代字體 Replace it with another file, or ignore it: its images keep showing the preview saved with the document. 以其他檔案取代,或忽略:其影像會繼續顯示隨文件儲存的預覽。 Replace Spine 取代脊線 + Create Spine 建立脊線 + Create Spine: 建立脊線: + Always 一律 + Never 永不 Replace Symbol 取代符號 Reset Transformation 重設變形 Replace With Font 取代為字體 @@ -3859,6 +3929,9 @@ digits Malayalam 馬來亞拉姆數字 Rise… 上升… Roman Baseline 羅馬基線 Roman Hanging Punctuation 羅馬懸掛標點 + Korean Line Break Anywhere 韓文任意位置換行 + East Asian Composition Settings 東亞排版設定 + Korean Composition Settings 韓文排版設定 Rotate 旋轉 Rotate 90° CW 順時針旋轉 90° Rotate Tool 旋轉工具 @@ -4142,6 +4215,15 @@ digits Malayalam 馬來亞拉姆數字 Stun Pulse 暈眩 Stealth Fade 隱身 Shield Buff 護盾 + Textures 紋理 + Fine Grain 細顆粒 + Canvas Weave 帆布紋 + Burlap Sack 麻布袋 + Cracked Glaze 裂紋釉 + Mosaic Floor 馬賽克地面 + Quilted Squares 絎縫方格 + Leaded Glass 鉛條玻璃 + Damp Paper 濕紙 Shape 形狀 Shape Builder 形狀建立 Shape Builder Regions 形狀建立區域 @@ -4204,6 +4286,7 @@ digits Malayalam 馬來亞拉姆數字 Show Modified 顯示已修改 Show Note 顯示註解 Show Options 顯示選項 + Show Recent Colors 顯示最近使用的顏色 Show Original Path 顯示原始路徑 Open this dialog with these settings next time 下次以這些設定開啟此對話方塊 Auto-Simplify 自動簡化 @@ -4508,6 +4591,8 @@ digits Malayalam 馬來亞拉姆數字 Scale at Center 從中心縮放 Up/Down: 上/下: Left/Right: 左/右: + Tate-chu-yoko Up/Down 縱中橫上/下 + Tate-chu-yoko Left/Right 縱中橫左/右 Temperature 色溫 Temperature/Tint… 色溫/色調… Template 範本 @@ -4578,6 +4663,8 @@ digits Malayalam 馬來亞拉姆數字 Toolbar: Single/Double Column 工具列:單欄/雙欄 Toolbar: Add Tool 工具列:新增工具 Toolbar: Remove Tool 工具列:移除工具 + Add Tool… 新增工具… + Remove Tool 移除工具 Toolbar: Reset 工具列:重設 Toolbars 工具列 Tools 工具 @@ -4652,6 +4739,8 @@ digits Malayalam 馬來亞拉姆數字 Type on a Path 路徑文字 Type on a Path Options 路徑文字選項 Type on a Path Options… 路徑文字選項… + Center on Top 在頂端置中 + Center on Bottom 在底端置中 Type on a Path Tool 路徑文字工具 Type Orientation 文字方向 Type stays text, and every stroke is a line with its lineweight and dashes. 文字維持為文字,每個筆畫都是帶有線寬與虛線的線條。 @@ -4862,6 +4951,7 @@ digits Malayalam 馬來亞拉姆數字 Windows Windows Working CMYK 使用中的 CMYK Working CMYK (don't tag) 工作 CMYK (不加標記) + Working RGB (don't tag) 工作 RGB (不加標記) Workspace 工作區 Workspace {i} 工作區 {i} Wrinkle Tool 皺摺工具 @@ -5043,6 +5133,13 @@ axis Both 兩者 Dock Panel 停駐面板 Dock to Top 停駐到頂部 Dock to Bottom 停駐到底部 + Control Bar Options 控制列選項 + Tool Options 工具選項 + Object Options 物件選項 + Image Options 影像選項 + Vertical Alignment 垂直對齊 + Align and Distribute 對齊與均分 + Document Options 文件選項 Dock Control Bar 停駐控制列 Drag to float the toolbar 拖曳以浮動工具列 Drag to the window's left or right edge to dock 拖曳到視窗左側或右側邊緣以停駐 @@ -5399,6 +5496,11 @@ lighting Light 光源 Softness 柔和度 Ambient Light 環境光 Light behind the object 光源位於物件後方 + Shadows 陰影 + Distance from Object 與物件的距離 + Shadow Bounds 陰影邊界 + Behind Object 物件後方 + Below Object 物件下方 3D Lighting Preset 3D 光照預設 Standard 標準 Diffuse 漫射 @@ -5558,6 +5660,8 @@ lighting Light 光源 @msg invalid object id {value}: expected a non-negative integer 無效的物件 id {value}:應為非負整數 @msg `{key}` entry {index} is {value}, not a non-negative integer object id `{key}` 中索引 {index} 處的項目為 {value},不是非負整數物件 id @msg no such object id {value} 沒有 id 為 {value} 的物件 +@msg id {value} is a ruler guide, not an object id {value} 是參考線,不是物件 +@msg a ruler guide goes only directly in a layer or sublayer 參考線只能直接位於圖層或子圖層中 @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} 是圖層,不是物件;請使用 layer.move 移動圖層 Move Anchor Point 移動錨點 @@ -5584,6 +5688,7 @@ lighting Light 光源 Ruby 注音 Geometric Guides 幾何參考線 Geometric Patterns 幾何圖樣 + Grit Textures 顆粒紋理 Ease In 緩入 Ease Out 緩出 Ease In Out 緩入緩出 @@ -5644,6 +5749,8 @@ axis Y Axis Y 軸 Version: {version} 版本:{version} Install “{name}” in place of the plug-in with the same ID? 要安裝「{name}」來取代具有相同 ID 的增效模組嗎? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此檔案不是先前以此 ID 安裝的增效模組。它會取得為該 ID 保存的設定和快取。 + Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 自動化要求安裝此增效模組。若要安裝,請自行選擇「物件 › 增效模組 › 安裝增效模組…」。 +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. 自動化要求安裝此增效模組。若要安裝,請自行選擇「物件 › 增效模組 › 安裝增效模組…」。 @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees 「{name}」與 ID 為 {_1} 的增效模組是不同的模組,並會取得為其保存的設定和快取:請在使用者同意後以 `replace: true` 安裝 File SHA-256: {hash} 檔案 SHA-256:{hash} Read the objects it is given 讀取交給它的物件 @@ -5689,6 +5796,11 @@ axis Y Axis Y 軸 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 記憶體預算(物件 {_1} 需要 {size} 位元組的輸入,剩餘 {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) 物件預算(超過 {MAX_OBJECTS} 個唯讀物件) +@msg instruction budget 指令預算 +@msg time budget 時間預算 +@msg memory budget (the selection is too large to hand over) 記憶體預算(所選內容太大,無法傳遞) +@msg output size ({what} is {len} bytes, limit {max}) 輸出大小({what} 為 {len} 位元組,上限 {max}) +@msg the plug-in's grant can't be removed from the plug-in store 無法從增效模組存放區移除該增效模組的授權 @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 權限 `{shown}` 保留給日後的增效模組 API;此主機不授予該權限 @msg unknown permission `{shown}` 未知權限 `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants 「{name}」需要權限 {asked}:需要有人在桌面應用程式中核准,或在以 --allow-plugin-grants 啟動的工作階段中傳入 `grant` @@ -5701,6 +5813,12 @@ axis Y Axis Y 軸 @msg command {name}: `label` must be 1-64 printable characters 指令 {name}:`label` 必須是 1-64 個可列印字元 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 指令 {name}:請使用由 a-z 0-9 _ 組成、以字母開頭的 1-{MAX_COMMAND_ID} 個字元的 ID @msg command {name}: {e} 指令 {name}:{e} +@msg manifest: {e} 資訊清單:{e} +@msg manifest: {e} at line {line} column {column} 資訊清單:{e}(第 {line} 行,第 {column} 欄) +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` 必須是指令清單,每個指令都有 `id` 和 `label` +@msg command {name} must be an object with an `id` and a `label` 指令 {name} 必須是包含 `id` 和 `label` 的物件 +@msg missing field `{key}` 找不到欄位 `{key}` +@msg duplicate field `{key}` 欄位 `{key}` 重複 @msg only a filter or a live effect declares `commands` 只有濾鏡或即時效果才能宣告 `commands` @msg “{name}” › {label}: {e} 「{name}」 › {label}:{e} @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed 模組的 SHA-256 與 `hash` 提供的不符:未安裝任何內容 @@ -5725,6 +5843,16 @@ axis Y Axis Y 軸 @msg message must be text message 必須是文字 @msg allowContinue must be true or false allowContinue 必須是 true 或 false @msg Batch cannot play an action with a stop 批次無法播放含有停止的動作 + Insert Menu Item… 插入選單項目… + Insert Menu Item 插入選單項目 + Menu Item: 選單項目: + No menu item matches. 沒有相符的選單項目。 + Several menu items match. Choose one from the list. 有多個選單項目相符。請從清單中選擇一個。 + Items that open a dialog, and File, Window and Help menu items, are not listed. 未列出會開啟對話框的項目,以及「檔案」、「視窗」和「說明」選單中的項目。 +@msg command must be text command 必須是文字 +@msg no menu item that can be inserted runs this command 沒有可插入的選單項目執行此指令 +@msg the action already has 10,000 steps 這個動作已有 10,000 個步驟 +@msg the action set would be larger than 8 MiB 動作組會超過 8 MiB Playback Options 播放選項 Accelerated 加速 Step by Step 逐步 @@ -5763,6 +5891,12 @@ axis Y Axis Y 軸 Crosshair 準星 Checkpoint 檢查點 Inventory Icons 物品欄圖示 + Skill Icons 技能圖示 + Attack 攻擊 + Defend 防禦 + Heal 治療 + Buff 增益 + Ult 必殺 Sword 劍 Shield 盾 Potion 藥水 @@ -5827,7 +5961,23 @@ axis Y Axis Y 軸 Dash Trail 虛線軌跡 Speed Line 速度線 Game Trails 遊戲軌跡 + Energy Beams 能量光束 + Laser Bolt 雷射彈 + Plasma Arc 電漿弧 + Charge Wave 充能波 + Spark Trail 火花尾跡 Calligraphic Nibs 書法筆尖 + Bristle Brushes 鬃毛筆刷集 + Fine Liner 細勾線筆 + Pointed Flat 尖頭平筆 + Stubby Round 短圓筆 + Dry Scrub 乾擦 + Soft Dome 柔和圓頂 + Filbert 榛形筆 + Angled Round 斜圓筆 + Angled Flat 斜平筆 + Fan Blender 混色扇形筆 + Grass Fan 畫草扇形筆 Pattern Borders 圖樣邊框 Scatter Shapes 散佈形狀 Save Brush Library… 儲存筆刷資料庫… @@ -6027,9 +6177,12 @@ anchor Points: 點: @msg {label} must be a number {label} 必須是數字 @msg {label} must be a number of at least 0.1 {label} 必須是至少 0.1 的數字 Advanced Character Formats 進階字元格式 + Basic Paragraph Formats 基本段落格式 + Composition 排版 Horizontal Scale 水平縮放 Vertical Scale 垂直縮放 @msg {label} must be a number from {min} to {max} {label} 必須是 {min} 到 {max} 之間的數字 +@msg {label} must be a whole number from {min} to {max} {label} 必須是 {min} 到 {max} 之間的整數 Character Color 字元顏色 OpenType Features OpenType 功能 Stylistic Sets 風格集 @@ -6037,6 +6190,10 @@ anchor Points: 點: @msg features lists at most {max} tags features 最多包含 {max} 個標籤 @msg unknown OpenType feature `{t}` 未知的 OpenType 功能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必須是大於 0 且不超過 {max} 的數字 +@msg {label} must be at most {max} characters {label} 最多 {max} 個字元 +@msg {label} must be one character {label} 必須是一個字元 +@msg at most {max} tab stops 最多 {max} 個定位點 +@msg unknown align `{other}` 未知的對齊方式 `{other}` @msg no character style `{name}` 找不到字元樣式 `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). @@ -6199,6 +6356,12 @@ breakText Glyphs 字符 Delete the selected brushes? 要刪除選取的筆刷嗎? Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? 有筆畫使用了其中一個或多個筆刷。要從這些筆畫移除筆刷並刪除筆刷嗎? Remove Strokes 移除筆畫 + Place Brush Art 置入筆刷圖稿 + Replace Brush Art 取代筆刷圖稿 + Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有筆畫使用了此筆刷。要將新圖稿套用到這些筆畫,還是保留筆畫不變並加入一個使用新圖稿的筆刷複本? + Apply to Strokes 套用至筆畫 + Leave Strokes 保留筆畫 +@msg `{name}` has no art (only scatter, art and pattern brushes do) `{name}` 沒有圖稿 (只有散佈筆刷、藝術筆刷和圖樣筆刷有圖稿) # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools 排列工具 Arrange in Grid… 依格狀排列… @@ -6394,6 +6557,11 @@ breakText Glyphs 字符 @msg only an exporter or an importer declares `extensions` 只有匯出或匯入增效模組才宣告 `extensions` @msg an importer always gets an import's budget: leave `budget` out 匯入增效模組一律取得匯入的預算:請勿指定 `budget` +# Copy Troubleshooting Info + Copy Troubleshooting Info 複製疑難排解資訊 +@msg Copied the troubleshooting info 已複製疑難排解資訊 +@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report 上次的 VectorCraft 工作階段在關閉前停止回應。說明 › 複製疑難排解資訊 可複製用於錯誤回報的詳細資料 + # Safe Mode Safe Mode… 安全模式… Safe Mode 安全模式 @@ -6414,6 +6582,8 @@ breakText Glyphs 字符 # Align to Pixel Grid Align to Pixel Grid 對齊像素格點 + Align New Objects to Pixel Grid 將新物件對齊像素格點 + Not Aligned to Pixel Grid 未對齊像素格點 @msg only paths and compound paths can be aligned to the pixel grid 只有路徑和複合路徑可以對齊像素格點 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` Edit Custom Dictionary 編輯自訂字典 @@ -6441,8 +6611,33 @@ breakText Glyphs 字符 @plural {n} line cut|{n} lines cut 已截斷 {n} 行 @msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必須是主控台保留的行號,且 `first` 不能在 `last` 之後 +# Learn panel + Learn 學習 + Explore tutorials 瀏覽教學課程 + For you 為你推薦 + Skills 技能 + Get started 入門 + Quick skill guide 快速技能指南 + Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials. 針對基本工具的簡短實作教學課程,依技能分組。選擇一項技能即可查看其教學課程。 + List Tutorials 列出教學課程 + Show Tutorial 顯示教學課程 +@msg missing `tutorial` (see learn.list) 未提供 `tutorial` (請參閱 learn.list) +@msg unknown tutorial `{id}` (see learn.list) 未知的教學課程 `{id}` (請參閱 learn.list) + # Deferred plug-in effects Refresh Deferred Effects 重新整理延後的效果 Deferred Effects 延後的效果 @msg no plug-in effect is deferred 沒有延後的增效模組效果 @msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 開啟時延後了 {n} 個增效模組效果。效果 › 重新整理延後的效果可執行它們。 + +# Cutting Tools add-on (Object › Plug-ins › Cutting Tools). + Cutting Tools 切割工具 + Stencil Bridges… 鏤空版連接橋… + Stencil Bridges 鏤空版連接橋 + Shortest Crossing 最短跨越 + Direction 方向 +@msg The selected art has no islands to bridge 所選圖稿沒有需要連接的孤島 +@msg No bridge of this width fits across the selected art 此寬度的連接橋無法放入所選圖稿 +@msg Some islands could not be joined to the area around the art 部分孤島無法連接到圖稿周圍的區域 +@msg `width` must be from {lo} to {hi} pt `width` 必須介於 {lo} 到 {hi} pt 之間 +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` 必須是介於 1 到 {MAX_BRIDGES_PER_ISLAND} 的整數 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 78eb6149d1..f521e45c22 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -89,6 +89,8 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-free-transform", include_bytes!("../../../assets/icons/dc-free-transform.svg")), ("dc-fx", include_bytes!("../../../assets/icons/dc-fx.svg")), ("dc-gamut", include_bytes!("../../../assets/icons/dc-gamut.svg")), + ("dc-grad-conic", include_bytes!("../../../assets/icons/dc-grad-conic.svg")), + ("dc-grad-diamond", include_bytes!("../../../assets/icons/dc-grad-diamond.svg")), ("dc-grad-freeform", include_bytes!("../../../assets/icons/dc-grad-freeform.svg")), ("dc-grad-linear", include_bytes!("../../../assets/icons/dc-grad-linear.svg")), ("dc-grad-radial", include_bytes!("../../../assets/icons/dc-grad-radial.svg")), @@ -195,6 +197,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("flip-vertical-2", include_bytes!("../../../assets/icons/flip-vertical-2.svg")), ("folder-open", include_bytes!("../../../assets/icons/folder-open.svg")), ("frame", include_bytes!("../../../assets/icons/frame.svg")), + ("graduation-cap", include_bytes!("../../../assets/icons/graduation-cap.svg")), ("grid-3x3", include_bytes!("../../../assets/icons/grid-3x3.svg")), ("group", include_bytes!("../../../assets/icons/group.svg")), ("hand", include_bytes!("../../../assets/icons/hand.svg")), diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index cc6f5d2262..dff4fa0dd2 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -30,7 +30,7 @@ pub use open::{ #[cfg(test)] pub(crate) use open::{open_file, opened_with_notes}; pub use save::{ask_format_options, ask_pdf_options, remember_active_artboard, remember_view, save, save_pdf}; -pub(crate) use save::{export_path, is_web, report_saved, target_path, write_named, write_reporting, write_to}; +pub(crate) use save::{export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to}; #[cfg(test)] pub(crate) use save::{report_write_error, saved_status}; @@ -80,6 +80,81 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// A file opened with a note about its page first and a note that its layers weren't read + /// second: the status bar names the layers note, counts both, and keeps both, the layers note + /// first, for its hover. A message about its linked files still replaces that message. Two + /// notes of what was left out keep the order the import gave them, and an open without notes + /// leaves the message and the notes an earlier open left. + #[test] + fn an_open_names_the_note_of_what_was_left_out_first() { + use vectorcraft_testkit::ai; + let (mut app, _) = app(); + let damaged = b"%AI12_CompressedData not zlib"; + let notes = notes_of; + let pdf = ai::pdf(damaged, "0 g 150 20 100 60 re f"); + let r = open_bytes(&mut app, "damaged.pdf", &pdf, None).unwrap(); + let [page, layers] = ¬es(&r)[..] else { panic!("two notes: {r}") }; + assert!(layers.contains("layers weren't read") && !page.contains("layers weren't read"), "{r}"); + assert_eq!(app.ui.status, opened_with_notes(2, layers)); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), vec![layers.clone(), page.clone()]))); + + // A message about its linked files replaces the open's message, as before. + app.session.prefs.update_links = "manually".into(); + let mut linked = r.clone(); + linked["modifiedLinks"] = json!([{ "ids": [1] }]); + opened(&mut app, &linked); + assert_eq!(app.ui.status, dialogs::missing_links::changed_on_disk_status(1)); + assert_eq!(app.ui.status_notes, Some((opened_with_notes(2, layers), vec![layers.clone(), page.clone()]))); + + let r = open_bytes(&mut app, "damaged.ai", &ai::ai(damaged, ai::page_pdf()), None).unwrap(); + let both = notes(&r); + assert_eq!(both.len(), 2, "{r}"); + assert_eq!(app.ui.status, opened_with_notes(2, &both[0])); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), both))); + + let r = open_document(&mut app, "page.pdf", &pdf, None, &json!({"editingData": false})).unwrap(); + let [only] = ¬es(&r)[..] else { panic!("one note: {r}") }; + assert_eq!(app.ui.status, opened_with_notes(1, only)); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), vec![only.clone()]))); + + let clean = br#""#; + open_bytes(&mut app, "damaged.pdf", &pdf, None).unwrap(); + let shown = (app.ui.status.clone(), app.ui.status_notes.clone()); + let r = open_bytes(&mut app, "clean.svg", clean, None).unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + assert_eq!((app.ui.status.clone(), app.ui.status_notes.clone()), shown); + } + + /// A save and an export with several notes: the status bar names the first, counts them, and + /// keeps every one of them, in the reply's order, for its hover. A save without notes keeps + /// none. + #[test] + fn a_save_and_an_export_keep_every_note_for_the_hover() { + let (mut app, _) = app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let r = app.run("file.save", json!({"path": "/out/a.svg", "compress": true})).unwrap(); + let notes = notes_of(&r); + assert_eq!(notes.len(), 2, "{r}"); + assert!(notes[0].starts_with("SVG keeps the artwork but not everything"), "{r}"); + assert_eq!(app.ui.status, saved_status("/out/a.svg", &r)); + assert!(app.ui.status.contains("with 2 notes"), "{}", app.ui.status); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes))); + + app.run("file.save", json!({"path": "/out/b.vectorcraft"})).unwrap(); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Saved /out/b.vectorcraft", &None)); + + // A PDF export of a knockout group and of type in a font that isn't installed. + app.run("text.create", json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("transparency.set", json!({"knockout": "on"})).unwrap(); + let r = export(&mut app, Some("pdf"), Some("/out/c.pdf".into()), &json!({})).unwrap(); + let notes = notes_of(&r); + assert_eq!(notes.len(), 2, "{r}"); + assert_eq!(app.ui.status, exported_with_notes("/out/c.pdf", notes.len(), ¬es[0])); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes))); + } + /// #1685: a save or an export that can't write its file says so in a dialog that names the /// file and the reason and stays until it is closed; the document stays modified and keeps /// the file it had. An agent's request only gets the error, and a message that arrives while diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 562dc0e00a..03e0196267 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -1,6 +1,7 @@ use super::save::{ - ask_before_losing, export_path, is_web, remember_active_artboard, report_saved, report_write_error, saved_status, target_path, - target_path_keeping, view_file, write_encoded, write_named, write_reporting, + ask_before_losing, ask_to_replace_files, checks_replaced, export_path, is_web, notes_of, remember_active_artboard, replaced_files, report_saved, + report_write_error, saved_status, show_with_notes, target_path, target_path_keeping, view_file, with_path, write_encoded, write_named, + write_reporting, }; use super::{EngineError, Progress, Value, VectorcraftApp, Writer, background, cancel, fileio, json, progress}; @@ -44,6 +45,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option std::sync::Arc::new(d), }; let doc = fileio::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, std::sync::Arc::new); + let uid = st.uid; let path = export_path(app, path, f)?; let mut again = params.clone(); if let Some(o) = again.as_object_mut() { @@ -68,11 +70,18 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option 1 { @@ -90,15 +99,21 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option = files.iter().filter_map(Value::as_str).map(str::to_string).collect(); + return Ok(ask_to_replace_files(app, uid, &files, &allowed_before, "file.exportAs", &rerun)); + } let what = match r["files"].as_array() { Some(files) => format!("{} files", files.len()), None => r["path"].as_str().unwrap_or_default().to_string(), }; - let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - app.status(match warnings.first() { + let warnings = notes_of(&r); + let status = match warnings.first() { Some(first) => exported_with_notes(&what, warnings.len(), first), None => format!("Exported {what}"), - }); + }; + show_with_notes(app, status, warnings); Ok(r) })?; if r.get("path").is_none() { @@ -115,7 +130,7 @@ pub(crate) fn exported_with_notes(what: &str, n: usize, first: &str) -> String { /// Run an engine command that returns `{dataBase64}` and write the bytes to a picked path /// (Export Selection, Save for Office Documents, Text Export Options and the presets dialogs' -/// Export…), reported with the first of the command's warnings ([`report_saved`]). +/// Export…), reported with the command's warnings ([`report_saved`]). pub fn save_command_output(app: &mut VectorcraftApp, id: &str, ext: &str, params: Value) -> Result { let (path, v) = run_to_file(app, id, ext, params)?; report_saved(app, &path, &v); @@ -241,8 +256,9 @@ pub(crate) fn open_original(app: &mut VectorcraftApp, path: &str) -> Result<(), /// File → Export for Screens with `document.exportForScreens` params: the files go into `folder`; /// without one the web downloads them (the ZIP, or each file) and the other frontends get them /// back as base64. With `openLocation`, the file manager shows the first file written. When an -/// export into a folder or a download has warnings, the status bar shows the first as -/// [`report_saved`] shows a save's notes: "Saved with n notes: …". +/// export into a folder or a download has warnings, the status bar shows them as [`report_saved`] +/// shows a save's notes: "Saved with n notes: …", and hovering the +/// message lists up to 30 of them, fewer when the window is small, with how many were left out. pub fn export_for_screens(app: &mut VectorcraftApp, params: Value) -> Result { export_files(app, "document.exportForScreens", params) } @@ -312,7 +328,7 @@ fn report_exported(app: &mut VectorcraftApp, r: Value, folder: &str, open_locati { status = format!("{status} ({e})"); } - app.status(status); + show_with_notes(app, status, notes_of(&r)); } else if let Some(download) = app.services.download.as_mut() { // A browser download has no folders: a file from a sub-folder (`2x/Logo@2x.png`) is named alone. let returned: Vec<(&str, &str)> = returned.iter().map(|(name, data)| (name.rsplit('/').next().unwrap_or(name), *data)).collect(); diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 50f13e695e..ae52b599b7 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -1,7 +1,7 @@ use vectorcraft_engine::cmd::plugin::InstallApproval; use vectorcraft_plugins::permissions; -use super::save::suggested; +use super::save::{notes_of, show_with_notes, suggested}; use super::{Dialog, FilePick, Format, Value, VectorcraftApp, dialogs, fileio, json}; /// Template extensions New from Template's open dialog lists first. @@ -137,15 +137,30 @@ pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: O } /// A document just opened (`r`: `document.open`'s result): the views follow, the status bar says -/// what didn't come in as it was, and missing links are asked about. +/// what didn't come in as it was, and missing links are asked about. The status bar names the +/// first of the notes that say reading the file left something out (the ones that make Save ask +/// before writing over it), else the first note, and keeps the notes in that order for its hover. pub(crate) fn opened(app: &mut VectorcraftApp, r: &Value) { app.sync_views(); - if let Some(w) = r["warnings"].as_array().filter(|w| !w.is_empty()) { - app.status(opened_with_notes(w.len(), w[0].as_str().unwrap_or_default())); + let notes = open_notes(app, r); + if let Some(first) = notes.first() { + let status = opened_with_notes(notes.len(), first); + show_with_notes(app, status, notes); } crate::dialogs::missing_links::after_open(app, r); } +/// The notes of the open `r`, those of what reading the file left out (its document's +/// `import_losses`) first, each group in the order the import gave them. +fn open_notes(app: &VectorcraftApp, r: &Value) -> Vec { + let notes = notes_of(r); + let index = r["index"].as_u64().and_then(|i| usize::try_from(i).ok()); + let losses = index.and_then(|i| app.session.documents().get(i)).map(|st| st.import_losses.as_slice()).unwrap_or_default(); + let (mut first, rest): (Vec, Vec) = notes.into_iter().partition(|n| losses.contains(n)); + first.extend(rest); + first +} + /// The status bar's line for a document opened with `n` notes, the first of them `first`. pub(crate) fn opened_with_notes(n: usize, first: &str) -> String { crate::i18n::msg_n(n as u64, "Opened with {n} note: {first}", "Opened with {n} notes: {first}", &[("first", first)]) @@ -200,16 +215,24 @@ fn permission_words(name: &str, commands: &[String]) -> String { /// place of another one with its id and get its settings and cache (`replace`); OK installs it if /// the module still has the hash the prompt showed, Cancel installs nothing → `{pending}` while it /// asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves. +/// Every question opens the approval dialog ([`dialogs::plugin::ask_install`]). When automation +/// asked ([`VectorcraftApp::automation_asked`]), the question has no OK that installs, its +/// `replace: true` doesn't skip asking about replacing, and the answer while it asks adds +/// `approval: "personMustStartInstall"`: the person starts Install Plug-in… to install it. /// Every text from the manifest is shown with its hidden characters escaped and its length capped /// ([`permissions::display_text`]). pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result { + let origin = if app.automation_asked() { dialogs::plugin::InstallOrigin::Automation } else { dialogs::plugin::InstallOrigin::Person }; + let automated = origin == dialogs::plugin::InstallOrigin::Automation; let given = |k: &str| module.get(k).map(|v| (k.to_string(), v.clone())); let source = Value::Object(["path", "dataBase64", "name"].into_iter().filter_map(given).collect()); let mut install = Value::Object(["path", "dataBase64", "name", "replace", "hash"].into_iter().filter_map(given).collect()); let info = app.run("plugin.inspect", source)?; let (needs_grant, heavy) = (info["needsApproval"] == true, info["budget"] == "heavy"); - // `replace: false` asks for no replacing, so only a module without `replace` asks. - let asks_replace = module.get("replace").is_none_or(Value::is_null) && info["needsReplace"] == true; + // `replace: false` asks for no replacing, so only a module without `replace` asks, or one whose + // `replace: true` automation gave. + let replace = module.get("replace").filter(|v| !v.is_null()); + let asks_replace = info["needsReplace"] == true && replace.is_none_or(|r| automated && *r == true); if !needs_grant && !heavy && !asks_replace { let r = app.run("plugin.install", install)?; report_installed(app, &r); @@ -230,13 +253,8 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result Result Result Option { /// File → Open… pub fn open_dialog(app: &mut VectorcraftApp) -> Result<(), String> { - if let Some(f) = app.services.open_async.as_mut() { - f(); + if crate::picks::open_async(app) { return Ok(()); } let path = diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index cfbdaaadba..d9d475e76f 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -264,7 +264,7 @@ pub fn save(app: &mut VectorcraftApp, mode: SaveMode, p: &Value, ask_options: bo if ask && matches!(mode, SaveMode::SaveAs | SaveMode::Copy) && matches!(first.format.id, "svg" | "svgz") { return ask_format_options(app, mode, first.format, &path); } - return write_plan(app, first); + return write_plan(app, first, (save_command(mode), with_path(p, &path))); } if is_web(app) && ask_options { return Ok(open_options(app, mode.command(), first.format, &first.name, true)); @@ -291,7 +291,42 @@ pub fn save(app: &mut VectorcraftApp, mode: SaveMode, p: &Value, ask_options: bo crate::dialogs::opened_by_panel(app); return r; } - write_plan(app, chosen) + write_plan(app, chosen, (save_command(mode), q)) +} + +/// `p` (an object, else none) with `path`. +pub(super) fn with_path(p: &Value, path: &str) -> Value { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + p["path"] = json!(path); + p +} + +/// The files among `paths` that a write to `path` replaces although the save panel asked only +/// about `path`: every other one that `exists` finds, but those in `known`. None without `exists`. +pub(super) fn replaced_files<'a>( + exists: Option<&crate::ExistsFn>, + path: &str, + known: &[String], + paths: impl IntoIterator, +) -> Vec { + let Some(exists) = exists else { return Vec::new() }; + paths.into_iter().filter(|p| *p != path && !known.iter().any(|k| k == p) && exists(p)).map(str::to_string).collect() +} + +/// The `exists` service with which a save or export checks the files it writes beside the one +/// picked ([`replaced_files`]), none on the web (downloads), and the files it replaces without +/// asking: those the OK of the question about them allowed while it runs that again. +pub(super) fn checks_replaced(app: &VectorcraftApp) -> (Option, Vec) { + (app.services.exists.clone().filter(|_| !is_web(app)), app.picks.replace_files_ok.clone()) +} + +/// Ask before a save or export of the document `doc` (its uid) replaces `files`, files that are +/// there beside the one picked in the save panel (a file per artboard, a linked image), which the +/// panel did not ask about. OK runs `command` with `params` again, replacing them and `allowed` +/// (those an earlier OK allowed); Cancel writes nothing → `{pending}`. +pub(super) fn ask_to_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[String], allowed: &[String], command: &str, params: &Value) -> Value { + dialogs::confirm::ask_replace_files(app, doc, files, allowed, command, params.clone()); + json!({ "pending": dialogs::confirm::REPLACE_FILES }) } /// The UI command that runs a save in `mode`. @@ -394,20 +429,35 @@ pub(super) fn view_file(app: &mut VectorcraftApp, path: &str) { } } -/// "Saved ", with the first of the result's warnings. +/// "Saved ", with the first of the result's warnings and how many there are; hovering the +/// message lists up to 30 of them, fewer when the window is small, with how many were left out +/// ([`show_with_notes`]). pub(crate) fn report_saved(app: &mut VectorcraftApp, path: &str, r: &Value) { - app.status(saved_status(path, r)); + show_with_notes(app, saved_status(path, r), notes_of(r)); +} + +/// The warnings of a reply `r`, in the reply's order (a save's notes start with what the format +/// loses). +pub(crate) fn notes_of(r: &Value) -> Vec { + r["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect() +} + +/// Show `status`, which names the first of `notes`, in the status bar and keep `notes` for its +/// hover ([`crate::state::UiState::status_notes`]). Without notes nothing is kept. +pub(crate) fn show_with_notes(app: &mut VectorcraftApp, status: String, notes: Vec) { + app.status(status); + app.ui.status_notes = (!notes.is_empty()).then(|| (app.ui.status.clone(), notes)); } /// [`report_saved`]'s message. pub(crate) fn saved_status(path: &str, r: &Value) -> String { - let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let warnings = notes_of(r); match warnings.first() { Some(first) => crate::i18n::msg_n( warnings.len() as u64, "Saved {path} with {n} note: {first}", "Saved {path} with {n} notes: {first}", - &[("path", path), ("first", first)], + &[("path", path), ("first", first.as_str())], ), None => format!("Saved {path}"), } @@ -418,7 +468,10 @@ pub(crate) fn saved_status(path: &str, r: &Value) -> String { /// ([`background`]): this returns `{path, background: true, status, format, warnings}` at once /// (`warnings`: what the format loses, then the save's notes on its params, such as an option the format /// doesn't read), and the document takes the file (and counts as saved, as of the snapshot) once it is written. -fn write_plan(app: &mut VectorcraftApp, plan: SavePlan) -> Result { +/// A file it writes beside the one at its path that is there already, and that the document's last +/// save did not write, is asked about before anything is written; `again` (a command and its params) +/// runs the save again once the question's OK allows it ([`ask_to_replace_files`]). +fn write_plan(app: &mut VectorcraftApp, plan: SavePlan, again: (&'static str, Value)) -> Result { let uid = app.session.active().ok_or("no document")?.uid; // Saves of one document finish in order. if app.background.busy_with(uid) { @@ -446,10 +499,19 @@ fn write_plan(app: &mut VectorcraftApp, plan: SavePlan) -> Result let done = job.clone(); // A native file streams into the file as it is encoded (desktop; not to a download). let stream = app.services.stream_shared.clone().filter(|_| job.streams() && !is_web(app)); + let (exists, allowed) = checks_replaced(app); + let known: Vec = allowed.iter().chain(app.picks.written_beside.get(&uid).into_iter().flatten()).cloned().collect(); let work = move |write: Writer| { match stream { Some(stream) => job.write_streamed(&mut |p, fill| stream(p, fill).map_err(EngineError::Other)), - None => job.write(|p, b| write(p, b).map_err(EngineError::Other)), + None => job.write_unless( + |paths| { + let path = job.plan().path.as_deref().unwrap_or_default(); + let replaced = replaced_files(exists.as_ref(), path, &known, paths.iter().copied()); + (!replaced.is_empty()).then(|| json!({ "replaces": replaced })) + }, + |p, b| write(p, b).map_err(EngineError::Other), + ), } .map_err(|e| e.to_string()) }; @@ -457,11 +519,20 @@ fn write_plan(app: &mut VectorcraftApp, plan: SavePlan) -> Result let then = move |app: &mut VectorcraftApp, r: Result| { // Not written: the document keeps its file, format and modified state, and the user is told. let r = r.inspect_err(|e| report_write_error(app, false, &failed, e))?; + // Nothing written either: asked first. + if let Some(files) = r.get("replaces").and_then(Value::as_array) { + let files: Vec = files.iter().filter_map(Value::as_str).map(str::to_string).collect(); + return Ok(ask_to_replace_files(app, uid, &files, &allowed, again.0, &again.1)); + } // The document may have closed meanwhile: the file is written all the same. done.complete(&mut app.session, uid); let path = r["path"].as_str().unwrap_or_default().to_string(); if retargets { note_recent(app, &path); + // The files written beside the document's file, which its next save replaces. + let beside = ["files", "linked"].iter().flat_map(|k| r[*k].as_array().into_iter().flatten()).filter_map(Value::as_str); + let beside: Vec = beside.filter(|p| *p != path).map(str::to_string).collect(); + app.picks.written_beside.insert(uid, beside); } report_saved(app, &path, &r); Ok(r) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 644125b545..be668e1e4f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -43,6 +43,7 @@ pub mod font_menu; mod frame_rate; mod free_transform; pub mod graphics; +pub mod hang_beacon; pub mod i18n; pub mod icon_data; pub mod icons; @@ -80,6 +81,7 @@ pub mod toolbar; mod tools_float; pub mod touch; pub mod trace_runs; +pub mod troubleshooting; mod ui_fonts; pub mod unsaved; pub mod updates_ui; @@ -120,7 +122,8 @@ pub use craft_ui::docking::Monitor as DockMonitor; #[cfg(test)] pub(crate) use services::browsable_url; pub use services::{ - DownloadFn, ExistsFn, FileFilter, FilePick, Inbox, NativeInputHook, OpenUrlFn, PickOpen, PickSave, ReadFn, RevealFn, Services, WriteFn, + DownloadFn, ExistsFn, FileFilter, FilePick, Inbox, NativeInputHook, OpenUrlFn, PickOpen, PickSave, PickedInbox, ReadFn, RevealFn, Services, + WriteFn, }; use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; pub(crate) use state::{InputFrame, take_frame_once}; @@ -133,6 +136,12 @@ pub struct VectorcraftApp { /// [`VectorcraftApp::sync_views`], which puts the views back with their documents after /// `document.move` reorders them (#5663). pub(crate) view_uids: Vec, + /// The thread that checks the system clipboard for `system_paste` instead + /// ([`Services::clipboard_probe`]). It is declared before `services` so that it is dropped + /// first: on X11 the last clipboard handle alive hands what the app copied to the clipboard + /// manager, and that must be the app's own handle in `services`, dropped on the UI thread + /// before the process exits. + clipboard_probe: Option, pub services: Services, pub canvas: CanvasCache, pub perf: Perf, @@ -222,6 +231,9 @@ pub struct VectorcraftApp { /// The graphics adapter the window renders with ("name (backend)"), as the host reports it: /// shown in Help › About and `ui.inspect` for GPU bug reports. `None` when unknown. pub graphics_adapter: Option, + /// Where [`Self::run`] marks each command for the desktop app's hang report: + /// [`hang_beacon::BEACON`], or a test's own. + pub(crate) beacon: &'static hang_beacon::Beacon, /// File → Place: picked files, the place cursor's thumbnails, the Control bar's image details. pub place: place::PlaceState, /// The Paste commands can paste from the system clipboard alone: it holds something to paste @@ -234,9 +246,6 @@ pub struct VectorcraftApp { pub(crate) clipboard_image_request: Option, /// When `system_paste` was last checked in line (app time, s; at most once per frame). system_paste_at: f64, - /// The thread that checks the system clipboard for `system_paste` instead - /// ([`Services::clipboard_probe`]). - clipboard_probe: Option, /// File dialogs shown off the UI thread and what runs again with their answers. pub(crate) picks: picks::Picks, /// The screen color sampler shown and not answered yet, and where its color goes. diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3d3f2a8c03..1698e06ed4 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -64,7 +64,9 @@ 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 use entries::{ + InsertableItem, MenuEntry, Row, context_entries, entry, insertable, insertable_items, menu_entries, pretty_shortcut, shown_shortcut, +}; pub(crate) use invoke::graph_dialog; #[cfg(test)] pub(crate) use invoke::with_held_keys; @@ -75,7 +77,7 @@ pub(crate) use labels::lists_plugin; use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; pub use run::{check_params, run_ui_command}; -pub(crate) use run::{normalize_panel, opt_bool}; +pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 815a00d6f9..42ad7b6555 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -127,6 +127,79 @@ pub fn context_entries(app: &VectorcraftApp) -> Vec { out } +/// A menu item that the Actions panel's Insert Menu Item… adds to an action as a step +/// ([`insertable_items`]). +#[derive(Clone, Debug, PartialEq)] +pub struct InsertableItem { + /// The menu title and the submenus that hold the item, as the tree names them in English. + pub path: Vec<&'static str>, + /// The item's label in the tree, in English. + pub label: &'static str, + pub command: &'static str, + /// The item's params; `{}` for an item that has none. + pub params: Value, +} + +/// The menus whose items are not added to actions: the application menu, File (documents and +/// files), Window (panels and workspaces) and Help. +const NOT_INSERTED_MENUS: [&str; 4] = ["VectorCraft", "File", "Window", "Help"]; + +/// Commands whose menu items do more than run the command, which action playback does not do: +/// Object › Image Trace › Make and Make and Expand trace off the UI thread with progress and Cancel +/// ([`crate::trace_runs::start`]), and Object › Pattern › Make and Edit Pattern open the Pattern +/// Options panel. +const MENU_ONLY_COMMANDS: [&str; 4] = ["imageTrace.make", "imageTrace.makeAndExpand", "object.pattern.make", "object.pattern.edit"]; + +/// Whether the item labeled `label` in menu `title`, which runs command `id` with `p`, can be a step +/// of an action. It can when it runs an engine command, which action playback runs as the menu +/// does; its label does not end with "…", the mark of an item that asks for values first; it is not +/// in a menu of [`NOT_INSERTED_MENUS`]; and it is not Undo, Redo, a Paste, an item that stands for a +/// saved selection, a saved view or a recent font, a plug-in's item or an action's own command. Nor +/// is it Object › Align, whose menu items add the Align To choice and the selection's key to their +/// params when clicked ([`crate::panels::align::with_align_to`]), which playback does not, or another +/// item of [`MENU_ONLY_COMMANDS`]. +pub fn insertable(title: &str, label: &str, id: &str, p: &Value) -> bool { + use super::slots::{RECENT_FONT_IDS, SAVED_SELECTION_IDS, SAVED_VIEW_IDS}; + vectorcraft_engine::find_command(id).is_some() + && !label.ends_with('…') + && !NOT_INSERTED_MENUS.contains(&title) + && !matches!(id, "edit.undo" | "edit.redo" | "command.batch" | "object.align") + && !MENU_ONLY_COMMANDS.contains(&id) + && !id.starts_with("edit.paste") + && !id.starts_with("prefs.") + && !id.starts_with("action.") + && ![&RECENT_FONT_IDS[..], &SAVED_SELECTION_IDS[..], &SAVED_VIEW_IDS[..]].iter().any(|ids| ids.contains(&id)) + && !super::labels::lists_plugin(id, p) +} + +/// Every menu item that can be a step of an action ([`insertable`]), in menu order. An item that +/// shows in two places is listed in both. `english_names` is as [`menu_tree_named`] takes it. +pub fn insertable_items(english_names: bool) -> Vec { + fn walk(title: &'static str, path: &mut Vec<&'static str>, items: &[Item], out: &mut Vec) { + for it in items { + match it { + Item::Cmd(label, id, p) if insertable(title, label, id, p) => out.push(InsertableItem { + path: path.clone(), + label, + command: id, + params: if p.is_null() { serde_json::json!({}) } else { p.clone() }, + }), + Item::Sub(label, children) => { + path.push(label); + walk(title, path, children, out); + path.pop(); + } + _ => {} + } + } + } + let mut out = vec![]; + for (title, items) in menu_tree_named(english_names) { + walk(title, &mut vec![title], &items, &mut out); + } + out +} + fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Vec) { for it in items { match it { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 1223e1e426..de3261de1b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -25,6 +25,34 @@ pub(crate) fn opt_bool(p: &Value, key: &str) -> Result, String> { } } +/// An optional `{key?: number}` param: none when it is omitted or null. +pub(crate) fn opt_number(p: &Value, key: &str) -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_f64().map(Some).ok_or_else(|| format!("`{key}` must be a number")), + } +} + +/// An optional `{key?: index}` param, a whole number of 0 or more: none when it is omitted or null. +pub(crate) fn opt_index(p: &Value, key: &str) -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).map(Some).ok_or_else(|| format!("`{key}` must be a whole number of 0 or more")), + } +} + +/// An optional `{key?: [x, y]}` param: none when it is omitted or null. +fn opt_point(p: &Value, key: &str) -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_array().map(Vec::as_slice) { + Some([x, y]) => x.as_f64().zip(y.as_f64()).map(|(x, y)| Some(vectorcraft_geom::Point::new(x, y))), + _ => None, + } + .ok_or_else(|| format!("`{key}` must be [x, y] numbers")), + } +} + /// Handle a UI command. `None` = not a UI command (the engine handles it). /// `params` has only keys the params description of engine command `id` names, or the parameter /// error naming the one it doesn't (#1442). The UI's own commands aren't checked yet: their @@ -48,13 +76,18 @@ pub fn check_params(session: &vectorcraft_engine::Session, id: &str, params: &Va pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { // Window menu items and the named panel function keys toggle against the checked state; // other commands that open panels show them. - if id == "window.panel" && p.get("toggle").and_then(Value::as_bool) == Some(true) && checked(app, id, p) == Some(true) { + let toggles = if id == "window.panel" { opt_bool(p, "toggle").and_then(|t| Ok((t, opt_bool(p, "toggleGroup")?))) } else { Ok((None, None)) }; + let (toggle, toggle_group) = match toggles { + Ok(flags) => flags, + Err(e) => return Some(Err(e)), + }; + if toggle == Some(true) && checked(app, id, p) == Some(true) { let panel = p.get("panel").and_then(Value::as_str).and_then(normalize_panel).unwrap_or_default(); if app.ui.open_panel.as_deref() == Some(panel) { app.ui.open_panel = None; return Some(Ok(json!({"open": null}))); } - if p.get("toggleGroup").and_then(Value::as_bool) == Some(true) { + if toggle_group == Some(true) { return Some(crate::panel_docking::hide_group(app, panel)); } return Some(app.run("window.panel.close", json!({"panel": panel}))); @@ -81,6 +114,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option io::open_with(app, p), // Saves write through the app (save panel, download); with no path known the panel and the // format's options dialog ask first. - "file.save" => io::save(app, SaveMode::Save, p, true), - "file.saveAs" => io::save(app, SaveMode::SaveAs, p, true), - "file.saveCopy" => io::save(app, SaveMode::Copy, p, true), - "file.saveAsTemplate" => io::save(app, SaveMode::Template, p, true), + // A confined request sees the document's own file, and the folder a save suggests, only + // inside its read roots. + "file.save" | "file.saveAs" | "file.saveCopy" | "file.saveAsTemplate" => { + let mode = match id { + "file.save" => SaveMode::Save, + "file.saveAs" => SaveMode::SaveAs, + "file.saveCopy" => SaveMode::Copy, + _ => SaveMode::Template, + }; + io::save(app, mode, p, true).map(|mut r| { + vectorcraft_engine::cmd::fileio::leave_out_unreadable_save_paths(&mut r, p.get("path").and_then(Value::as_str)); + r + }) + } "document.exportSelection" => { io::save_command_output(app, id, "png", if p.is_object() { p.clone() } else { json!({}) }).map(|p| json!({"path": p})) } // Bytes sent by an agent go straight to the engine; a path or nothing opens it here. "file.newFromTemplate" if p.get("dataBase64").is_none() => io::new_from_template(app, s("path")), - "file.revert" if p.get("confirmed").and_then(Value::as_bool) != Some(true) => io::ask_revert(app), + "file.revert" if opt_bool(p, "confirmed") != Ok(Some(true)) => opt_bool(p, "confirmed").and_then(|_| io::ask_revert(app)), "file.reveal" => io::reveal(app), "file.cancelExport" => Ok(io::cancel_exports(app)), "file.exportInBackground" => Ok(io::hide_exports(app)), @@ -386,9 +430,11 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { let print = app.session.prefs.display_print_size; - let z = crate::state::zoom_from_display_percent(p.get("zoom").and_then(Value::as_f64).unwrap_or(100.0), print); - let center = - p.get("center").and_then(Value::as_array).and_then(|a| Some(vectorcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))); + let (zoom, center) = match opt_number(p, "zoom").and_then(|z| Ok((z, opt_point(p, "center")?))) { + Ok(given) => given, + Err(e) => return Some(Err(e)), + }; + let z = crate::state::zoom_from_display_percent(zoom.unwrap_or(100.0), print); match app.view_mut() { Some(v) => { v.zoom = z.clamp(0.0313, 640.0); @@ -417,7 +463,11 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { - app.ui.screen_mode = match p.get("mode").and_then(Value::as_u64) { + let mode = match opt_index(p, "mode") { + Ok(mode) => mode, + Err(e) => return Some(Err(e)), + }; + app.ui.screen_mode = match mode { Some(m) => m.min(3) as u8, // F cycles the three screen modes. Without a mode, the command also goes from // Presentation Mode (not in the cycle) back to Normal. @@ -477,6 +527,24 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err(format!("`{key}` must be one of {}", edges.join(", "))), } } + // The Control bar's panel menu: a group of the bar's options on or off. + "window.control.options" => { + let groups = crate::chrome::CONTROL_BAR_GROUPS; + match (groups.iter().find(|g| s("group").as_deref() == Some(**g)), opt_bool(p, "visible")) { + (None, _) => Err(format!("`group` must be one of {}", groups.join(", "))), + (_, Err(e)) => Err(e), + (Some(&group), Ok(visible)) => { + let hidden = &mut app.ui.control_bar_hidden_groups; + let visible = visible.unwrap_or_else(|| hidden.contains(group)); + if visible { + hidden.remove(group); + } else { + hidden.insert(group.to_string()); + } + Ok(json!({ "group": group, "visible": visible })) + } + } + } "window.toolbar" => flag(&mut app.ui.toolbar), "window.toolbarColumns" => { let toolbar = match crate::custom_toolbars::target(&app.ui, p) { @@ -656,6 +724,7 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::updates_ui::check(app), "help.safeMode" => crate::dialogs::safe_mode::open(app), + "help.copyTroubleshootingInfo" => crate::troubleshooting::copy(app), "help.commandPalette" => { app.ui.palette_open = !app.ui.palette_open; app.ui.palette_query.clear(); @@ -664,9 +733,10 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option match p.get("index").and_then(Value::as_u64).map(|i| i as usize) { - Some(i) => crate::unsaved::close(app, i), - None => { + "file.close" => match opt_index(p, "index") { + Err(e) => Err(e), + Ok(Some(i)) => crate::unsaved::close(app, i), + Ok(None) => { app.session.active_index()?; crate::doc_windows::close_current(app) } @@ -678,8 +748,10 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("missing `name`".into()), }, "ui.newSwatch" => { - let on = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false); - crate::dialogs::new_swatch::open(app, on("spot"), on("global"), s("group").as_deref()) + let on = |k: &str| opt_bool(p, k).map(|on| on.unwrap_or(false)); + on("spot") + .and_then(|spot| Ok((spot, on("global")?))) + .and_then(|(spot, global)| crate::dialogs::new_swatch::open(app, spot, global, s("group").as_deref())) } "ui.newColorGroup" => { let names = p.get("swatches").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()); @@ -693,11 +765,19 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("missing `name`".into()), }, "ui.charStyleOptions.resetPanel" => crate::dialogs::char_style_options::reset_panel(app), + "ui.paraStyleOptions" => match s("name") { + Some(name) => crate::dialogs::para_style_options::open(app, &name), + None => Err("missing `name`".into()), + }, + "ui.paraStyleOptions.resetPanel" => crate::dialogs::para_style_options::reset_panel(app), "ui.newCharStyle" => crate::panels::text_styles::open_new(app, crate::panels::text_styles::Kind::Char), "ui.newParaStyle" => crate::panels::text_styles::open_new(app, crate::panels::text_styles::Kind::Para), "ui.symbolOptions" => { let name = s("name"); - let edit = p.get("edit").and_then(Value::as_bool).unwrap_or(false); + let edit = match opt_bool(p, "edit") { + Ok(edit) => edit.unwrap_or(false), + Err(e) => return Some(Err(e)), + }; if edit || name.is_some() { crate::dialogs::symbol_options::open_edit(app, name.as_deref()) } else { @@ -896,12 +976,12 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::record(app, p), crate::panels::actions::STOP_RECORDING => crate::panels::actions::stop(app, p), crate::panels::actions::INSERT_STOP => crate::panels::actions::insert_stop(app, p), + crate::panels::actions::INSERT_MENU_ITEM => crate::panels::actions::insert_menu_item(app, p), crate::panels::actions::CONTINUE_PLAYBACK => crate::panels::actions::continue_playback(app, p), crate::panels::actions::DELETE_STEP => crate::panels::actions::delete_step(app, p), "ui.batchDialog" => { - let set = p.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; - let action = p.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; - crate::dialogs::action_batch::open(app, set, action) + let index = |k: &str| opt_index(p, k).map(|i| i.unwrap_or(0)); + index("set").and_then(|set| Ok((set, index("action")?))).and_then(|(set, action)| crate::dialogs::action_batch::open(app, set, action)) } crate::panels::actions::SAVE_SET => crate::panels::actions::save_set(app, p), crate::panels::actions::LOAD_SET => crate::panels::actions::load_set(app, p), @@ -934,7 +1014,11 @@ fn run_ui_part12(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { - app.run("assets.add", json!({ "multiple": p.get("multiple").and_then(Value::as_bool).unwrap_or(false) })).map(|r| { + let multiple = match opt_bool(p, "multiple") { + Ok(multiple) => multiple.unwrap_or(false), + Err(e) => return Some(Err(e)), + }; + app.run("assets.add", json!({ "multiple": multiple })).map(|r| { let ids: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); crate::dialogs::open_export_for_screens_assets(app, Some(&ids)); json!({ "assets": ids }) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 1941504e57..d68608824b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -16,16 +16,16 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { let v = &app.ui.view; // An item that can be on or off is `Some` whatever the document and selection (off with none): // the macOS menu bar can't change an item's kind without rebuilding. - // The first type object (of type on a path, with `onpath`) among the selected objects and the - // objects inside them, in the order the type commands act on them. - let selected_text = |onpath: bool| { + // The first type object of a kind `kinds` takes among the selected objects and the objects + // inside them, in the order the type commands act on them. + let selected_text = |kinds: fn(&vectorcraft_engine::doc::TextKind) -> bool| { let st = app.session.active()?; let mut found = None; for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { n.walk(&mut |c| { if found.is_none() && let vectorcraft_engine::doc::NodeKind::Text(t) = &c.kind - && (!onpath || matches!(t.kind, vectorcraft_engine::doc::TextKind::OnPath { .. })) + && kinds(&t.kind) { found = Some(t); } @@ -41,15 +41,17 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { crate::panels::character::shared_text_flag(app, |t| t.vertical) == Some(id == "type.orientation.vertical") } "type.opticalMarginAlignment" => crate::panels::character::shared_text_flag(app, |t| t.optical_margin) == Some(true), + // Dynamic Text of the first selected type on a path or area type, which the item turns the + // other way. + "type.dynamicText" => selected_text(|k| !matches!(k, vectorcraft_engine::doc::TextKind::Point)).is_some_and(|t| t.dynamic_text), "view.outline" => app.outline_view(), "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, "view.snapToGlyph" => v.snap_to_glyph, // Type on a Path effect of the selected path type. - "type.pathOptions" if p.get("effect").is_some() => { - selected_text(true).is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())) - } + "type.pathOptions" if p.get("effect").is_some() => selected_text(|k| matches!(k, vectorcraft_engine::doc::TextKind::OnPath { .. })) + .is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())), "view.smartGuides" => v.smart_guides, "edit.autoSpellCheck" => v.auto_spell_check, "view.grid" => v.grid, @@ -64,6 +66,10 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "window.control.dock" => { p.get("edge").and_then(Value::as_str) == Some(crate::chrome::CONTROL_BAR_EDGES[usize::from(app.ui.control_bar_bottom)]) } + "window.control.options" => p + .get("group") + .and_then(Value::as_str) + .is_some_and(|g| crate::chrome::CONTROL_BAR_GROUPS.contains(&g) && !app.ui.control_bar_hidden_groups.contains(g)), "window.toolbar" => app.ui.toolbar, "window.toolbarAdvanced" => app.ui.toolbar_advanced, "window.toolsBesideCanvas" => app.ui.tools_beside_canvas, @@ -87,6 +93,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "window.taskBar" => app.ui.task_bar, "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, + "window.learn" => crate::panels::learn::visible(&app.ui), "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); normalize_panel(panel).is_some_and(|id| crate::panel_docking::showing(&app.ui, id)) @@ -264,11 +271,18 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(), "ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), "ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(), - "ui.graphicStyleOptions" | "ui.charStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => app.session.active().is_some(), + "ui.graphicStyleOptions" | "ui.charStyleOptions" | "ui.paraStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => { + app.session.active().is_some() + } "ui.charStyleOptions.resetPanel" => app.ui.dialog.as_ref().is_some_and(|d| { (d.kind == crate::dialogs::char_style_options::KIND || (d.kind == crate::dialogs::new_text_style::KIND && !d.bool("__para"))) && crate::dialogs::char_style_options::can_reset(d) }), + "ui.paraStyleOptions.resetPanel" => app + .ui + .dialog + .as_ref() + .is_some_and(|d| crate::dialogs::para_style_options::is_paragraph_dialog(d) && crate::dialogs::para_style_options::can_reset(d)), "ui.newArtboard" | "artboard.selectAll" => app.session.active().is_some(), "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index bcb51b133a..c4a5f10069 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -313,6 +313,138 @@ fn optical_margin_alignment_is_a_checked_type_menu_item() { assert_eq!(checked(&app, "type.orientation.horizontal", &Value::Null), Some(false)); } +/// Type › Dynamic Text runs `type.dynamicText`, is enabled for type on a path and area type that +/// are in no thread, and is checked while the selected type has it on. +#[test] +fn dynamic_text_is_a_checked_type_menu_item() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ids: Vec<&str> = menu_tree() + .into_iter() + .filter(|(menu, _)| *menu == "Type") + .flat_map(|(_, items)| items) + .filter_map(|item| match item { + Item::Cmd("Dynamic Text", id, _) => Some(id), + _ => None, + }) + .collect(); + assert_eq!(ids, ["type.dynamicText"]); + let id = "type.dynamicText"; + assert_eq!(checked(&app, id, &Value::Null), Some(false)); + assert!(!enabled(&app, id)); + let point = app.run("text.create", json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [point]})).unwrap(); + assert!(!enabled(&app, id), "point type"); + let path = app.run("path.create", json!({"d": "M60 150 L340 150"})).unwrap()["id"].clone(); + let t = app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Along", "at": [60, 150]})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [t]})).unwrap(); + assert!(enabled(&app, id)); + assert_eq!(checked(&app, id, &Value::Null), Some(false)); + app.run(id, json!({})).unwrap(); + assert_eq!(checked(&app, id, &Value::Null), Some(true)); + app.run(id, json!({})).unwrap(); + assert_eq!(checked(&app, id, &Value::Null), Some(false)); + let frame = app.run("shape.rectangle", json!({"x": 60, "y": 200, "width": 200, "height": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [t, frame]})).unwrap(); + app.run("text.thread.create", json!({})).unwrap(); + app.run("select.set", json!({"ids": [t]})).unwrap(); + assert!(!enabled(&app, id), "type on a path in a thread"); + // Area type takes Block, and the item is checked while it is on. + let area = app.run("text.create", json!({"x": 10, "y": 400, "text": "Block", "area": {"width": 100, "height": 50}})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [area]})).unwrap(); + assert!(enabled(&app, id), "area type"); + assert_eq!(checked(&app, id, &Value::Null), Some(false)); + app.run(id, json!({})).unwrap(); + assert_eq!(checked(&app, id, &Value::Null), Some(true)); +} + +/// Type › Type on a Path › Center on Top and Center on Bottom run `type.pathCenter.top` and +/// `.bottom`, which the command palette also runs without params, and are enabled for type on a +/// closed path only. +#[test] +fn center_on_top_and_bottom_are_type_on_a_path_items() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let items: Vec<(&str, &str)> = menu_tree() + .into_iter() + .filter(|(menu, _)| *menu == "Type") + .flat_map(|(_, items)| items) + .filter_map(|item| match item { + Item::Sub("Type on a Path", children) => Some(children), + _ => None, + }) + .flatten() + .filter_map(|item| match item { + Item::Cmd(label, id, Value::Null) if id.starts_with("type.pathCenter") => Some((label, id)), + _ => None, + }) + .collect(); + let ids = ["type.pathCenter.top", "type.pathCenter.bottom"]; + assert_eq!(items, [("Center on Top", ids[0]), ("Center on Bottom", ids[1])]); + let palette = crate::palette::items(); + for (label, id) in items { + assert!(palette.iter().any(|(l, i, _)| l == &format!("Type › Type on a Path › {label}") && i == id), "{label}"); + } + let line = app.run("path.create", json!({"d": "M60 150 L340 150"})).unwrap()["id"].clone(); + let open = app.run("text.createInPath", json!({"path": line, "mode": "onPath", "text": "Along", "at": [60, 150]})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [open]})).unwrap(); + assert!(ids.iter().all(|id| !enabled(&app, id)), "type on an open path"); + let square = app.run("path.create", json!({"d": "M60 200 L160 200 L160 300 L60 300 Z"})).unwrap()["id"].clone(); + let closed = app.run("text.createInPath", json!({"path": square, "mode": "onPath", "text": "Round", "at": [60, 200]})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [closed]})).unwrap(); + assert!(ids.iter().all(|id| enabled(&app, id))); + app.run("select.set", json!({"ids": [closed, open]})).unwrap(); + assert!(ids.iter().all(|id| !enabled(&app, id)), "type on a closed path and on an open one"); + // A palette pick runs the command with no params. + app.run("select.set", json!({"ids": [closed]})).unwrap(); + crate::palette::run_pick(&mut app, ids[0]); + let doc = &app.session.active().unwrap().doc; + let start = match &doc.node(vectorcraft_doc::NodeId(closed.as_u64().unwrap())).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => match t.kind { + vectorcraft_doc::TextKind::OnPath { start, .. } => start, + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + // Once round, the middle of the top edge an eighth of the way round. + assert!((start - 0.625).abs() < 1e-6, "{start}"); +} + +/// Type › Dynamic Text Presets › Circle, Arch and Bow run `type.dynamicTextPreset` with their +/// preset, enabled for point type and type on a path but not for area type alone. +#[test] +fn dynamic_text_presets_are_a_type_submenu() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let items: Vec<(&str, &str, Value)> = menu_tree() + .into_iter() + .filter(|(menu, _)| *menu == "Type") + .flat_map(|(_, items)| items) + .filter_map(|item| match item { + Item::Sub("Dynamic Text Presets", children) => Some(children), + _ => None, + }) + .flatten() + .filter_map(|item| match item { + Item::Cmd(label, id, p) => Some((label, id, p)), + _ => None, + }) + .collect(); + let id = "type.dynamicTextPreset"; + assert_eq!(items, [("Circle", id, json!({"preset": "circle"})), ("Arch", id, json!({"preset": "arch"})), ("Bow", id, json!({"preset": "bow"}))]); + assert!(!enabled(&app, id)); + let area = app.run("text.create", json!({"x": 10, "y": 200, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [area]})).unwrap(); + assert!(!enabled(&app, id), "area type"); + let point = app.run("text.create", json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [point]})).unwrap(); + assert!(enabled(&app, id)); + app.run(id, json!({"preset": "arch"})).unwrap(); + // Now type on a path with Dynamic Text on, so Type › Dynamic Text is checked. + assert!(enabled(&app, id)); + assert_eq!(checked(&app, "type.dynamicText", &Value::Null), Some(true)); +} + /// Type › Optical Margin Alignment menu check uses `shared_text_flag`; mixed values stay unchecked. #[test] fn optical_margin_alignment_menu_unchecked_when_shared_flag_none() { @@ -444,6 +576,38 @@ fn classic_extrude_bevel_is_in_the_3d_classic_submenu() { assert!(at("Materials…").unwrap() < at("Extrude & Bevel (Classic)…").unwrap()); } +/// Effect › 3D and Materials › 3D (Classic) › Revolve (Classic)… opens its effect dialog, after +/// Extrude & Bevel (Classic)…, and nowhere else. +#[test] +fn classic_revolve_is_in_the_3d_classic_submenu() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let entries = menu_entries(&app); + let classic: Vec<_> = entries.iter().filter(|e| e.params.get("effect").and_then(Value::as_str) == Some("threeD.classicRevolve")).collect(); + assert_eq!(classic.len(), 1, "listed once"); + let e = classic[0]; + assert_eq!(e.path, ["Effect", "3D and Materials", "3D (Classic)"]); + assert_eq!((e.label.as_str(), e.command.as_deref()), ("Revolve (Classic)…", Some("effect.dialog"))); + let at = |label: &str| entries.iter().position(|x| x.label == label && x.path.get(1).is_some_and(|p| p == "3D and Materials")); + assert!(at("Extrude & Bevel (Classic)…").unwrap() < at("Revolve (Classic)…").unwrap()); +} + +/// Effect › 3D and Materials › 3D (Classic) › Rotate (Classic)… opens its effect dialog, after +/// Revolve (Classic)…, and nowhere else. +#[test] +fn classic_rotate_is_in_the_3d_classic_submenu() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let entries = menu_entries(&app); + let classic: Vec<_> = entries.iter().filter(|e| e.params.get("effect").and_then(Value::as_str) == Some("threeD.classicRotate")).collect(); + assert_eq!(classic.len(), 1, "listed once"); + let e = classic[0]; + assert_eq!(e.path, ["Effect", "3D and Materials", "3D (Classic)"]); + assert_eq!((e.label.as_str(), e.command.as_deref()), ("Rotate (Classic)…", Some("effect.dialog"))); + let at = |label: &str| entries.iter().position(|x| x.label == label && x.path.get(1).is_some_and(|p| p == "3D and Materials")); + assert!(at("Revolve (Classic)…").unwrap() < at("Rotate (Classic)…").unwrap()); +} + /// A document's 25 views are all listed at the bottom of the View menu, by name, and the last /// one brings back its zoom, centre and rotation after the view changed. #[test] diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 947093aba3..5b88346f82 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -396,9 +396,24 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { PATH_EFFECTS .iter() .map(|&(label, effect)| cp(label, "type.pathOptions", json!({ "effect": effect }))) - .chain([Sep, c("Type on a Path Options…", "type.pathOptions")]) + .chain([ + Sep, + c("Center on Top", "type.pathCenter.top"), + c("Center on Bottom", "type.pathCenter.bottom"), + Sep, + c("Type on a Path Options…", "type.pathOptions"), + ]) .collect(), ), + c("Dynamic Text", "type.dynamicText"), + sub( + "Dynamic Text Presets", + vec![ + cp("Circle", "type.dynamicTextPreset", json!({"preset": "circle"})), + cp("Arch", "type.dynamicTextPreset", json!({"preset": "arch"})), + cp("Bow", "type.dynamicTextPreset", json!({"preset": "bow"})), + ], + ), sub( "Threaded Text", vec![ @@ -490,6 +505,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Slices", "select.object.slices"), c("Stray Points", "select.object.strayPoints"), c("Open Paths", "select.object.openPaths"), + c("Not Aligned to Pixel Grid", "select.object.notAlignedToPixelGrid"), Sep, c("All Text Objects", "select.object.textObjects"), c("Point Text Objects", "select.object.pointText"), @@ -657,6 +673,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { panel("Image Trace", "imageTrace"), panel("Info", "info"), panel("Layers", "layers"), + cp("Learn", "window.learn", json!({})), panel("Libraries", "libraries"), panel("Links", crate::panels::links::ID), panel("Magic Wand", "magicWand"), @@ -711,6 +728,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Search Commands…", "help.commandPalette"), todos("VectorCraft Help…", "F1"), c("Safe Mode…", "help.safeMode"), + c("Copy Troubleshooting Info", "help.copyTroubleshootingInfo"), Sep, c("Check for Updates…", "help.checkForUpdates"), c("About VectorCraft", "help.about"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index a96f13e67c..f435bfff22 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -472,6 +472,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{edge: \"top\"|\"bottom\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do; kept with the workspace; another edge is an error and changes nothing; returns {edge}", ), + ( + "window.control.options", + "Control Bar Options", + "", + "{group: \"snapping\"|\"anchors\"|\"toolOptions\"|\"objectOptions\"|\"imageOptions\"|\"fillStroke\"|\"opacity\"|\"graphicStyle\"|\"character\"|\"paragraph\"|\"verticalAlignment\"|\"alignDistribute\"|\"transform\"|\"artboardOptions\"|\"documentOptions\", visible?: bool} turn a group of the Control bar's options on (true), off (false) or toggle it (omitted), as the bar's panel menu does; a group that is off stays out of the bar even while its tool or object is selected, and one that is on shows only while the selection or the tool calls for it; every group starts on; kept with the workspace; another group or a `visible` that is not true or false is an error and changes nothing; returns {group, visible}", + ), ("window.toolbar", "Tools", "", "{}"), ( "window.toolbarColumns", @@ -629,6 +635,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{collapsed?: bool} collapse every expanded dock column to icons (true), expand the outer dock column, Properties | Layers | Libraries (false), or toggle the outer column (omitted), as the double arrow at the top of the dock does; returns the new state", ), + ( + "window.learn", + "Learn", + "", + "{show?: bool} show (true), hide (false) or toggle (omitted or null) the Learn panel, as Window › Learn and the app bar's Explore tutorials button do; any other value is an error and changes nothing; returns whether the panel shows", + ), + ( + "learn.list", + "List Tutorials", + "", + "{} the Learn panel's skills in the order its Skills tab lists them: {skills: [{id, title, tutorials: [{id, title, steps: number of steps}]}]}", + ), + ( + "learn.show", + "Show Tutorial", + "", + "{tutorial: id (see learn.list)} show the Learn panel on its Skills tab with that tutorial's numbered steps, as choosing its skill and then the tutorial does; a missing, non-string or unknown id is an error and changes nothing; returns {skill, tutorial, title, steps: [text]}", + ), ("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"), ( "window.workspace", @@ -743,6 +767,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open the Safe Mode dialog (dialog `safeMode`): whether VectorCraft is in Safe Mode, and the disabled plug-ins, each with Enable on Re-launch (engine: plugin.setEnabled). Closing it leaves Safe Mode as it is; Safe Mode is chosen at launch (--safe-mode, or the choice after a launch that stopped while a plug-in was loading, dialog `pluginStopped`)", ), + ( + "help.copyTroubleshootingInfo", + "Copy Troubleshooting Info", + "", + "{} put text for a bug report on the clipboard: the version, and in the desktop app the platform, the window system, the graphics processor, the commands and frame times of the last few frames, and the hang reports of this session and the session before (no document contents or file paths) → {chars}", + ), ("app.quit", "Quit VectorCraft", "Cmd+Q", "{}"), ( "ui.swatchOptions", @@ -804,6 +834,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} clear the settings of the section shown, Basic Character Formats, Advanced Character Formats, Character Color or OpenType Features, in the open Character Style Options or New Character Style dialog; available only on those sections", ), + ( + "ui.paraStyleOptions", + "Paragraph Style Options", + "", + "{name} open Paragraph Style Options (dialog `paraStyleOptions`, sections General, Basic Paragraph Formats, Composition, Hyphenation and Justification); OK runs paraStyle.edit with name, to and sparse attrs in one undo step; Cancel restores a live preview", + ), + ( + "ui.paraStyleOptions.resetPanel", + "Reset Panel", + "", + "{} clear the settings of the section shown, Basic Paragraph Formats, Composition, Hyphenation or Justification, in the open Paragraph Style Options or New Paragraph Style dialog; available only on those sections", + ), ( "ui.newCharStyle", "New Character Style…", @@ -814,7 +856,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newParaStyle", "New Paragraph Style…", "", - "{} open New Paragraph Style (dialog `newTextStyle`, field `name`, filled in with the name paraStyle.new {} would give the style), what Alt-clicking the Paragraph Styles panel's New button opens; OK runs paraStyle.new with the name and the paragraph of the Type tool's selection (else the selected type) as it was when the dialog opened; Cancel adds no style", + "{} open New Paragraph Style (dialog `newTextStyle`, field `name`, filled in with the name paraStyle.new {} would give the style), what Alt-clicking the Paragraph Styles panel's New button opens; the dialog also has the sections of Paragraph Style Options, filled in from the paragraph of the Type tool's selection (else the selected type) as it was when the dialog opened; OK runs paraStyle.new with the name and those attrs; Cancel adds no style", ), ( "ui.symbolOptions", @@ -1195,7 +1237,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPanel", "Color Panel Options", "", - "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), and Show Options (true) or Hide Options (false); both are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options) → {mode (null: none picked yet), options, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", + "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool, recentColors?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), Show Options (true) or Hide Options (false), and check (true) or uncheck (false) Show Recent Colors, which shows or hides the panel's Recent Colors row (applied colors still join the list while it is hidden; the Swatches panel keeps its row); all three are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options, ui.color_show_recent_colors) → {mode (null: none picked yet), options, recentColors, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", ), ( "ui.savePdfDialog", @@ -1378,7 +1420,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::INSERT_STOP, "Insert Stop", "", - "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, or no action and no recording is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, no action and no recording, or a stop that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), + ( + crate::panels::actions::INSERT_MENU_ITEM, + "Insert Menu Item", + "", + "{set?: index, action?: index, step?: index, command, params?: object} insert the command of a menu item as a step, without running it; the step plays as choosing the item runs it. command and params (default {}) must be those of a menu item that can be a step: one that runs an engine command, whose label does not end with \"…\", outside the VectorCraft, File, Window and Help menus, and that is not Undo, Redo, a Paste, a batch (command.batch), a preference (prefs.*) or action (action.*) command, an Object › Align item, Image Trace's Make or Make and Expand, Pattern's Make or Edit Pattern, a saved selection, saved view or recent font item, or a plug-in's item. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A command and params that no such menu item has, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Menu Item… (dialog `actionInsertMenuItem` with find, command, params, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", ), ( crate::panels::actions::CONTINUE_PLAYBACK, @@ -1463,7 +1511,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "css.exportFile", "Export CSS…", "", - "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first)}", + "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first and how many there are, and hovering the message lists up to 30 of them, fewer when the window is small, with how many were left out)}", ), ( "file.print", @@ -1494,25 +1542,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", ), ( "ui.installPlugin", "Install Plug-in…", "", - "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), ( "plugin.cancelRuns", "Cancel Plug-in Run", "", - "{} stop every heavy filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", + "{} stop every filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", ), ( "plugin.hideRuns", "Continue in Background", "", - "{} close the progress window of the heavy filters running in the background; they go on, shown in the status bar → {hidden: n}", + "{} close the progress window of the filters running in the background; they go on, shown in the status bar → {hidden: n}", ), ( "imageTrace.cancelRuns", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 56baee51aa..510131be0e 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -499,6 +499,9 @@ pub enum Event { /// A key equivalent pressed: the item's key with the modifiers held, to be handled as the key /// press it was. Key(KeyboardShortcut), + /// A menu of the bar opened. The Scripts folder is read again, as when the in-window File menu + /// opens; the new listing shows the next time the menu opens. + Opened, } /// A platform's native menu bar (the desktop app implements it for macOS with muda). @@ -517,6 +520,8 @@ pub struct NativeMenu { /// Hash of the state the menus were last read in ([`state_hash`]). state: Option, clicks: Vec, + /// A menu opened since the last [`run`]. + opened: bool, /// Something was chosen (AppKit may have toggled a check mark itself): read the menus again. dirty: bool, logged: bool, @@ -524,17 +529,21 @@ pub struct NativeMenu { impl NativeMenu { pub fn new(backend: Box) -> NativeMenu { - NativeMenu { backend, state: None, clicks: Vec::new(), dirty: true, logged: false } + NativeMenu { backend, state: None, clicks: Vec::new(), opened: false, dirty: true, logged: false } } - /// The key equivalents pressed since the last frame, for [`key_events`]; clicks wait for - /// [`run`]. + /// The key equivalents pressed since the last frame, for [`key_events`]; clicks and menus + /// opened wait for [`run`]. pub fn take_keys(&mut self) -> Vec { let mut keys = Vec::new(); for e in self.backend.drain() { match e { Event::Key(k) => keys.push(k), Event::Click(it) => self.clicks.push(it), + Event::Opened => { + self.opened = true; + continue; + } } self.dirty = true; } @@ -542,10 +551,15 @@ impl NativeMenu { } } -/// Run the items clicked in the native menu since the last frame, like in-window menu clicks. +/// Run the items clicked in the native menu since the last frame, like in-window menu clicks, and +/// read the Scripts folder again when a menu opened. pub fn run(app: &mut VectorcraftApp, ctx: &egui::Context) { let picking = app.file_dialog_open(); let Some(menu) = app.services.native_menu.as_mut() else { return }; + if std::mem::take(&mut menu.opened) { + crate::scripts_menu::refresh(app, Some(ctx)); + } + let Some(menu) = app.services.native_menu.as_mut() else { return }; for it in std::mem::take(&mut menu.clicks) { // A click that raced the menu going inert under a file dialog. if picking && !modal_allows(&it) { diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 3447cd1e15..ef502761df 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1238,18 +1238,28 @@ fn palette_window_state(modal: bool, popup: bool, active: bool) -> (egui::Window /// 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. +/// the windows there are. A window that opens while the others are hidden (a panel floated under a +/// dialog, a menu, a flyout or the drawer) opens shown at its palette level, so it gets the commands +/// in its first frame. #[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 state = (modal, popup, active); + let windows: Vec = layout.floating.iter().map(|window| window.id).collect(); + let sent = ctx.data(|d| d.get_temp::<((bool, bool, bool), Vec)>(key)); let (level, visible) = palette_window_state(modal, popup, active); - for window in &layout.floating { + // The windows that already have this state's commands. + let known: &[u64] = match &sent { + Some((was, ids)) if *was == state && !visible => ids, + Some((was, _)) if *was == state => &windows, + _ => &[], + }; + let fresh: Vec = windows.iter().copied().filter(|id| !known.contains(id)).collect(); + if sent.as_ref().is_none_or(|(was, ids)| *was != state || *ids != windows) { + ctx.data_mut(|d| d.insert_temp(key, (state, windows))); + } + for window in layout.floating.iter().filter(|window| fresh.contains(&window.id)) { 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)); diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index db1e6be36c..2f1d0d536c 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -842,6 +842,36 @@ fn a_torn_off_strip_or_a_new_toolbar_leaves_the_palette_windows_shown() { assert_eq!(take_palette_commands(&h, viewport).0, [false], "still shown: the drawer hides them again"); } +/// A panel floated while the palette windows are hidden opens hidden too, and shows with the others +/// once the drawer or the dialog over them closes. +#[test] +fn a_panel_floated_while_the_palette_windows_are_hidden_opens_hidden() { + let mut h = Harness::new(); + let navigator = h.float("navigator"); + h.host.borrow_mut().focus = ViewportId::ROOT; + h.frames(2); + take_palette_commands(&h, navigator); + h.app.run("window.editToolbar", json!({"open": true})).unwrap(); + h.frames(2); + assert_eq!(take_palette_commands(&h, navigator).0, [false], "hidden under the drawer"); + let layers = h.float("layers"); + h.host.borrow_mut().focus = ViewportId::ROOT; + assert!(h.app.ui.tools_drawer, "the drawer stays open"); + let (shown, levels) = take_palette_commands(&h, layers); + assert_eq!(shown, [false], "the new palette window is hidden under the drawer"); + assert_eq!(levels, [egui::WindowLevel::Normal], "and out of the top level"); + h.app.run("window.editToolbar", json!({"open": false})).unwrap(); + h.frames(2); + assert_eq!(take_palette_commands(&h, layers).0, [true], "shown when the drawer closes"); + + h.app.ui.palette_open = true; + h.frames(2); + assert_eq!(take_palette_commands(&h, layers).0, [false], "hidden under the command palette"); + let swatches = h.float("swatches"); + h.host.borrow_mut().focus = ViewportId::ROOT; + assert_eq!(take_palette_commands(&h, swatches).0, [false], "a panel floated under it is hidden too"); +} + /// The frame in which a click elsewhere closes a flyout or the drawer shows the palette windows, as /// no later frame need come while the app is idle. #[test] diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 1106406bc0..899f026398 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -26,6 +26,7 @@ pub mod history; pub mod image_trace; pub mod info; pub mod layers; +pub mod learn; pub mod libraries; pub mod library_panel; pub mod links; @@ -185,6 +186,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { css_properties::ID => css_properties::show(app, ui), three_d::ID => three_d::show(app, ui), script_console::ID => script_console::show(app, ui), + learn::ID => learn::show(app, ui), crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 2533ef0292..de6b36bc6e 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -870,31 +870,145 @@ const SELECTED_STEP: &str = "actions-selected-step"; /// them, it goes into the recording in progress, after the steps recorded so far. `message` is /// the text playback shows (default: none), and `allowContinue` offers Continue in the message box /// (default: false). An index past the last set, action or step, a param of another type, params -/// that are not an object, or no action and no recording is an error, and then nothing changes. -/// Record Stop's OK runs this. A stop in an action becomes the selected step, and its action and set -/// become the selected ones. → {set, action, step}, or {recording: true} +/// that are not an object, or no action and no recording is an error, and then nothing changes. So +/// is a stop that would give the action more than 10,000 steps, or its set a file larger than 8 MiB, +/// the most Load Actions… reads. Record Stop's OK runs this. A stop in an action becomes the selected +/// step, and its action and set become the selected ones. → {set, action, step}, or {recording: true} pub fn insert_stop(app: &mut VectorcraftApp, p: &Value) -> Result { if !p.is_object() { return Err("`params` must be an object".into()); } let (message, allow_continue) = stop_params(p)?; - let step = (STOP_STEP.to_string(), json!({"message": message, "allowContinue": allow_continue})); + insert(app, p, (STOP_STEP.to_string(), json!({"message": message, "allowContinue": allow_continue}))) +} + +/// The command that inserts a menu item's command as a step ([`insert_menu_item`]). +pub const INSERT_MENU_ITEM: &str = "ui.action.insertMenuItem"; + +/// `ui.action.insertMenuItem {set?, action?, step?, command, params?}`: inserts the command of a +/// menu item as a step, without running it. `command` and `params` (default: `{}`) are those of a +/// menu item that can be a step ([`crate::menus::insertable_items`]); the step plays as the item +/// runs. The place is as [`insert_stop`] takes it, and the step is selected as a stop is. A command +/// and params that no such item has, a param of another type, params that are not an object, or a +/// place [`insert_stop`] refuses is an error, and then nothing changes. Insert Menu Item's OK runs +/// this. → {set, action, step}, or {recording: true} +pub fn insert_menu_item(app: &mut VectorcraftApp, p: &Value) -> Result { + if !p.is_object() { + return Err("`params` must be an object".into()); + } + let command = p.get("command").and_then(Value::as_str).ok_or("command must be text")?; + let params = match p.get("params") { + None => json!({}), + Some(v) if v.is_object() => v.clone(), + Some(_) => return Err("`params` must be an object".into()), + }; + let items = crate::menus::insertable_items(app.session.prefs.font_names_in_english); + if !items.iter().any(|item| item.command == command && item.params == params) { + return Err("no menu item that can be inserted runs this command".into()); + } + insert(app, p, (command.to_string(), params)) +} + +/// Err when adding `step` to the recording in progress would give the action that Stop +/// Playing/Recording keeps more than [`files::MAX_ACTION_STEPS`] steps, or its set a file larger +/// than [`files::MAX_SET_FILE`], the most Load Actions… reads. +fn recording_room(app: &VectorcraftApp, step: &(String, Value)) -> Result<(), String> { + let Some((set, name, start)) = app.ui.recording.clone() else { return Err("no such action".into()) }; + let start = app.session.journal.held().unwrap_or(start); + let mut steps = app.session.journal_for_action(start); + let into = app.ui.recording_into; + let holder = into.and_then(|id| app.ui.action_sets.iter().position(|s| s.actions.iter().any(|a| a.id == id))).unwrap_or(set); + let Some(mut s) = app.ui.action_sets.get(holder).cloned() else { return Ok(()) }; + let at = match into.and_then(|id| s.actions.iter().position(|a| a.id == id)) { + Some(at) => at, + None => { + s.actions.push(Action::new(name, vec![])); + s.actions.len() - 1 + } + }; + if s.actions[at].steps.len() + steps.len() >= files::MAX_ACTION_STEPS { + return Err("the action already has 10,000 steps".into()); + } + steps.push(step.clone()); + s.actions[at].steps.extend(steps); + if files::write_set(&s).len() > files::MAX_SET_FILE { + return Err("the action set would be larger than 8 MiB".into()); + } + Ok(()) +} + +/// What Stop Playing/Recording adds to a set ([`recorded_into`]). +struct Recorded { + /// The set's action that the recording records into; None for the new action that the + /// recording adds. + into: Option, + /// The new action's name. + name: String, + /// The steps recorded so far. + steps: Vec<(String, Value)>, +} + +/// What Stop Playing/Recording adds to set `set`; None when the recording in progress adds nothing +/// to it. +fn recorded_into(app: &VectorcraftApp, set: usize) -> Option { + let (recording_set, name, start) = app.ui.recording.as_ref()?; + let into = match app.ui.recording_into { + Some(id) => Some(app.ui.action_sets.get(set)?.actions.iter().position(|a| a.id == id)?), + None if *recording_set == set => None, + None => return None, + }; + let steps = app.session.journal_for_action(app.session.journal.held().unwrap_or(*start)); + Some(Recorded { into, name: name.clone(), steps }) +} + +/// Puts `step` where params `p` say ([`insert_stop`]) → what [`insert_stop`] returns. When the +/// recording in progress adds steps to the set, the limits count them as Stop Playing/Recording +/// would leave the set. +fn insert(app: &mut VectorcraftApp, p: &Value, step: (String, Value)) -> Result { let index = |k: &str| p.get(k).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); if p.get("set").is_none() && p.get("action").is_none() && p.get("step").is_none() { if app.ui.recording.is_none() { return Err("no such action".into()); } + recording_room(app, &step)?; app.session.journal.push(step); return Ok(json!({"recording": true})); } let (set, at) = index("set").zip(index("action")).ok_or("no such action")?; - let action = app.ui.action_sets.get_mut(set).and_then(|s| s.actions.get_mut(at)).ok_or("no such action")?; + let recorded = recorded_into(app, set); + let pending = match &recorded { + Some(r) if r.into == Some(at) => r.steps.len(), + _ => 0, + }; + let s = app.ui.action_sets.get_mut(set).filter(|s| at < s.actions.len()).ok_or("no such action")?; + let action = &mut s.actions[at]; let after = match p.get("step") { None => action.steps.len(), Some(_) => index("step").filter(|&s| s < action.steps.len()).ok_or("no such action step")? + 1, }; + if action.steps.len() + pending >= files::MAX_ACTION_STEPS { + return Err("the action already has 10,000 steps".into()); + } + let excluded = action.excluded_steps.clone(); action.insert_step(after, step); let id = action.id; + let file_len = match recorded { + None => files::write_set(s).len(), + Some(Recorded { into, name, steps }) => { + let mut kept = s.clone(); + match into { + Some(into) => kept.actions[into].steps.extend(steps), + None => kept.actions.push(Action::new(name, steps)), + } + files::write_set(&kept).len() + } + }; + if file_len > files::MAX_SET_FILE { + let action = &mut s.actions[at]; + action.steps.remove(after); + action.excluded_steps = excluded; + return Err("the action set would be larger than 8 MiB".into()); + } app.ui.action_set = Some(set); app.ui.action_sets_selected = vec![set]; if let Some(ctx) = app.ui_ctx.clone() { @@ -922,8 +1036,8 @@ pub const DELETE_STEP: &str = "ui.action.deleteStep"; /// `ui.action.deleteStep {set, action, step}`: deletes step `step`, a stop or a command, of the /// action at index `action` of set `set`. The steps after it keep whether they are excluded, and -/// no step of that action stays selected. A Record Stop dialog open on that step closes, and one -/// open on a later step of the action follows it up. A missing or invalid index is an error, and +/// no step of that action stays selected. A Record Stop or Insert Menu Item dialog open on that step +/// closes, and one open on a later step of the action follows it up. A missing or invalid index is an error, and /// then nothing changes. Undo does not bring the step back. Delete Selection runs this for the /// selected step. → {set, action, step} pub fn delete_step(app: &mut VectorcraftApp, p: &Value) -> Result { @@ -943,7 +1057,7 @@ pub fn delete_step(app: &mut VectorcraftApp, p: &Value) -> Result .ui .dialog .as_ref() - .filter(|d| d.kind == crate::dialogs::action_stop::RECORD_KIND) + .filter(|d| holds_step(d)) .filter(|d| d.fields.get("set").and_then(number) == Some(set) && d.fields.get("action").and_then(number) == Some(at)) .and_then(|d| d.fields.get("step").and_then(number)); if held == Some(step) { @@ -1190,10 +1304,16 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result fn holds_set(d: &crate::state::Dialog) -> bool { d.kind == crate::dialogs::action_batch::KIND || d.kind == crate::dialogs::action_new::KIND - || d.kind == crate::dialogs::action_stop::RECORD_KIND + || holds_step(d) || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) } +/// Whether dialog `d` is a Record Stop or Insert Menu Item dialog, which holds the place of a new +/// step in its `set`, `action` and `step` fields. +fn holds_step(d: &crate::state::Dialog) -> bool { + d.kind == crate::dialogs::action_stop::RECORD_KIND || d.kind == crate::dialogs::action_insert_menu_item::KIND +} + /// The command that duplicates an action or an action set ([`duplicate`]). pub const DUPLICATE: &str = "ui.actionSet.duplicate"; @@ -1240,9 +1360,9 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { let Some(mut copy) = src.actions.get(a).map(Action::copy) else { return Err("no such action".into()) }; copy.name = format!("{} copy", copy.name); src.actions.insert(a + 1, copy); - // A Batch or Record Stop dialog open on a later action of the set follows it down. - if let Some(d) = - app.ui.dialog.as_mut().filter(|d| d.kind == crate::dialogs::action_batch::KIND || d.kind == crate::dialogs::action_stop::RECORD_KIND) + // A Batch, Record Stop or Insert Menu Item dialog open on a later action of the set follows it + // down. + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == crate::dialogs::action_batch::KIND || holds_step(d)) && d.fields.get("set").and_then(index) == Some(set) && let Some(da) = d.fields.get("action").and_then(index).filter(|&da| da > a) { @@ -1317,6 +1437,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let step = selected_step(app, ui.ctx(), selected); crate::dialogs::action_stop::open_record(app, if recording { None } else { selected }, step); } + if widgets::menu_item(ui, tl!("Insert Menu Item…"), recording || has, false) { + let step = selected_step(app, ui.ctx(), selected); + crate::dialogs::action_insert_menu_item::open(app, if recording { None } else { selected }, step); + } if widgets::menu_item(ui, tl!("Action Options…"), has, false) && let Some((s, a)) = selected { @@ -3963,6 +4087,253 @@ mod tests { assert!(app.ui.action_sets[0].actions.last().unwrap().steps.is_empty(), "the refused stop is not recorded"); } + #[test] + fn insert_menu_item_goes_after_the_given_step_or_at_the_end_runs_nothing_and_plays_as_the_menu_runs_it() { + let (mut app, x) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([0, 2]); + let doc = app.session.active().unwrap().doc.clone(); + let journal = app.session.journal.len(); + let r = app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "step": 0, "command": "object.group"})).unwrap(); + assert_eq!(r, json!({"set": 0, "action": 0, "step": 1})); + let r = app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": "type.changeCase", "params": {"case": "upper"}})).unwrap(); + assert_eq!(r, json!({"set": 0, "action": 0, "step": 4})); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc), "inserting runs nothing"); + assert_eq!(app.session.journal.len(), journal, "and records nothing"); + let action = &app.ui.action_sets[0].actions[0]; + let ids: Vec<&str> = action.steps.iter().map(|(c, _)| c.as_str()).collect(); + assert_eq!(ids, ["object.move", "object.group", "object.move", "object.move", "type.changeCase"]); + assert_eq!((&action.steps[1].1, &action.steps[4].1), (&json!({}), &json!({"case": "upper"}))); + assert_eq!(action.excluded_steps, BTreeSet::from([0, 3]), "the step excluded after the insertion point moved with it"); + + app.ui.action_sets[0].actions[0].excluded_steps.insert(4); + let before = undo_steps(&app); + let r = play(&mut app, 0, 0).unwrap(); + let results = r["results"].as_array().unwrap(); + assert_eq!(results.len(), 2, "the group and the included move play, and the excluded change of case does not: {r}"); + assert!(results[0]["id"].is_u64(), "the group step made a group: {r}"); + assert_eq!(undo_steps(&app), before + 1, "the action plays as one undo step"); + assert_eq!(x(&app), 2.0, "the move of 2 moved the group"); + } + + #[test] + fn an_inserted_menu_item_plays_step_by_step() { + let (mut app, x) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].steps.truncate(1); + app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "step": 0, "command": "object.group"})).unwrap(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + let rect = app.session.active().unwrap().selection.objects.first().copied(); + let before = undo_steps(&app); + let r = play(&mut app, 0, 0).unwrap(); + assert_eq!(r["pending"], json!(1), "the move ran, the group waits: {r}"); + play_out(&mut app); + assert_eq!(undo_steps(&app), before + 2, "each step its own undo step"); + assert_eq!(x(&app), 1.0); + let selected = app.session.active().unwrap().selection.objects.first().copied(); + assert!(selected.is_some() && selected != rect, "the group step ran and selected the new group"); + } + + #[test] + fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { + let (mut app, _) = app_with_three_moves(); + let place = |extra: Value| { + let mut p = json!({"set": 0, "action": 0}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p + }; + let none = "no menu item that can be inserted runs this command"; + for (params, want) in [ + (place(json!({})), "command must be text"), + (place(json!({"command": 5})), "command must be text"), + (place(json!({"command": "no.such.command"})), none), + // Undo, a File menu item, an item that asks for values first, the app's own commands and + // an action's own command. + (place(json!({"command": "edit.undo"})), none), + (place(json!({"command": "file.save"})), none), + (place(json!({"command": "object.move"})), none), + (place(json!({"command": "object.move", "params": {"dx": 1, "dy": 0}})), none), + (place(json!({"command": "view.zoomIn"})), none), + (place(json!({"command": INSERT_MENU_ITEM})), none), + (place(json!({"command": "edit.paste"})), none), + // Align, whose menu items add the Align To choice when clicked. + (place(json!({"command": "object.align", "params": {"horizontal": "left"}})), none), + // Image Trace, whose menu items trace off the UI thread with progress and Cancel. + (place(json!({"command": "imageTrace.make", "params": {"preset": "Default"}})), none), + (place(json!({"command": "imageTrace.makeAndExpand", "params": {"preset": "Default"}})), none), + // Pattern's Make and Edit Pattern, whose menu items open the Pattern Options panel. + (place(json!({"command": "object.pattern.make"})), none), + (place(json!({"command": "object.pattern.edit"})), none), + // Params that no menu item gives its command. + (place(json!({"command": "type.changeCase"})), none), + (place(json!({"command": "type.changeCase", "params": {"case": "middle"}})), none), + (place(json!({"command": "object.group", "params": {"ids": [1]}})), none), + (place(json!({"command": "object.group", "params": [1]})), "`params` must be an object"), + (place(json!({"command": "object.group", "params": null})), "`params` must be an object"), + (place(json!({"command": "object.group", "step": 3})), "no such action step"), + (place(json!({"command": "object.group", "step": null})), "no such action step"), + (json!({"command": "object.group"}), "no such action"), + (json!({"command": "object.group", "set": 0}), "no such action"), + (json!({"command": "object.group", "set": 0, "action": 1}), "no such action"), + (json!({"command": "object.group", "set": 1, "action": 0}), "no such action"), + (json!(5), "`params` must be an object"), + (json!(null), "`params` must be an object"), + ] { + assert_eq!(app.run(INSERT_MENU_ITEM, params.clone()).unwrap_err(), want, "{params}"); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "{params}"); + } + } + + /// A listed menu item runs from the menu what its step runs in playback: the click opens no + /// dialog, and it journals the item's own command with the item's own params. + #[test] + fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { + for item in crate::menus::insertable_items(false) { + let (mut app, _) = app_with_three_moves(); + let start = app.session.journal.len(); + crate::menus::invoke(&mut app, item.command, item.params.clone()); + assert!(app.ui.dialog.is_none(), "{item:?} opens a dialog"); + let ran = app.session.journal_for_action(start); + assert!(ran.iter().all(|(c, p)| c != item.command || *p == item.params), "{item:?} ran {ran:?}"); + } + } + + #[test] + fn insert_menu_item_goes_into_the_recording() { + let (mut app, _) = app_with_three_moves(); + app.run(START_RECORDING, json!({})).unwrap(); + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"command": "object.group"})).unwrap(), json!({"recording": true})); + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"command": "file.save"})).unwrap_err(), "no menu item that can be inserted runs this command"); + app.run(STOP_RECORDING, json!({})).unwrap(); + let recorded = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!(recorded.steps, [("object.group".to_string(), json!({}))]); + } + + /// An action stays one that Load Actions… reads back: a stop or a menu item that would give it + /// more than 10,000 steps, or its set's file more than 8 MiB, is refused, and the action keeps its + /// steps and exclusions as they were. + #[test] + fn inserted_steps_keep_an_action_set_that_load_actions_reads() { + let (mut app, _) = app_with_three_moves(); + let full = vec![("object.group".to_string(), json!({})); files::MAX_ACTION_STEPS]; + app.ui.action_sets[0].actions[0].steps = full; + let steps = "the action already has 10,000 steps"; + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": "object.group"})).unwrap_err(), steps); + assert_eq!(app.run(INSERT_STOP, json!({"set": 0, "action": 0, "step": 0})).unwrap_err(), steps); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), files::MAX_ACTION_STEPS); + app.ui.action_sets[0].actions[0].steps.pop(); + assert!(app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": "object.group"})).is_ok(), "the 10,000th step goes in"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions[0].steps.len(), files::MAX_ACTION_STEPS, "and loads again"); + + let pad = |n: usize| vec![("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)}))]; + app.ui.action_sets[0].actions[0].steps = pad(0); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([0, 7]); + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = pad(room - 8); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "step": 0, "command": "object.group"})).unwrap_err(), size); + assert_eq!(app.run(INSERT_STOP, json!({"set": 0, "action": 0})).unwrap_err(), size); + let action = &app.ui.action_sets[0].actions[0]; + assert_eq!((action.steps.len(), &action.excluded_steps), (1, &BTreeSet::from([0, 7])), "nothing changed"); + assert!(files::write_set(&app.ui.action_sets[0]).len() <= files::MAX_SET_FILE); + } + + /// The limits hold for a step inserted into the recording in progress too: they count the steps + /// recorded so far and, for New Action's recording, the action's own steps and its set. + #[test] + fn steps_inserted_into_a_recording_keep_an_action_set_that_load_actions_reads() { + let (mut app, _) = app_with_three_moves(); + app.run(START_RECORDING, json!({})).unwrap(); + app.run(INSERT_MENU_ITEM, json!({"command": "object.group"})).unwrap(); + for _ in 1..files::MAX_ACTION_STEPS - 1 { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + let steps = "the action already has 10,000 steps"; + assert_eq!(app.run(INSERT_STOP, json!({})).unwrap(), json!({"recording": true}), "the 10,000th step goes in"); + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"command": "object.group"})).unwrap_err(), steps); + assert_eq!(app.run(INSERT_STOP, json!({})).unwrap_err(), steps); + app.run(STOP_RECORDING, json!({})).unwrap(); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions.last().unwrap().steps.len(), files::MAX_ACTION_STEPS, "and loads again"); + + let (mut app, _) = app_with_three_moves(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + app.ui.action_sets[0].actions[0].steps = vec![pad(0)]; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.ui.action_sets[0].actions[0].steps = vec![pad(room - 8)]; + let into = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"command": "object.group"})).unwrap_err(), size); + assert_eq!(app.run(INSERT_STOP, json!({})).unwrap_err(), size); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 1, "nothing was recorded into the action"); + assert!(files::write_set(&app.ui.action_sets[0]).len() <= files::MAX_SET_FILE); + } + + /// A step put by its set and action into the action that the recording in progress records into + /// counts the steps recorded so far, which Stop Playing/Recording adds to that action. + #[test] + fn steps_inserted_into_the_action_being_recorded_into_count_the_recorded_steps() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions.push(Action::new("Other", vec![])); + let into = app.ui.action_sets[0].actions[0].id; + let stored = app.ui.action_sets[0].actions[0].steps.len(); + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + for _ in stored..files::MAX_ACTION_STEPS { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + let steps = "the action already has 10,000 steps"; + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": "object.group"})).unwrap_err(), steps); + assert_eq!(app.run(INSERT_STOP, json!({"set": 0, "action": 0})).unwrap_err(), steps); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), stored, "nothing was inserted"); + assert!(app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 1, "command": "object.group"})).is_ok(), "another action takes the step"); + app.run(STOP_RECORDING, json!({})).unwrap(); + let saved = files::write_set(&app.ui.action_sets[0]); + assert_eq!(files::read_set(&saved, "Test").unwrap().actions[0].steps.len(), files::MAX_ACTION_STEPS, "and loads again"); + + let (mut app, _) = app_with_three_moves(); + let pad = |n: usize| ("object.move".to_string(), json!({"dx": 1, "dy": 0, "pad": "x".repeat(n)})); + let into = app.ui.action_sets[0].actions[0].id; + let room = files::MAX_SET_FILE - files::write_set(&app.ui.action_sets[0]).len(); + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = Some(into); + app.session.journal.push(pad(room - 8)); + let size = "the action set would be larger than 8 MiB"; + assert_eq!(app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": "object.group"})).unwrap_err(), size); + assert_eq!(app.run(INSERT_STOP, json!({"set": 0, "action": 0})).unwrap_err(), size); + // Another action of the set counts them too, for a recording into an action and for a + // recording that adds a new action. + for into_first in [true, false] { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions.push(Action::new("Other", vec![])); + let first = app.ui.action_sets[0].actions[0].id; + app.run(START_RECORDING, json!({})).unwrap(); + app.ui.recording_into = into_first.then_some(first); + app.session.journal.push(pad(room - 8)); + let r = app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 1, "command": "object.group"})); + assert_eq!(r.unwrap_err(), size, "recording into the first action: {into_first}"); + assert!(app.ui.action_sets[0].actions[1].steps.is_empty(), "recording into the first action: {into_first}"); + } + } + + /// A step inserted from the menu saves and loads as the command and params it holds, with its + /// place and exclusion. + #[test] + fn an_inserted_menu_item_saves_and_loads() { + let (mut app, _) = app_with_three_moves(); + app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "step": 1, "command": "type.changeCase", "params": {"case": "title"}})).unwrap(); + app.ui.action_sets[0].actions[0].excluded_steps = BTreeSet::from([2]); + let loaded = files::read_set(&files::write_set(&app.ui.action_sets[0]), "Test").unwrap(); + let action = &loaded.actions[0]; + assert_eq!(action.steps, app.ui.action_sets[0].actions[0].steps); + assert_eq!(action.steps[2], ("type.changeCase".to_string(), json!({"case": "title"}))); + assert_eq!(action.excluded_steps, BTreeSet::from([2])); + } + #[test] fn delete_step_removes_one_step_and_moves_the_exclusions_up() { let (mut app, _) = app_with_a_stop(false); @@ -4004,6 +4375,22 @@ mod tests { assert_eq!(open_kind(&app), None, "deleting its step closes it"); } + #[test] + fn step_and_set_edits_keep_an_open_insert_menu_item_on_its_place() { + let (mut app, _) = app_with_three_moves(); + app.ui.action_sets[0].actions.insert(0, Action::new("First", vec![])); + crate::dialogs::action_insert_menu_item::open(&mut app, Some((0, 1)), Some(2)); + app.run(DUPLICATE, json!({"set": 0, "action": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["action"], json!(2), "a copied action above moves it down"); + app.run(DELETE_STEP, json!({"set": 0, "action": 2, "step": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["step"], json!(1), "a deleted step above moves it up"); + app.run(DELETE_STEP, json!({"set": 0, "action": 2, "step": 1})).unwrap(); + assert_eq!(open_kind(&app), None, "deleting its step closes it"); + crate::dialogs::action_insert_menu_item::open(&mut app, Some((0, 0)), None); + app.run(DELETE_SETS, json!({"sets": [0]})).unwrap(); + assert_eq!(open_kind(&app), None, "deleting its set closes it"); + } + /// Selects the first step of "Three Moves" by clicking its row, with the action open. fn click_first_step(ctx: &egui::Context, app: &mut VectorcraftApp) { use super::super::tests_appearance::{click, frame_events}; @@ -4474,6 +4861,58 @@ mod tests { assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3); } + /// The panel menu's Insert Menu Item… after the selected step: Find narrows the list, a click on + /// a row picks the item and runs nothing, Cancel inserts nothing, and OK inserts the pick after + /// the step. With nothing selected and nothing recording, the item is off. + #[test] + fn insert_menu_item_in_the_menu_picks_from_the_list_and_inserts_on_ok() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let (mut app, _) = app_with_three_moves(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let open = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Insert Menu Item…").map(|(_, r)| *r).expect("Insert Menu Item… in the menu"); + click(ctx, app, item.center(), menu); + }; + open(&ctx, &mut app); + assert_eq!(open_kind(&app), None, "nothing selected and nothing recording: the item is off"); + + click_first_step(&ctx, &mut app); + open(&ctx, &mut app); + let d = app.ui.dialog.as_ref().expect("Insert Menu Item… opens its dialog"); + assert_eq!(d.kind, crate::dialogs::action_insert_menu_item::KIND); + assert_eq!((&d.fields["set"], &d.fields["action"], &d.fields["step"]), (&json!(0), &json!(0), &json!(0))); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("object.ungroup")); + } + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::dialogs::show(app, ui.ctx()); + let mut texts = vec![]; + for _ in 0..3 { + texts = frame_events(&ctx, &mut app, vec![], draw); + } + assert!(!texts.iter().any(|(s, _)| s == "Object › Group"), "Find narrows the list: {texts:?}"); + let doc = app.session.active().unwrap().doc.clone(); + click(&ctx, &mut app, text_rect(&texts, "Object › Ungroup").center(), draw); + let d = app.ui.dialog.as_ref().expect("a pick keeps the dialog open"); + assert_eq!((d.str("command"), &d.fields["params"]), ("object.ungroup".to_string(), &json!({}))); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc), "a pick runs nothing"); + + crate::dialogs::cancel(&mut app); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "Cancel inserts nothing"); + + open(&ctx, &mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("command".into(), json!("object.ungroup")); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(open_kind(&app), None, "OK closes the dialog"); + let ids: Vec = app.ui.action_sets[0].actions[0].steps.iter().map(|(c, _)| c.clone()).collect(); + assert_eq!(ids, ["object.move", "object.ungroup", "object.move", "object.move"], "the pick goes after the selected step"); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), Some((app.ui.action_sets[0].actions[0].id, 1)), "and is selected"); + } + #[test] fn set_edits_keep_an_open_record_stop_on_its_action() { let mut app = app_with_sets(); diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index f7df78ee9b..2e1385a7d8 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -34,7 +34,7 @@ pub(super) const MAX_SET_FILE: usize = 8 << 20; const MAX_SET_ACTIONS: usize = 1000; /// The most steps [`read_set`] reads in one action. -const MAX_ACTION_STEPS: usize = 10_000; +pub(super) const MAX_ACTION_STEPS: usize = 10_000; /// The most left-out steps that Load Actions… lists for an action set another app saved. const MAX_SKIPPED: usize = 1000; diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index 0c322f0a05..82005595f0 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -210,7 +210,9 @@ fn has_key(app: &VectorcraftApp) -> bool { /// The first selected ruler guide while objects are selected too: the one Align to Key Object /// makes the key when there is no other object to be it. fn guide_for_key(app: &VectorcraftApp) -> Option { - app.session.active().filter(|st| !st.selection.is_empty()).and_then(|st| st.selection.guides.first().copied()) + let st = app.session.active().filter(|st| !st.selection.is_empty())?; + let first = st.selection.guides.first().copied()?; + vectorcraft_engine::cmd::guide_indexes(&st.doc, &[first]).first().copied() } /// The number of selected ruler guides, which Distribute spaces with the objects (#1597). @@ -231,11 +233,106 @@ fn align_to(app: &VectorcraftApp) -> AlignTo { if has_key(app) { AlignTo::Key } else { app.ui.align_to } } +/// The Align To choices of the Align panel and of the Control bar's Align To menu, in their order. +const ALIGN_TO: [AlignTo; 3] = [AlignTo::Selection, AlignTo::Key, AlignTo::Artboard]; + +/// The icon and the translated name of Align To choice `v`. +fn align_to_icon_name(v: AlignTo) -> (&'static str, &'static str) { + match v { + AlignTo::Selection => ("dc-alignto-selection", tl!("Align to Selection")), + AlignTo::Key => ("dc-alignto-key", tl!("Align to Key Object")), + AlignTo::Artboard => ("dc-alignto-artboard", tl!("Align to Artboard")), + } +} + +/// The Align To choice that the Align panel and the Control bar show chosen: Artboard while one +/// object is selected (the buttons then align it to the artboard), else [`align_to`]. +fn shown_align_to(app: &VectorcraftApp) -> AlignTo { + aligns_to(align_to(app), objects_aligned(app)) +} + +/// Whether Align To choice `v` can be chosen. Align to Key Object needs a key object or a key +/// guide, or something to make one of: two or more selected objects, or a guide selected with +/// objects. +fn can_choose(app: &VectorcraftApp, v: AlignTo) -> bool { + v != AlignTo::Key || selection_len(app) >= 2 || has_key(app) || guide_for_key(app).is_some() +} + +/// Chooses Align To `v`, as the Align panel's Align To buttons and the Control bar's Align To menu +/// do. Align to Key Object makes the topmost selected object the key object, unless there is one +/// already; with one object, a guide selected with it becomes the key. The stored choice stays as +/// it was, and Align To shows it again once the key is cleared. Align to Selection and Align to +/// Artboard store the choice and let go of the key object. +pub(crate) fn choose_align_to(app: &mut VectorcraftApp, v: AlignTo) { + if !can_choose(app, v) { + return; + } + if v == AlignTo::Key { + if !has_key(app) { + match (topmost(app).filter(|_| selection_len(app) >= 2), guide_for_key(app)) { + (Some(id), _) => app.run("select.key", json!({"id": id.0})).ok(), + (None, Some(g)) => app.run("select.key", json!({"guide": g})).ok(), + (None, None) => None, + }; + } + } else { + app.ui.align_to = v; + if has_key(app) { + app.run("select.key", json!({})).ok(); + } + } +} + +/// The width of the Control bar's Align To menu ([`align_to_menu`]) for buttons `size` points +/// square: the icon of the choice and the arrow after it. +pub(crate) fn align_to_menu_width(size: f32) -> f32 { + size + ALIGN_TO_ARROW +} + +/// The width of the arrow of the Control bar's Align To menu. +const ALIGN_TO_ARROW: f32 = 14.0; + +/// The Control bar's Align To menu, next to its Align buttons: the icon of the choice that the +/// Align panel's Align To shows ([`shown_align_to`]) and an arrow, `size` points tall. Its menu +/// lists Align to Selection, Align to Key Object and Align to Artboard with that choice checked, +/// and a pick chooses it as the Align panel does ([`choose_align_to`]). Align to Key Object is off +/// while no key object can be made. Screen readers get a combo box named "Align To:" whose value +/// is the choice. +pub(crate) fn align_to_menu(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) { + let t = crate::theme::Tokens::get(ui.ctx()); + let shown = shown_align_to(app); + let (icon, name) = align_to_icon_name(shown); + let (rect, resp) = ui.allocate_exact_size(egui::vec2(align_to_menu_width(size), size), egui::Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, egui::CornerRadius::same(5), t.hover); + } + let square = egui::Rect::from_min_size(rect.min, egui::vec2(size, size)); + crate::icons::paint(ui, icon, square.shrink((size * 0.2).round()), t.icon); + let arrow = egui::Rect::from_center_size(egui::pos2(square.right() + ALIGN_TO_ARROW / 2.0, rect.center().y), egui::vec2(10.0, 10.0)); + crate::icons::paint(ui, "chevron-down", arrow, t.text_dim); + resp.widget_info(|| egui::WidgetInfo { + current_text_value: Some(name.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), tl!("Align To:")) + }); + let resp = resp.on_hover_text(name); + let picked = egui::Popup::menu(&resp).show(|ui| { + let mut picked = None; + for v in ALIGN_TO { + if menu_item(ui, align_to_icon_name(v).1, can_choose(app, v), shown == v) { + picked = Some(v); + } + } + picked + }); + if let Some(v) = picked.and_then(|r| r.inner) { + choose_align_to(app, v); + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let n = selection_len(app); let guides = selected_guides(app); let can_align = n + guides >= 1; - let to = align_to(app); // `spacing` is the Distribute Spacing value. The Distribute Objects and Distribute Spacing // buttons send it while there is a key object or a key guide (#2143). let spacing = app.ui.align_spacing; @@ -297,36 +394,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.vertical(|ui| { widgets::subheader(ui, tl!("Align To:")); // With one object selected the buttons align it to the artboard, and Align To shows Artboard. - let shown = aligns_to(to, objects_aligned(app)); + let shown = shown_align_to(app); ui.horizontal(|ui| { - for (v, icon, tip) in [ - (AlignTo::Selection, "dc-alignto-selection", tl!("Align to Selection")), - (AlignTo::Key, "dc-alignto-key", tl!("Align to Key Object")), - (AlignTo::Artboard, "dc-alignto-artboard", tl!("Align to Artboard")), - ] { - // A key object is one of two or more selected objects, or a guide selected - // with objects. - let on = v != AlignTo::Key || n >= 2 || has_key(app) || guide_for_key(app).is_some(); - if widgets::icon_button_enabled(ui, icon, tl!(tip), shown == v, on, 28.0).clicked() { - if v == AlignTo::Key { - // The topmost selected object becomes the key object, unless - // there is one already. The Align To choice stays as it was, and - // Align To shows it again once the key is cleared. - // With one object, a guide selected with it becomes the key. - if !has_key(app) { - match (topmost(app).filter(|_| n >= 2), guide_for_key(app)) { - (Some(id), _) => app.run("select.key", json!({"id": id.0})).ok(), - (None, Some(g)) => app.run("select.key", json!({"guide": g})).ok(), - (None, None) => None, - }; - } - } else { - app.ui.align_to = v; - // Aligning to the selection or the artboard lets go of the key object. - if has_key(app) { - app.run("select.key", json!({})).ok(); - } - } + for v in ALIGN_TO { + let (icon, tip) = align_to_icon_name(v); + if widgets::icon_button_enabled(ui, icon, tip, shown == v, can_choose(app, v), 28.0).clicked() { + choose_align_to(app, v); } } }); diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index 76b7e3b60d..6cd9364cda 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -28,11 +28,13 @@ fn align_to_key_object_makes_a_selected_guide_the_key() { let ctx = egui::Context::default(); let ([_, key, _], left) = panel_buttons(&mut app, &ctx); click(&ctx, &mut app, key.center(), show); - assert_eq!(app.session.active().unwrap().selection.key_guide, Some(0), "{}", app.ui.status); + let st = app.session.active().unwrap(); + let key = st.selection.key_guide.map(|k| vectorcraft_engine::cmd::guide_indexes(&st.doc, &[k])); + assert_eq!(key, Some(vec![0]), "{}", app.ui.status); assert_eq!(align_to(&app), AlignTo::Key); click(&ctx, &mut app, left.center(), show); assert_eq!(left_edge(&app, &a), 120.0, "on the guide, not the artboard: {}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.guides[0].pos, 120.0); + assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].pos, 120.0); } /// A Shift-click that leaves the key object selected on its own lets the key go, and the align @@ -532,13 +534,13 @@ fn the_distribute_buttons_send_the_spacing_with_a_key_guide() { app.ui.align_spacing = 15.0; click(&ctx, &mut app, left.center(), show); assert_eq!(lefts(&app), [70.0, 85.0, 115.0], "15 pt apart, outward from the guide: {}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.guides[0].pos, 100.0, "the guide stays put"); + assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].pos, 100.0, "the guide stays put"); // Horizontal Distribute Space with 15: the object before the guide ends 15 pt before it, // the one after it starts 15 pt after it. click(&ctx, &mut app, space.center(), show); assert_eq!(sent(&app), ("object.distributeSpacing".to_string(), json!("key"), Some(json!(15.0)))); assert_eq!(lefts(&app), [10.0, 45.0, 115.0], "{}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.guides[0].pos, 100.0, "the guide stays put"); + assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].pos, 100.0, "the guide stays put"); } /// Three vertical ruler guides selected without objects: Align Objects buttons are on, and @@ -560,7 +562,7 @@ fn the_align_buttons_align_guides_selected_alone_to_artboard() { row.sort_by(|a, b| a.left().total_cmp(&b.left())); assert!(row[0].width() > 0.0, "Horizontal Align Left is enabled"); click(&ctx, &mut app, row[0].center(), show); - let pos = |app: &VectorcraftApp| app.session.active().unwrap().doc.guides.iter().map(|g| g.pos).collect::>(); + let pos = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::>(); assert_eq!(pos(&app), [0.0, 0.0, 0.0], "{}", app.ui.status); } @@ -585,7 +587,7 @@ fn the_distribute_buttons_space_guides_selected_alone() { assert_eq!(row.len(), 6, "the Distribute row"); // Its fifth button is Horizontal Distribute Center. click(&ctx, &mut app, row[4].center(), show); - let pos = |app: &VectorcraftApp| app.session.active().unwrap().doc.guides.iter().map(|g| g.pos).collect::>(); + let pos = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::>(); assert_eq!(pos(&app), [20.0, 100.0, 180.0], "{}", app.ui.status); app.run("edit.undo", json!({})).unwrap(); assert_eq!(pos(&app), [20.0, 50.0, 180.0], "one undo step"); diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 04f2719e76..0b661c8bcf 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -60,9 +60,11 @@ const NAME_FIELD_ROOM: f32 = 330.0; /// names in tooltips, when the bar is short of room) and, while the bar has room, the reference /// point the Transform panel also uses with the artboard's X and Y, and its W and H with the /// Constrain Width and Height Proportions link. Each control runs the command its Properties panel -/// or Transform panel counterpart runs. Returns false, and draws nothing, while another tool is in -/// use. -pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { +/// or Transform panel counterpart runs. With `options` false (the bar's panel menu has its Artboard +/// Options group off), the controls other than the Transform link and the fields are left out; with +/// `transform` false (its Transform group off), the Transform link and the fields are. Returns +/// false, and draws nothing, while another tool is in use. +pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, transform: bool) -> bool { if app.session.tool_id() != "artboard" { return false; } @@ -71,35 +73,43 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let i = selected(app, n); let Some(ab) = app.session.active().and_then(|d| d.doc.artboards.get(i)).cloned() else { return true }; let r = ab.rect; - super::properties::artboard_size_row(app, ui, i, r.width(), r.height()); - if widgets::icon_button(ui, "dc-new-item", tl!("New Artboard"), false, 24.0).clicked() { - add_new(app); + if options { + super::properties::artboard_size_row(app, ui, i, r.width(), r.height()); + if widgets::icon_button(ui, "dc-new-item", tl!("New Artboard"), false, 24.0).clicked() { + add_new(app); + } + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Artboard"), false, n > 1, 24.0).clicked() { + delete_selected(app); + } + ui.separator(); + // The field shows the name as it is (names are never translated). A new name is applied on Enter + // or a click elsewhere, and an empty field or Escape keeps the old one, as in the Properties panel. + ui.label(egui::RichText::new(tl!("Name:")).size(12.0).color(t.text)); + let width = if ui.available_width() < NAME_FIELD_ROOM { 100.0 } else { 120.0 }; + if let Some(name) = widgets::text_field_named(ui, ("cb-ab", "name"), Some(tl!("Name:")), Some(&ab.name), width, 1).filter(|n| !n.is_empty()) { + app.run("artboard.setProps", json!({"index": i, "name": name})).ok(); + } + if widgets::icon_button(ui, "dc-artboard-options", tl!("Artboard Options"), false, 24.0).clicked() { + app.run("tool.options", json!({"tool": "artboard"})).ok(); + } + if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards"), false, n > 1, 24.0).clicked() { + open_rearrange(app); + } + ui.separator(); } - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Artboard"), false, n > 1, 24.0).clicked() { - delete_selected(app); + if transform { + super::transform::link(app, ui); + ui.separator(); } - ui.separator(); - // The field shows the name as it is (names are never translated). A new name is applied on Enter - // or a click elsewhere, and an empty field or Escape keeps the old one, as in the Properties panel. - ui.label(egui::RichText::new(tl!("Name:")).size(12.0).color(t.text)); - let width = if ui.available_width() < NAME_FIELD_ROOM { 100.0 } else { 120.0 }; - if let Some(name) = widgets::text_field_named(ui, ("cb-ab", "name"), Some(tl!("Name:")), Some(&ab.name), width, 1).filter(|n| !n.is_empty()) { - app.run("artboard.setProps", json!({"index": i, "name": name})).ok(); + if options { + art_option_boxes(app, ui, ui.available_width() < ART_OPTIONS_WIDTH); } - if widgets::icon_button(ui, "dc-artboard-options", tl!("Artboard Options"), false, 24.0).clicked() { - app.run("tool.options", json!({"tool": "artboard"})).ok(); - } - if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards"), false, n > 1, 24.0).clicked() { - open_rearrange(app); - } - ui.separator(); - super::transform::link(app, ui); - ui.separator(); - art_option_boxes(app, ui, ui.available_width() < ART_OPTIONS_WIDTH); - if ui.available_width() < INLINE_FIELDS_WIDTH { + if !transform || ui.available_width() < INLINE_FIELDS_WIDTH { return true; } - ui.separator(); + if options { + ui.separator(); + } let units = app.session.general_unit(); let origin = app.ruler_origin(); let refi = super::transform::reference_index(ui); diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 23aab10159..f2be587642 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -382,6 +382,32 @@ fn paste_and_cut_with_the_artboard_tool_make_its_artboard_active() { assert_eq!(active(&app), (1, json!(1)), "Cut Artboard 3: Artboard 2"); } +/// With the Artboard tool selecting several artboards, Paste in Place, in Front and in Back put a +/// copy of the copied object on each, where it was on the artboard it was copied from; with one +/// selected, on the active one. +#[test] +fn in_place_pastes_put_a_copy_on_each_artboard_the_artboard_tool_selects() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 150, "artboards": 3})).unwrap(); + let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.origin()).collect(); + let r = app.run("shape.rectangle", json!({"x": boards[0].x + 10.0, "y": boards[0].y + 20.0, "width": 5, "height": 5})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.select_tool("artboard"); + let offset = vectorcraft_geom::Vec2::new(10.0, 20.0); + let pasted = |app: &mut VectorcraftApp, id: &str| -> Vec { + let r = app.run(id, json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + r["ids"].as_array().unwrap().iter().map(|i| doc.bounds_of(&[vectorcraft_doc::NodeId(i.as_u64().unwrap())], false).unwrap().origin()).collect() + }; + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + app.run("tool.setOption", json!({"key": "selected", "value": [2, 0]})).unwrap(); + assert_eq!(pasted(&mut app, id), [boards[0] + offset, boards[2] + offset], "{id}"); + app.run("tool.setOption", json!({"key": "selected", "value": [1]})).unwrap(); + assert_eq!(pasted(&mut app, id), [boards[1] + offset], "{id}: the active artboard"); + } +} + /// `tool.setOption` with the Artboard tool's `selected` or `active` makes the artboard the tool /// then has active the active one. #[test] diff --git a/crates/ui-egui/src/panels/blend.rs b/crates/ui-egui/src/panels/blend.rs index e258cfbc09..a41c2946c7 100644 --- a/crates/ui-egui/src/panels/blend.rs +++ b/crates/ui-egui/src/panels/blend.rs @@ -1,13 +1,17 @@ -//! Blend panel (Window → Blend): Make, the Spacing and Orientation of the selected blend (with no -//! blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, -//! Replace Spine, Expand and Release. Each control runs its Object → Blend command -//! (`object.blend.make`, `object.blend.options` and the others), so a change of the selected -//! blend's spacing or orientation shows on the canvas at once as one undo step. Make is dimmed -//! until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two -//! or more objects are selected, and the other buttons are dimmed until a blend is selected. +//! Blend panel (Window → Blend): Make, Create Spine (whether new blends get a spine), the Spacing +//! and Orientation of the selected blend (with no blend selected, the options new blends start +//! with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release. Each control +//! runs its Object → Blend command (`object.blend.make`, `object.blend.createSpine`, +//! `object.blend.options` and the others), so a change of the selected blend's spacing or +//! orientation shows on the canvas at once as one undo step. Make is dimmed until two or more +//! objects are selected. Create Spine is always available. Spacing and Orientation are dimmed until +//! a blend or two or more objects are selected, and the other buttons are dimmed until a blend is +//! selected. Easing and Reverse Spine are dimmed for a blend made without a spine. use egui::Ui; use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_doc::live::BlendSpineMode; use super::selection_len; use crate::VectorcraftApp; @@ -38,10 +42,18 @@ fn buttons(app: &mut VectorcraftApp, ui: &mut Ui, row: &[(&str, &str)]) { }); } -/// Can `cmd` run on the selection? Make needs two or more objects, and the other commands need a -/// selected blend. +/// Can `cmd` run on the selection? Make needs two or more objects, the other commands need a +/// selected blend, and Reverse Spine needs every selected blend to have a spine. fn available(app: &VectorcraftApp, cmd: &str) -> bool { - crate::menus::enabled(app, cmd) && (cmd != "object.blend.make" || selection_len(app) >= 2) + crate::menus::enabled(app, cmd) + && (cmd != "object.blend.make" || selection_len(app) >= 2) + && (cmd != "object.blend.reverseSpine" || !selects_blend_without_spine(app)) +} + +/// Is a blend made without a spine selected? +fn selects_blend_without_spine(app: &VectorcraftApp) -> bool { + let Ok(st) = app.session.doc() else { return false }; + st.selection.objects.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) } /// `object.blend.options` parameters for spacing mode `mode`, with the step count and distance @@ -95,8 +107,9 @@ fn settings(app: &mut VectorcraftApp, ui: &mut Ui) { } }); let selected = info["target"] == "blend"; - // Position easing needs a spine to run along: a replaced one, or Align to Path. - let spined = info["spine"]["explicit"] == true || info["orientation"] == "path"; + // Position easing needs a spine to run along: a replaced one, or Align to Path. A blend made + // without a spine has none. + let spined = info["hasSpine"] != false && (info["spine"]["explicit"] == true || info["orientation"] == "path"); ui.add_enabled_ui(selected && spined, |ui| { let modes = ["easeIn", "easeOut", "easeInOut", "easeOutIn"]; let labels = [tl!("Ease In"), tl!("Ease Out"), tl!("Ease In Out"), tl!("Ease Out In")]; @@ -129,9 +142,30 @@ fn settings(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Create Spine: whether new blends get a spine. It shows the setting new blends take, whatever is +/// selected, and a change runs `object.blend.createSpine`; blends already made keep theirs. +fn create_spine(app: &mut VectorcraftApp, ui: &mut Ui) { + let current = app.session.prefs.blend_options.unwrap_or_default().create_spine; + let modes = BlendSpineMode::ALL; + let labels = [tl!("Auto"), tl!("Always"), tl!("Never")]; + let shown = modes.iter().position(|m| *m == current).and_then(|i| labels.get(i)).copied().unwrap_or(labels[0]); + let mut change = None; + widgets::label_row(ui, tl!("Create Spine:"), LABEL_W, |ui| { + if let Some(mode) = + widgets::dropdown(ui, "blend-panel-create-spine", shown, &labels, ui.available_width().max(FIELD_W)).and_then(|i| modes.get(i)) + { + change = Some(*mode); + } + }); + if let Some(mode) = change { + app.run("object.blend.createSpine", json!({ "mode": mode.id() })).ok(); + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let blend = crate::menus::enabled(app, "object.blend.release"); buttons(app, ui, &[(tl!("Make"), "object.blend.make")]); + create_spine(app, ui); widgets::divider(ui); ui.add_enabled_ui(blend || selection_len(app) >= 2, |ui| settings(app, ui)); widgets::label_row(ui, tl!("Direction:"), LABEL_W, |ui| buttons(app, ui, &[(tl!("Reverse Front to Back"), "object.blend.reverseFrontToBack")])); diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index a282ff9973..8f29c70475 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -2,7 +2,9 @@ //! applies it to the selected paths (and makes it the Paintbrush's current brush); double-clicking //! one opens its Brush Options. Shift-click selects a range of brushes, Cmd/Ctrl-click adds or //! removes one, and the panel menu's Select All Unused selects the brushes no stroke paints with, -//! for Delete Brush and Duplicate Brush. Brush libraries open in library panels +//! for Delete Brush and Duplicate Brush. A scatter, art or pattern brush dragged onto an empty part +//! of the canvas places a copy of its art there, and art from the canvas Alt-dragged (Option-dragged +//! on macOS) onto such a brush replaces its art. Brush libraries open in library panels //! ([`BrushLibraries`]). use std::cell::RefCell; @@ -269,6 +271,22 @@ fn reorder_drop( } } +/// Art dragged off the canvas and held over the tile or row `resp` of a scatter, art or pattern +/// brush `name` (of type `ty`) with Alt (Option on macOS) held: the tile is outlined, and released +/// there it sets `replaced` to the brush and the art's ids, whose art then replaces the brush's. +/// Without Alt, or on another type of brush, the drop is left to the list, which opens New Brush. +fn replace_drop(ui: &Ui, resp: &egui::Response, name: &str, ty: &str, replaced: &mut Option<(String, Vec)>) { + if !matches!(ty, "scatter" | "art" | "pattern") || !ui.input(|i| i.modifiers.alt) { + return; + } + let Some(drag) = resp.dnd_hover_payload::() else { return }; + let PanelDrag::Art(ids) = &*drag else { return }; + ui.painter().rect_stroke(resp.rect, 0.0, egui::Stroke::new(1.5, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside); + if resp.dnd_release_payload::().is_some() { + *replaced = Some((name.to_string(), ids.iter().map(|id| id.0).collect())); + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let (list, current) = brushes(app); @@ -284,6 +302,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut clicked: Option<(String, egui::Modifiers)> = None; let mut options: Option = None; let mut moved: Option = None; + let mut replaced: Option<(String, Vec)> = None; let list_rect = widgets::list_box(ui, |ui| { ui.set_min_height(110.0); ui.set_width(ui.available_width()); @@ -346,6 +365,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for (i, (name, _)) in group.into_iter().enumerate() { let resp = row(ui, name, vec2(ui.available_width(), 26.0), true); reorder_drop(ui, &resp, &list, (name, ty, i), true, &mut moved); + replace_drop(ui, &resp, name, ty, &mut replaced); pick(resp, name); } } else { @@ -353,6 +373,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for (i, (name, _)) in group.into_iter().enumerate() { let resp = row(ui, name, vec2(64.0, 28.0), false); reorder_drop(ui, &resp, &list, (name, ty, i), false, &mut moved); + replace_drop(ui, &resp, name, ty, &mut replaced); pick(resp, name); } }); @@ -361,6 +382,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.min_rect() }); + // Art Alt-dragged onto a scatter, art or pattern brush replaces its art, asking first when + // strokes use the brush. + if let Some((name, ids)) = replaced { + crate::dialogs::brush_replace_art::replace(app, &name, &ids); + } // Art dragged off the canvas and dropped on the list opens New Brush for that art, as the New // Brush button opens it for the selection; a brush library's brush dropped there is added. let zone = ui.interact(list_rect, ui.scope_id().with("brushes-drop"), Sense::hover()); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index e4c5b9d764..fcab4373ce 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -461,6 +461,54 @@ fn art_dropped_on_the_panel_becomes_an_art_brush_and_a_brush_drags_out() { assert!(matches!(drag.as_deref(), Some(PanelDrag::Brush { name, def }) if *name == after[0].0 && def["name"] == json!(name)), "{drag:?}"); } +/// Art dragged off the canvas and released on a scatter, art or pattern brush with Alt held +/// replaces that brush's art (no stroke uses it, so nothing asks); without Alt, or on a +/// calligraphic brush, the list opens New Brush as before. +#[test] +fn art_alt_dropped_on_a_brush_with_art_replaces_its_art() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 12})).unwrap()["id"].as_u64().unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_with(&ctx, &mut app, vec![], egui::Modifiers::NONE, 0.0, show); + let tiles: Vec = clickable(&out).into_iter().map(|c| c.1).filter(|r| r.width() == 64.0).collect(); + assert_eq!(shown(&brushes(&mut app).0, &[])[3], "Dots"); + let dots = app.run("brush.get", json!({"name": "Dots"})).unwrap(); + let drop = |app: &mut VectorcraftApp, at: Pos2, modifiers: egui::Modifiers, time: f64| { + egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![NodeId(id)])); + frame_with(&ctx, app, vec![egui::Event::PointerMoved(at)], modifiers, time, show); + frame_with(&ctx, app, vec![button(at, false)], modifiers, time + 0.1, show); + }; + // Without Alt: New Brush, and Dots stays as it was. + drop(&mut app, tiles[3].center(), egui::Modifiers::NONE, 1.0); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::new_brush::KIND)); + app.ui.dialog = None; + // Alt on a calligraphic or a bristle brush: New Brush too. + let list = brushes(&mut app).0; + let names = shown(&list, &[]); + let at = |name: &str| tiles[names.iter().position(|n| *n == name).unwrap()].center(); + for (i, name) in ["3 pt. Round", "Bristle Round"].into_iter().enumerate() { + let lib = app.run("brush.list", json!({})).unwrap(); + drop(&mut app, at(name), egui::Modifiers::ALT, 2.0 + i as f64); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::new_brush::KIND), "{name}"); + app.ui.dialog = None; + assert_eq!(app.run("brush.list", json!({})).unwrap(), lib, "{name}"); + } + assert_eq!(app.run("brush.get", json!({"name": "Dots"})).unwrap(), dots); + // Alt on Dots (scatter), Arrow (art) and Chain (pattern, its side tile): the rectangle is its + // art now, in one undo step each. + for (i, (name, key)) in [("Dots", "art"), ("Arrow", "art"), ("Chain", "side")].into_iter().enumerate() { + let steps = app.session.active().unwrap().history.undo.len(); + drop(&mut app, at(name), egui::Modifiers::ALT, 4.0 + i as f64); + assert!(app.ui.dialog.is_none(), "no stroke uses {name}: nothing asks"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{name}"); + let art: vectorcraft_doc::Node = serde_json::from_value(app.run("brush.get", json!({"name": name})).unwrap()[key].clone()).unwrap(); + let b = art.geometric_bounds().unwrap(); + assert!((b.width() - 30.0).abs() < 1e-6 && (b.height() - 12.0).abs() < 1e-6, "{name}: {b:?}"); + } +} + /// A brush dragged onto the left half of another brush of its type goes before it, with a bar /// marking the slot while it is held there, as one undo step; dropped on a brush of another /// type, it stays where it is and the status bar says why. diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 5f2f96a8cc..2f834a272c 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -266,8 +266,9 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { /// Set the Kerning field's `value` (a number, "auto", or "optical"). At a caret in text the Type tool edits /// it is the pair kerning after the character before the caret, as Alt+←/→ steps it -/// (`type.step`); nowhere to set at the start of the text. Else it is a character attribute like -/// the others: the selected range, or all the text. +/// (`type.step`), or at the start of a line the space before the character after it, where Auto +/// and Optical set no space (#5111); nowhere to set at an empty line's start. Else it is a +/// character attribute like the others: the selected range, or all the text. fn set_kerning(app: &mut VectorcraftApp, value: Value) { let Some((id, a, b)) = text_editing(app) else { format(app, json!({"kerning": value})); @@ -278,15 +279,18 @@ fn set_kerning(app: &mut VectorcraftApp, value: Value) { return; } let Some(NodeKind::Text(t)) = app.session.active().and_then(|st| st.doc.node(id)).map(|n| &n.kind) else { return }; - let start = vectorcraft_text::edit::prev_char(&t.plain_text(), a); - if start >= a { - return; - } + let Some((target, before)) = vectorcraft_text::edit::caret_kerning_target(&t.plain_text(), a) else { return }; end_typing(app); - app.run("text.setRangeStyle", json!({"id": id.0, "start": start, "end": a, "kerning": value})).ok(); + let params = if before { + json!({"id": id.0, "start": target.start, "end": target.end, "kerningBefore": value.as_f64().unwrap_or(0.0)}) + } else { + json!({"id": id.0, "start": target.start, "end": target.end, "kerning": value}) + }; + app.run("text.setRangeStyle", params).ok(); } -/// The pair before the caret, in 1/1000 em, using the layout the canvas draws. +/// The kerning at the caret, in 1/1000 em, using the layout the canvas draws: the pair before it, +/// or at the start of a line the space before the character after it. fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> { let (id, a, b) = text_editing(app)?; if a != b { @@ -294,11 +298,12 @@ fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> { } let NodeKind::Text(t) = &app.session.active()?.doc.node(id)?.kind else { return None }; let text = t.plain_text(); - let start = vectorcraft_text::edit::prev_char(&text, a); - if start >= a { - return None; - } + let (target, before) = vectorcraft_text::edit::caret_kerning_target(&text, a)?; + let start = target.start; let style = vectorcraft_text::edit::style_at(&t.runs, start + 1); + if before { + return Some((style.kerning_before, false)); + } if let Some(v) = style.kerning { return Some((v, false)); } diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index e58ca56f66..4e13f629a5 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -12,7 +12,10 @@ //! the inactive proxy when Alt is also held; //! Shift-dragging a slider moves the others in tandem; RGB and HSB show the out-of-gamut warning; //! Hide Options leaves just the proxy and the spectrum (the app keeps it between sessions too). -//! `ui.colorPanel` picks a mode and shows or hides the options as the panel menu does. +//! Unchecking Show Recent Colors hides the Recent Colors row while applied colors still join the +//! list (the app keeps it between sessions too). +//! `ui.colorPanel` picks a mode, shows or hides the options and checks or unchecks Show Recent +//! Colors as the panel menu does. use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::{Value, json}; @@ -287,6 +290,14 @@ pub fn deserialize_hide_options<'de, D: serde::Deserializer<'de>>(d: D) -> Resul Ok(v.as_bool().unwrap_or_default()) } +/// Serde reader for the saved Show Recent Colors ([`crate::UiState::color_show_recent_colors`]): +/// `false` hides the row and any other value shows it, so an unknown value doesn't lose the rest +/// of the preferences. +pub fn deserialize_show_recent_colors<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_bool().unwrap_or(true)) +} + /// The mode the panel shows `color` in: with nothing selected (the defaults for new art) the mode /// picked last, which the app keeps between sessions, else [`display_mode`]. fn shown_mode(app: &VectorcraftApp, color: Option<&Color>) -> Mode { @@ -511,16 +522,18 @@ fn recolor(app: &mut VectorcraftApp, ui: &Ui, tgt: &Target, invert: bool, behind } } -/// `ui.colorPanel {mode?, options?}`: pick a mode as the panel menu does ([`set_mode`]), and Show -/// Options (true) or Hide Options (false). → {mode, options, shown}: the mode picked last (null: -/// none yet), whether the options show, and the mode the panel shows the color in (`tint` for a -/// tint of a global or spot swatch). +/// `ui.colorPanel {mode?, options?, recentColors?}`: pick a mode as the panel menu does +/// ([`set_mode`]), Show Options (true) or Hide Options (false), and check (true) or uncheck +/// (false) Show Recent Colors. → {mode, options, recentColors, shown}: the mode picked last (null: +/// none yet), whether the options show, whether Show Recent Colors is checked, and the mode the +/// panel shows the color in (`tint` for a tint of a global or spot swatch). pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { let mode = match p.get("mode") { None | Some(Value::Null) => None, Some(v) => Some(menu_mode(v).ok_or("`mode` must be grayscale, rgb, hsb, cmyk or websafe")?), }; let options = crate::menus::opt_bool(p, "options")?; + let recent = crate::menus::opt_bool(p, "recentColors")?; let (fill, stroke) = app.session.proxy_mixed(); let mixed = if app.session.fill_active { fill } else { stroke }; if let Some(m) = mode { @@ -529,12 +542,20 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result json!("tint"), None => json!(shown_mode(app, tgt.color().as_ref())), }; - Ok(json!({"mode": app.ui.color_mode, "options": !app.ui.color_hide_options, "shown": shown})) + Ok(json!({ + "mode": app.ui.color_mode, + "options": !app.ui.color_hide_options, + "recentColors": app.ui.color_show_recent_colors, + "shown": shown, + })) } /// Tint mode's rows: the swatch's chip and name, and the T slider and field. Returns a new tint @@ -626,8 +647,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (Some(c), _) => components(mode, &c), (None, _) => vec![0.0; mode.labels().len()], }; - let recent = super::recent_colors_row(app, ui); - widgets::divider(ui); + // Show Recent Colors draws the Recent Colors row; the Swatches panel's row does not read it. + let mut recent = None; + if app.ui.color_show_recent_colors { + recent = super::recent_colors_row(app, ui); + widgets::divider(ui); + } // An edit of the active colour with its displayed components (`new`), or a colour clicked with // Alt held for the inactive proxy (`behind`). let mut new: Option<(Color, Live, Vec)> = None; @@ -770,6 +795,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, if hidden { tl!("Show Options") } else { tl!("Hide Options") }, true, false) { command(app, &json!({ "options": hidden })).ok(); } + let recent = app.ui.color_show_recent_colors; + if menu_item(ui, tl!("Show Recent Colors"), true, recent) { + command(app, &json!({ "recentColors": !recent })).ok(); + } ui.separator(); let tgt = target(app, ui); let color = tgt.color(); diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 9f9b3c1dd7..36acc60e4a 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -599,6 +599,83 @@ fn hide_options_comes_back_after_a_restart() { } } +/// The panel menu's Show Recent Colors hides the Recent Colors row and shows it again. Applied +/// colors still join the list while the row is hidden, Hide Options hides the row either way, and +/// the Swatches panel keeps its own row. +#[test] +fn show_recent_colors_hides_and_shows_the_row() { + let mut app = app(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let none = egui::Modifiers::NONE; + // The first recent chip's rect and the panel's height. The second frame's answer counts, since + // egui also answers for a widget the frame before drew. + let chip = |app: &mut VectorcraftApp| { + frame_with(app, &ctx, vec![], none, ("recent", 0usize)); + frame_with(app, &ctx, vec![], none, ("recent", 0usize)) + }; + let (shown, full) = chip(&mut app); + assert!(shown.is_some(), "the row shows by default"); + // The item is checked while the row shows. + click_menu_item(&mut app, &ctx, "✓ Show Recent Colors"); + assert!(!app.ui.color_show_recent_colors); + let (hidden, short) = chip(&mut app); + assert!(hidden.is_none() && short < full, "the row is hidden: {short} / {full}"); + // A color applied while the row is hidden still joins the list. + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + assert_eq!(app.session.recent_colors.first().map(|c| c.to_hex()).as_deref(), Some("#00ff00")); + // The Swatches panel keeps its row (drawn in a context of its own, whose chip ids the Color + // panel's would share). + let mut swatch_chip = None; + let screen_rect = Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(280.0, 700.0))); + let swatches = egui::Context::default(); + let mut out = swatches.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| { + crate::panels::swatches::show(&mut app, ui); + swatch_chip = swatches.read_response(ui.scope_id().with(("recent", 0usize))).map(|r| r.rect); + }); + out.textures_delta.clear(); + assert!(swatch_chip.is_some(), "the Swatches panel still draws its recent colors"); + // Show Options leaves the row hidden, and Hide Options hides it with the row checked too. + app.run("ui.colorPanel", json!({"options": false})).unwrap(); + app.run("ui.colorPanel", json!({"options": true})).unwrap(); + assert!(chip(&mut app).0.is_none(), "Show Options keeps Show Recent Colors unchecked"); + click_menu_item(&mut app, &ctx, "Show Recent Colors"); + assert!(chip(&mut app).0.is_some(), "checking the item shows the row again"); + assert_eq!(app.run("ui.colorPanel", json!({"options": false})).unwrap()["recentColors"], true); + assert!(chip(&mut app).0.is_none(), "Hide Options hides the row"); + assert!(app.ui.color_show_recent_colors, "Hide Options leaves Show Recent Colors checked"); + let r = app.run("ui.colorPanel", json!({"options": true, "recentColors": false})).unwrap(); + assert_eq!((&r["options"], &r["recentColors"]), (&json!(true), &json!(false))); + assert!(chip(&mut app).0.is_none()); + app.run("ui.colorPanel", json!({"recentColors": true})).unwrap(); + assert_eq!(chip(&mut app).1, full, "the panel is as tall as before"); +} + +/// Show Recent Colors is kept with the UI state, which the app saves with its preferences. A saved +/// state without it, or with a value that isn't true or false, reads as checked, and the rest of the +/// state still loads. A value that isn't true or false in the command answers an error and changes +/// nothing. +#[test] +fn show_recent_colors_comes_back_after_a_restart() { + let mut app = app(); + app.run("ui.colorPanel", json!({"recentColors": false})).unwrap(); + let saved: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert!(!saved.color_show_recent_colors); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_show_recent_colors"], false); + let old: crate::UiState = serde_json::from_value(json!({"place_link": false})).unwrap(); + assert!(old.color_show_recent_colors, "a state saved before the setting existed shows the row"); + for v in [json!(7), json!("hide"), json!({}), Value::Null] { + let ui: crate::UiState = serde_json::from_value(json!({"color_show_recent_colors": v, "place_link": false})).unwrap(); + assert_eq!((ui.color_show_recent_colors, ui.place_link), (true, false), "{v}"); + } + for v in [json!("no"), json!(0), json!([])] { + let e = app.run("ui.colorPanel", json!({"mode": "cmyk", "options": false, "recentColors": v})).unwrap_err(); + assert_eq!(e, "`recentColors` must be true or false", "{v}"); + } + assert_eq!((app.ui.color_mode, app.ui.color_hide_options, app.ui.color_show_recent_colors), (None, false, false)); +} + /// `ui.colorPanel {mode}` picks a mode as the panel menu does: HSB shows an RGB fill as H, S and /// B, and CMYK converts it as one undo step. #[test] @@ -607,7 +684,7 @@ fn ui_color_panel_picks_a_mode_as_the_menu_does() { let ctx = egui::Context::default(); app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); let r = app.run("ui.colorPanel", json!({"mode": "hsb"})).unwrap(); - assert_eq!(r, json!({"mode": "hsb", "options": true, "shown": "hsb"})); + assert_eq!(r, json!({"mode": "hsb", "options": true, "recentColors": true, "shown": "hsb"})); assert_eq!(slider_labels(&mut app, &ctx), ["H", "S", "B"]); assert_eq!(crate::control::inspect(&app, &ctx)["ui"]["color_mode"], "hsb"); assert_eq!(paints_hex(&app).0, "#336699", "HSB keeps the RGB color"); @@ -617,7 +694,7 @@ fn ui_color_panel_picks_a_mode_as_the_menu_does() { assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Rgb { .. })), "undo restores it"); assert_eq!(paints_hex(&app).0, "#336699"); // `{}` reads the settings: CMYK stays picked, and the RGB fill shows in its own model. - assert_eq!(app.run("ui.colorPanel", json!({})).unwrap(), json!({"mode": "cmyk", "options": true, "shown": "rgb"})); + assert_eq!(app.run("ui.colorPanel", json!({})).unwrap(), json!({"mode": "cmyk", "options": true, "recentColors": true, "shown": "rgb"})); // A tint of a global swatch shows Tint mode. app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true})).unwrap(); app.run("paint.setFill", json!({"swatch": "Ink", "tint": 50})).unwrap(); diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index bc362fb576..eae559dff5 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -86,7 +86,7 @@ fn shown(app: &mut VectorcraftApp, ui: &Ui, opts: &CssOptions, all: bool) -> Opt let (id, scope) = if all { ("css.generate", "all") } else { ("css.selection", "selection") }; let out = app.session.execute(id, ¶ms(opts, scope)).unwrap_or_default(); let rules: Vec<&str> = out["rules"].as_array().into_iter().flatten().filter_map(|r| r["css"].as_str()).collect(); - let warnings = out["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + let warnings = io::notes_of(&out); let job = (!rules.is_empty()) .then(|| Arc::new(highlight(rules.get(..MAX_SHOWN).unwrap_or(&rules), &t, egui::TextStyle::Monospace.resolve(ui.style())))); let skipped = out["skipped"].as_u64().unwrap_or(0); @@ -204,13 +204,14 @@ pub(crate) fn export_file(app: &mut VectorcraftApp, p: &Value) -> Result = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + // The status bar shows the warnings as Export As shows them. + let warnings = io::notes_of(&r); let what = &path; - app.status(match warnings.first() { + let status = match warnings.first() { Some(first) => io::exported_with_notes(what, warnings.len(), first), None => format!("Exported {path}"), - }); + }; + io::show_with_notes(app, status, warnings); Ok(json!({ "path": path, "rules": r["rules"], "images": images, "warnings": r["warnings"] })) } diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index f6becb3911..4d6bf05ec1 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -1,6 +1,6 @@ //! Document Info panel: the document's setup and what it contains (objects by kind, graphic -//! styles, brushes, spot colors, patterns, gradients, symbols, fonts and their files, linked and embedded -//! images, repeat objects), for the whole document or the selection only. The flyout picks one category (or all) +//! styles, brushes, spot colors, objects painted with patterns and with gradients, symbols, fonts and their files, +//! linked and embedded images, repeat objects), for the whole document or the selection only. The flyout picks one category (or all) //! and saves the text report (`docInfo.save`, the report File → Package writes too). use egui::Ui; @@ -191,9 +191,20 @@ mod tests { menu_text.contains("Font Details") && menu_text.contains("Brushes") && menu_text.contains("Repeat Objects") + && menu_text.contains("Gradient Objects") && menu_text.contains("Save…"), "{menu_text}" ); + // Gradient Objects lists the objects painted with a gradient by name. + let r = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + let ramp = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + app.session.execute("paint.setFill", &json!({"ids": [r], "gradient": ramp})).unwrap(); + app.session.execute("layer.setProps", &json!({"id": r, "name": "Glow"})).unwrap(); + let gradients = crate::tests_labels::painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), "docinfo-category", "gradients".to_string()); + show(app, ui); + }); + assert!(gradients.contains("Gradient Objects (1)") && gradients.contains("Glow") && gradients.contains("Radial gradient"), "{gradients}"); let filtered = crate::tests_labels::painted_text(&mut app, |app, ui| { set_pstate(ui.ctx(), "docinfo-category", "fonts".to_string()); show(app, ui); @@ -210,6 +221,7 @@ mod tests { assert_eq!(r["path"], "/tmp/info.txt"); let report = String::from_utf8(written.borrow().clone()).unwrap(); assert!(report.starts_with("Document Info: ") && report.contains("\nFONT DETAILS\n") && report.contains("\nREPEAT OBJECTS\n"), "{report}"); + assert!(report.contains("\nGRADIENT OBJECTS\nGlow: Radial gradient\n"), "{report}"); } /// The report the panel menu's Save… writes with category `category` shown ("" for All diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 07744bf1b6..500649b7ed 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -124,8 +124,8 @@ fn dragged_stops(origin: &[GradientStop], i: usize, offset: f32, copy: bool, ove // ---------- shared edits ---------- -/// The Type row: Linear, Radial and Freeform for the paint behind the active proxy (one of them -/// lit when it is a gradient). The Gradient panel's and the Properties panel's. +/// The Type row: Linear, Radial, Conic, Diamond and Freeform for the paint behind the active +/// proxy (one of them lit when it is a gradient). The Gradient panel's and the Properties panel's. pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) { let kind = current(app).map(|g| g.gradient.kind); ui.horizontal(|ui| { @@ -133,6 +133,8 @@ pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) { for (k, icon, tip) in [ (GradientKind::Linear, "dc-grad-linear", tl!("Linear Gradient")), (GradientKind::Radial, "dc-grad-radial", tl!("Radial Gradient")), + (GradientKind::Conic, "dc-grad-conic", tl!("Conic Gradient")), + (GradientKind::Diamond, "dc-grad-diamond", tl!("Diamond Gradient")), (GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")), ] { if widgets::icon_button(ui, icon, tip, kind == Some(k), 24.0).clicked() { @@ -344,17 +346,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { edit(app, json!({"reverse": true}), Live::Released); } }); - let radial = kind == GradientKind::Radial && placed; + let radial = kind.is_centered() && placed; ui.horizontal(|ui| { icons::icon(ui, "scaling", 15.0, if radial { t.icon } else { t.text_disabled }).on_hover_text(tl!("Aspect Ratio")); - let asp = g.geom.map_or(100.0, |x| (x.aspect * 1000.0).round() / 10.0); + // A mirrored conic's negative aspect shows as its size; an edit keeps the mirror. + let mirror = g.geom.map_or(1.0, |x| if x.is_mirrored() && kind == GradientKind::Conic { -1.0 } else { 1.0 }); + let asp = g.geom.map_or(100.0, |x| (x.aspect.abs() * 1000.0).round() / 10.0); let set = ui .add_enabled_ui(radial, |ui| { widgets::spin_plain_named(ui, "grad-aspect", Some(tl!("Aspect Ratio")), asp, "%", 1, 104.0, 1.0, 0.5, &ASPECT_PRESETS) }) .inner; if let Some(a) = set { - edit(app, json!({"aspect": a}), Live::Released); + edit(app, json!({"aspect": a * mirror}), Live::Released); } }); }); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 9177f315e2..27b0eda0b4 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -354,6 +354,51 @@ fn a_selected_diamond_shows_and_sets_its_midpoint_in_location() { assert!(texts.iter().any(|(t, _)| t == "0%")); } +/// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the +/// sweep mirrored. +#[test] +fn the_aspect_field_keeps_a_mirrored_conic_mirrored() { + let mut app = app(json!({"gradient": {"kind": "conic", "aspect": -50}})); + let mut p = Panel::new(); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + let field = texts.iter().find(|(t, _)| t == "50%").unwrap_or_else(|| panic!("the aspect field: {texts:?}")).1; + p.click(&mut app, field); + let key = |k, modifiers| Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }; + p.frame(&mut app, vec![key(egui::Key::A, Modifiers::COMMAND), Event::Text("80".into())], Modifiers::NONE); + p.frame(&mut app, vec![key(egui::Key::Enter, Modifiers::NONE)], Modifiers::NONE); + let geom = fill(&app).geom.unwrap(); + assert!((geom.aspect + 0.8).abs() < 1e-9 && geom.is_mirrored(), "{geom:?}"); +} + +/// The Type row's Diamond button (the fourth of five) makes the gradient a diamond, and the +/// Aspect Ratio field then edits its aspect. +#[test] +fn the_diamond_button_makes_a_diamond_whose_aspect_field_edits_it() { + let mut app = app(json!({"gradient": {"kind": "linear", "start": [150, 150], "end": [200, 150]}})); + let mut p = Panel::new(); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + let label = texts.iter().find(|(t, _)| t == "Type:").unwrap_or_else(|| panic!("the Type row: {texts:?}")).1; + let buttons = p.row_after(label, 24.0); + assert_eq!(buttons.len(), 5, "Linear, Radial, Conic, Diamond and Freeform"); + p.click(&mut app, buttons[3].center()); + assert_eq!(fill(&app).gradient.kind, GradientKind::Diamond); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + // The aspect field is the first 100% (above Opacity's). + let field = texts + .iter() + .filter(|(t, _)| t == "100%") + .map(|(_, at)| *at) + .min_by(|a, b| a.y.total_cmp(&b.y)) + .unwrap_or_else(|| panic!("the aspect field: {texts:?}")); + p.click(&mut app, field); + let key = |k, modifiers| Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }; + p.frame(&mut app, vec![key(egui::Key::A, Modifiers::COMMAND), Event::Text("80".into())], Modifiers::NONE); + p.frame(&mut app, vec![key(egui::Key::Enter, Modifiers::NONE)], Modifiers::NONE); + let g = fill(&app); + assert_eq!(g.gradient.kind, GradientKind::Diamond); + assert!((g.geom.unwrap().aspect - 0.8).abs() < 1e-9, "{:?}", g.geom); +} + #[test] fn the_thumbnail_menu_applies_gradient_swatches_and_saves_one() { let mut app = app(json!({"color": "#336699"})); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 313242bb48..f027f2c717 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -151,8 +151,10 @@ struct View<'a> { /// Where the row thumbnails come from. thumbs: ThumbSource<'a>, sel: HashSet, - /// The selected ruler guides. + /// The selected ruler guides, as indexes into [`Self::ruler_guides`]. guides: Vec, + /// The document's ruler guides ([`Document::ruler_guides`]). + ruler_guides: Vec, target: Option, current: Option, rows: Vec, @@ -262,7 +264,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { doc: &doc, thumbs: ThumbSource::of(app, st, &doc), sel: st.selection.objects.iter().copied().collect(), - guides: st.selection.guides.clone(), + guides: vectorcraft_engine::cmd::guide_indexes(&doc, &st.selection.guides), + ruler_guides: doc.ruler_guides(), target: st.selection.target, current: st.current_layer(), rows, @@ -468,7 +471,8 @@ fn listed_when_opened(doc: &Document, open: &OpenRows, opts: &PanelOptions, quer open.set(*a, true); } let mut rows = vec![]; - push_rows(layer, 0, false, (Color32::PLACEHOLDER, true), (&open, opts, query, filter, doc), &mut rows); + // Only object rows are looked for, so the guide rows are left out. + push_rows(layer, 0, false, (Color32::PLACEHOLDER, true), (&open, opts, query, filter, &[]), &mut rows); rows.iter().any(|r| r.node.id == id && r.guide.is_none() && !r.spine) } diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index bbafbb7559..c24863ffbc 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -1,5 +1,5 @@ use super::rows::key; -use super::{Arc, Color32, Document, LiveShape, Node, NodeKind, OpenRows, PanelOptions, Ui, Value, VectorcraftApp}; +use super::{Arc, Color32, Document, LiveShape, Node, NodeId, NodeKind, OpenRows, PanelOptions, Ui, Value, VectorcraftApp}; /// Where a dragged row goes relative to the row it is dropped on. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -42,7 +42,8 @@ pub(crate) fn shown_name(app: &VectorcraftApp, n: &Node, lang: crate::i18n::Lang pub(super) fn opens(n: &Node, opts: &PanelOptions) -> bool { match n.kind { NodeKind::Compound { .. } => false, - _ => n.children().is_some_and(|c| c.iter().any(|c| !opts.layers_only || c.is_layer())), + // Ruler guide nodes are not object rows (a layer's guide rows are counted by its caller). + _ => n.children().is_some_and(|c| c.iter().any(|c| !c.is_ruler_guide() && (!opts.layers_only || c.is_layer()))), } } @@ -226,25 +227,29 @@ struct RowsKey { /// contains `query` (lowercase) and that `filter` keeps, and every row holding one. pub(super) fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str, filter: &Filter) -> Vec { let mask_layer = doc.mask_edit.map(|m| m.layer); + // The ruler guides' ids by `guide.list` index, listed once for every layer. + let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); let mut out = vec![]; for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) { - push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query, filter, doc), &mut out); + push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query, filter, &guides), &mut out); } out } /// Add the rows of `n` and those open inside it to `out`; `(colour, shown)` are those of what holds -/// it (the layer's colour, and whether it is visible). +/// it (the layer's colour, and whether it is visible). The last item of `cx` is the document's +/// ruler guide ids by `guide.list` index. pub(super) fn push_rows( n: &Arc, depth: usize, clip_path: bool, (colour, shown): (Color32, bool), - cx: (&OpenRows, &PanelOptions, &str, &Filter, &Document), + cx: (&OpenRows, &PanelOptions, &str, &Filter, &[NodeId]), out: &mut Vec, ) { - let (open_rows, opts, query, filter, doc) = cx; - if opts.layers_only && !n.is_layer() { + let (open_rows, opts, query, filter, all_guides) = cx; + // A ruler guide node gets no object row: its layer lists the guide rows. + if n.is_ruler_guide() || (opts.layers_only && !n.is_layer()) { return; } let colour = match &n.kind { @@ -257,10 +262,16 @@ pub(super) fn push_rows( let shown = shown && n.visible; let searching = !query.is_empty(); let narrowing = searching || filter.is_on(); - // A layer's ruler guides are rows in it, above its art (not while searching, nor while the - // filter leaves them out). - let guides: Vec = - if n.is_layer() && !opts.layers_only && !searching && filter.keeps_guides() { doc.guides_on(n.id).map(|(i, _)| i).collect() } else { vec![] }; + // A layer's ruler guides are rows in it, above its art, the highest `guide.list` index first + // (not while searching, nor while the filter leaves them out). + let guides: Vec = if n.is_layer() && !opts.layers_only && !searching && filter.keeps_guides() { + let mut found: Vec = + n.children().into_iter().flatten().filter(|c| c.is_ruler_guide()).filter_map(|c| all_guides.binary_search(&c.id).ok()).collect(); + found.sort_unstable(); + found + } else { + vec![] + }; let opens = opens(n, opts) || !guides.is_empty(); let open = opens && (narrowing || open_rows.contains(n.id)); let at = out.len(); diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 376c021c41..13b6ff1e2b 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -122,7 +122,7 @@ fn takes(n: &Node, drag: &LayersDrag, doc: &Document) -> bool { fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) { let (t, h) = (&view.t, view.h); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); - let Some(g) = view.doc.guides.get(i) else { return }; + let Some(g) = view.ruler_guides.get(i) else { return }; let selected = view.guides.contains(&i); let editable = view.doc.guide_editable(g); if editable && resp.hovered() { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index cad2530e5f..4b47cbd3fe 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -272,12 +272,44 @@ fn closing_a_document_releases_only_its_layer_thumbnails() { }); } +/// From now on each reading of this thread's render budget clock is `ms` later than the one before. +/// A render reads it before and after, so each row thumbnail rendered takes `ms` of the budget. +fn clock_steps(ms: f64) { + let mut now = 0.0; + THUMBS.with(|c| { + c.borrow_mut().clock = Some(Box::new(move || { + now += ms; + now + })) + }); +} + +/// Rendering on the UI thread stops for the pass once the thumbnails rendered in it took the +/// budget, and the rest render in the next passes. +#[test] +fn row_thumbnails_past_the_render_budget_wait_for_the_next_pass() { + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let renders = || THUMBS.with(|c| c.borrow().renders); + // Each render takes 5 ms: after two renders the pass has used 10 ms, past the 8 ms budget. + clock_steps(5.0); + let mut per_pass = vec![]; + for _ in 0..4 { + let before = renders(); + frame(&mut app, &ctx, vec![], false); + per_pass.push(renders() - before); + } + assert_eq!(per_pass, [2, 1, 0, 0], "the layer's and two objects' thumbnails, two in the first pass"); +} + #[test] fn row_thumbnails_wait_for_the_end_of_a_drag() { let (mut app, _, _) = two_rects(); app.session.execute("select.all", &json!({})).unwrap(); let ctx = egui::Context::default(); let renders = || THUMBS.with(|c| c.borrow().renders); + // Renders take no time, so every row's thumbnail fits in a pass however busy the machine is. + clock_steps(0.0); frame(&mut app, &ctx, vec![], false); let first = renders(); assert!(first >= 1, "the rows' thumbnails render at once"); @@ -650,14 +682,17 @@ fn guide_rows_select_and_move_their_guides() { let (circles, _) = frame(&mut app, &ctx, vec![], false); assert_eq!(circles.len(), 3); let guide_row = egui::pos2(150.0, (circles[1].y + circles[2].y) / 2.0); - let guides = |app: &VectorcraftApp| app.session.active().unwrap().selection.guides.clone(); + let guides = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides) + }; click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE); assert_eq!(guides(&app), [0], "its row selects it"); // Dragged onto Layer 2's row, it goes on Layer 2, in one undo step. let undo = app.session.active().unwrap().history.undo.len(); drag(&mut app, &ctx, guide_row, egui::pos2(150.0, circles[0].y), false); let st = app.session.active().unwrap(); - assert_eq!((st.doc.guides[0].layer, st.history.undo.len()), (Some(second), undo + 1)); + assert_eq!((st.doc.ruler_guides()[0].layer, st.history.undo.len()), (Some(second), undo + 1)); // Now under Layer 2: locked, its row neither selects nor drags it. run(&mut app, "layer.setProps", json!({"ids": [second.0], "locked": true})); assert!(guides(&app).is_empty(), "deselected with its layer locked"); @@ -666,7 +701,7 @@ fn guide_rows_select_and_move_their_guides() { click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE); assert!(guides(&app).is_empty()); drag(&mut app, &ctx, guide_row, egui::pos2(150.0, circles[2].y), false); - assert_eq!(app.session.active().unwrap().doc.guides[0].layer, Some(second)); + assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].layer, Some(second)); } /// The selection squares drawn: (big ones on rows whose object is selected, small ones on rows @@ -1783,3 +1818,48 @@ fn a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend() { click_with(&mut app, &ctx, spine_row, egui::Modifiers::NONE); assert!(selected(&app).is_empty(), "a locked blend's spine can't be selected"); } + +/// A ruler guide node gets no object row, and a layer that holds only one has no rows to open. +#[test] +fn ruler_guide_nodes_get_no_object_row() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let rect = NodeId(app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + expand(&mut app, &json!({})).unwrap(); + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let (first, second) = (doc.layers[0].id, doc.add_layer(Some("Guides only"))); + for l in [first, second] { + let g = Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 20.0, artboard: None }); + doc.insert(Some(l), usize::MAX, g).unwrap(); + } + let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + let ids: Vec = rows.iter().filter(|r| r.guide.is_none()).map(|r| r.node.id).collect(); + assert_eq!(ids, [second, first, rect]); + // Each guide is a guide row of its layer instead. + let guide_rows: Vec = rows.iter().filter(|r| r.guide.is_some()).map(|r| r.node.id).collect(); + assert_eq!(guide_rows, [first], "the open layer lists its guide"); + assert!(rows[0].opens, "a layer with only a ruler guide opens to its guide row"); +} + +/// A layer lists its guide rows by `guide.list` index, the highest first, whatever the order of +/// the guide nodes in the layer (`guide.setLayer` puts a moved guide at the top of its new layer). +#[test] +fn guide_rows_list_by_index_whatever_the_node_order() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for pos in [10, 20, 30] { + app.session.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let layer = doc.layers[0].id; + // The guide of index 0 moves to the top of the layer's guides. + let first = doc.ruler_guides()[0].id.unwrap(); + doc.move_node(first, Some(layer), usize::MAX).unwrap(); + let kids: Vec = doc.layers[0].children().unwrap().iter().map(|c| c.id).collect(); + assert_eq!(kids.last(), Some(&first)); + let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), "", &Filter::default()); + let indexes: Vec = rows.iter().filter_map(|r| r.guide).collect(); + assert_eq!(indexes, [2, 1, 0]); +} diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index 2f15878133..861e894275 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -65,6 +65,10 @@ pub(super) struct Thumbs { spent: (u64, f64, u32), /// Thumbnails rendered on the UI thread (tests count them). pub(super) renders: u64, + /// A test's clock (ms) for the render budget, replacing [`crate::now_ms`] so a test decides how + /// long each render takes (production always leaves this `None`). + #[cfg(test)] + pub(super) clock: Option f64>>, } thread_local! { @@ -230,7 +234,8 @@ fn weigh(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Docum 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)) + // A layer's ruler guides draw nothing in its thumbnail and use no budget. + n.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).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); @@ -257,6 +262,15 @@ impl Thumbs { self.entries.keys().any(|key| key.0 == uid) } + /// The time (ms) a render on the UI thread is measured by: [`crate::now_ms`], or a test's clock. + fn now_ms(&mut self) -> f64 { + #[cfg(test)] + if let Some(clock) = self.clock.as_mut() { + return clock(); + } + crate::now_ms() + } + /// 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 @@ -415,9 +429,9 @@ impl Thumbs { thread_local! { static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } - let t0 = crate::now_ms(); + let t0 = self.now_ms(); let img = RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), src.doc, n, px)); - let ms = crate::now_ms() - t0; + let ms = self.now_ms() - t0; self.spent.1 += ms; self.spent.2 += 1; self.renders += 1; diff --git a/crates/ui-egui/src/panels/learn.rs b/crates/ui-egui/src/panels/learn.rs new file mode 100644 index 0000000000..e49832c0da --- /dev/null +++ b/crates/ui-egui/src/panels/learn.rs @@ -0,0 +1,214 @@ +//! Learn panel (Window › Learn, and Explore tutorials at the right end of the app bar): short +//! hands-on tutorials grouped by skill ([`catalog::SKILLS`]). The For you tab holds the Get started +//! section with the Quick skill guide card, which opens the Skills tab. The Skills tab lists each +//! skill with an empty progress ring and its count of tutorials; a skill lists its tutorials, and a +//! tutorial previews its numbered steps. Back goes up one level. `learn.list` lists the tutorials, +//! `learn.show` opens one and `window.learn` shows or hides the panel. + +pub mod catalog; + +use egui::{Sense, Stroke, Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::theme::Tokens; + +pub const ID: &str = "learn"; +/// The height of a skill or tutorial row. +const ROW_HEIGHT: f32 = 28.0; + +/// The panel's tabs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Tab { + #[default] + ForYou, + Skills, +} + +/// What the panel shows: its tab and, on the Skills tab, the skill and the tutorial open. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct View { + pub tab: Tab, + pub skill: Option<&'static str>, + pub tutorial: Option<&'static str>, +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + ui.horizontal(|ui| { + for (tab, label) in [(Tab::ForYou, tl!("For you")), (Tab::Skills, tl!("Skills"))] { + if ui.selectable_label(app.ui.learn.tab == tab, label).clicked() { + app.ui.learn.tab = tab; + } + } + }); + crate::widgets::divider(ui); + match app.ui.learn.tab { + Tab::ForYou => for_you(app, ui), + Tab::Skills => skills(app, ui), + } +} + +/// The For you tab: Get started, with the Quick skill guide card. +fn for_you(app: &mut VectorcraftApp, ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + crate::widgets::subheader(ui, tl!("Get started")); + ui.add_space(4.0); + let card = egui::Frame::NONE + .fill(t.panel_darker) + .stroke(Stroke::new(1.0, t.border)) + .corner_radius(egui::CornerRadius::same(t.radius)) + .inner_margin(egui::Margin::same(10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + crate::icons::icon(ui, "graduation-cap", 18.0, t.text_strong); + ui.label(egui::RichText::new(tl!("Quick skill guide")).size(13.0).color(t.text_strong)); + }); + ui.add_space(4.0); + ui.add(egui::Label::new( + egui::RichText::new(tl!("Short hands-on tutorials for the essential tools, grouped by skill. Choose a skill to see its tutorials.")) + .size(11.5) + .color(t.text_dim), + )); + }); + let resp = ui.interact(card.response.rect, ui.scope_id().with("quick-skill-guide"), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Quick skill guide"))); + if resp.clicked() { + app.ui.learn = View { tab: Tab::Skills, skill: None, tutorial: None }; + } +} + +/// The Skills tab: the skills, a skill's tutorials, or a tutorial's steps. +fn skills(app: &mut VectorcraftApp, ui: &mut Ui) { + let open = app.ui.learn.tutorial.and_then(catalog::tutorial); + if let Some((skill, tutorial)) = open { + if back(ui) { + app.ui.learn.skill = Some(skill.id); + app.ui.learn.tutorial = None; + } + steps(ui, tutorial); + return; + } + if let Some(skill) = app.ui.learn.skill.and_then(catalog::skill) { + if back(ui) { + app.ui.learn.skill = None; + } + crate::widgets::subheader(ui, skill.title); + for tutorial in skill.tutorials { + if row(ui, tutorial.title, None).clicked() { + app.ui.learn.tutorial = Some(tutorial.id); + } + } + return; + } + for skill in catalog::SKILLS { + if row(ui, skill.title, Some(skill.tutorials.len())).clicked() { + app.ui.learn.skill = Some(skill.id); + } + } +} + +/// The Back button above a skill's tutorials and a tutorial's steps; true when it was clicked. +fn back(ui: &mut Ui) -> bool { + crate::widgets::icon_button(ui, "chevron-left", tl!("Back"), false, 22.0).clicked() +} + +/// A tutorial's title and its numbered steps. +fn steps(ui: &mut Ui, tutorial: &catalog::Tutorial) { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(tutorial.title).size(13.0).color(t.text_strong)); + ui.add_space(4.0); + for (i, step) in tutorial.steps.iter().enumerate() { + ui.horizontal_top(|ui| { + ui.label(egui::RichText::new(format!("{}.", i + 1)).color(t.text_dim)); + ui.add(egui::Label::new(egui::RichText::new(step.text).color(t.text)).wrap()); + }); + ui.add_space(2.0); + } +} + +/// A clickable row: `title`, and for a skill (`tutorials`) a progress ring before it and the +/// count of tutorials done of all after it. No progress is kept yet, so the ring is empty. +fn row(ui: &mut Ui, title: &str, tutorials: Option) -> egui::Response { + let t = Tokens::get(ui.ctx()); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, egui::CornerRadius::same(4), t.hover); + } + let mut left = rect.left() + 6.0; + let mut right = rect.right() - 6.0; + let chevron = egui::Rect::from_center_size(egui::pos2(right - 6.0, rect.center().y), vec2(12.0, 12.0)); + crate::icons::paint(ui, "chevron-right", chevron, t.text_dim); + right = chevron.left() - 6.0; + if let Some(total) = tutorials { + ui.painter().circle_stroke(egui::pos2(left + 8.0, rect.center().y), 7.0, Stroke::new(2.0, t.border)); + left += 24.0; + let count = ui.painter().layout_no_wrap(format!("0/{total}"), egui::FontId::proportional(11.5), t.text_dim); + right -= count.size().x; + ui.painter().galley(egui::pos2(right, rect.center().y - count.size().y / 2.0), count, t.text_dim); + right -= 6.0; + } + let name = ui.painter().layout(title.to_string(), egui::FontId::proportional(12.5), t.text, f32::INFINITY); + let clip = egui::Rect::from_min_max(egui::pos2(left, rect.top()), egui::pos2(right.max(left), rect.bottom())); + ui.painter().with_clip_rect(clip).galley(egui::pos2(left, rect.center().y - name.size().y / 2.0), name, t.text); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), title)); + resp.on_hover_cursor(egui::CursorIcon::PointingHand) +} + +/// The Learn panel's UI commands: `window.learn`, `learn.list` and `learn.show`. +pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { + Some(match id { + "window.learn" => toggle(app, p), + "learn.list" => Ok(list()), + "learn.show" => open(app, p), + _ => return None, + }) +} + +/// Whether the panel can be seen: it is the front panel, the dock is not hidden and no full screen +/// mode hides the panels. +pub(crate) fn visible(ui: &crate::state::UiState) -> bool { + ui.dock && ui.screen_mode < 3 && crate::panel_docking::showing(ui, ID) +} + +/// `window.learn {show?}`: show the panel (true), hide it (false) or toggle it (omitted), as the +/// app bar's Explore tutorials button and Window › Learn do → whether it shows ([`visible`]). +/// Showing it also shows a hidden dock; in a full screen mode it makes the panel the front one. +fn toggle(app: &mut VectorcraftApp, p: &Value) -> Result { + let shown = visible(&app.ui); + let show = crate::menus::opt_bool(p, "show")?.unwrap_or(!shown); + if show && !shown { + crate::panel_docking::reveal_panel(app, ID)?; + } else if !show && shown { + app.run("window.panel", json!({ "panel": ID, "toggle": true }))?; + } + Ok(json!(visible(&app.ui))) +} + +/// `learn.list`: every skill with its tutorials and their step counts. +fn list() -> Value { + let skills = catalog::SKILLS.iter().map(|s| { + let tutorials: Vec = s.tutorials.iter().map(|t| json!({"id": t.id, "title": t.title, "steps": t.steps.len()})).collect(); + json!({"id": s.id, "title": s.title, "tutorials": tutorials}) + }); + json!({ "skills": skills.collect::>() }) +} + +/// `learn.show {tutorial}`: show the panel on the Skills tab with that tutorial's steps → the +/// tutorial. A missing or unknown id is an error and changes nothing. +fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "tutorial"; + let id = match p.get(key) { + None | Some(Value::Null) => return Err("missing `tutorial` (see learn.list)".into()), + Some(Value::String(id)) => id.as_str(), + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let (skill, tutorial) = catalog::tutorial(id).ok_or_else(|| format!("unknown tutorial `{id}` (see learn.list)"))?; + crate::panel_docking::reveal_panel(app, ID)?; + app.ui.learn = View { tab: Tab::Skills, skill: Some(skill.id), tutorial: Some(tutorial.id) }; + let steps: Vec<&str> = tutorial.steps.iter().map(|s| s.text).collect(); + Ok(json!({"skill": skill.id, "tutorial": tutorial.id, "title": tutorial.title, "steps": steps})) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/panels/learn/catalog.rs b/crates/ui-egui/src/panels/learn/catalog.rs new file mode 100644 index 0000000000..b1ffd897d7 --- /dev/null +++ b/crates/ui-egui/src/panels/learn/catalog.rs @@ -0,0 +1,185 @@ +//! The Learn panel's tutorials, VectorCraft's own short lessons, grouped by skill. The text is +//! English data: the panel shows it as written in every interface language. + +/// One step of a tutorial: what to do, and the tool it chooses or the command it runs, if any. +pub struct Step { + pub text: &'static str, + /// A tool id ([`vectorcraft_tools::catalog::tool_info`]) the step names. + pub tool: Option<&'static str>, + /// A command id the step names. + pub command: Option<&'static str>, +} + +/// A tutorial: an id for `learn.show`, its title and its numbered steps. +pub struct Tutorial { + pub id: &'static str, + pub title: &'static str, + pub steps: &'static [Step], +} + +/// A skill and its tutorials, in the order the panel lists them. +pub struct Skill { + pub id: &'static str, + pub title: &'static str, + pub tutorials: &'static [Tutorial], +} + +/// A step that names no tool or command. +const fn say(text: &'static str) -> Step { + Step { text, tool: None, command: None } +} + +/// A step that uses tool `id`. +const fn tool(text: &'static str, id: &'static str) -> Step { + Step { text, tool: Some(id), command: None } +} + +/// A step that runs command `id`. +const fn command(text: &'static str, id: &'static str) -> Step { + Step { text, tool: None, command: Some(id) } +} + +/// Every skill, in the order the Skills tab lists them. +pub const SKILLS: &[Skill] = &[ + Skill { + id: "essentials", + title: "Best of VectorCraft", + tutorials: &[ + Tutorial { + id: "draw-and-color", + title: "Draw and color a shape", + steps: &[ + tool("Choose the Rectangle tool in the toolbar.", "rectangle"), + say("Drag on the artboard to draw a rectangle."), + say("With the rectangle still selected, click a color in the Swatches panel to fill it."), + command("Click the Stroke box under the tools, then click another swatch to color the outline.", "paint.toggleActive"), + ], + }, + Tutorial { + id: "combine-shapes", + title: "Combine shapes into one", + steps: &[ + tool("Choose the Ellipse tool and draw two circles that overlap.", "ellipse"), + tool("Choose the Selection tool and drag across both circles to select them.", "selection"), + tool("Choose the Shape Builder tool and drag across the parts you want to merge.", "shapeBuilder"), + ], + }, + Tutorial { + id: "add-headline", + title: "Add a headline", + steps: &[ + tool("Choose the Type tool and click on the artboard.", "type"), + say("Type a few words, then press Escape to finish."), + say("Pick a font and a size in the Character panel."), + ], + }, + ], + }, + Skill { + id: "draw", + title: "Draw and build", + tutorials: &[ + Tutorial { + id: "pen-paths", + title: "Draw paths with the Pen", + steps: &[ + tool("Choose the Pen tool.", "pen"), + say("Click to place corner points, or drag to pull out a curve."), + say("Click the first point again to close the shape, or press Enter to leave it open."), + ], + }, + Tutorial { + id: "smooth-curves", + title: "Draw smooth curves", + steps: &[ + tool("Choose the Curvature tool.", "curvature"), + say("Click to place points: the path bends smoothly through each one."), + tool("Choose the Direct Selection tool and drag a point to reshape the curve.", "directSelection"), + ], + }, + Tutorial { + id: "pencil-sketch", + title: "Sketch with the Pencil", + steps: &[ + tool("Choose the Pencil tool.", "pencil"), + say("Drag to draw a freehand line."), + tool("Choose the Smooth tool and drag along the line to even it out.", "smooth"), + ], + }, + ], + }, + Skill { + id: "color", + title: "Apply color", + tutorials: &[ + Tutorial { + id: "fill-and-stroke", + title: "Fill and stroke", + steps: &[ + tool("Select an object with the Selection tool.", "selection"), + say("Click the Fill box under the tools, then pick a color in the Color panel."), + command("Click the double arrow beside the boxes to swap the fill and the stroke.", "paint.swap"), + ], + }, + Tutorial { + id: "gradient", + title: "Add a gradient", + steps: &[ + tool("Select an object with the Selection tool.", "selection"), + tool("Choose the Gradient tool and click the object to give it a gradient.", "gradient"), + say("Drag across the object to set the gradient's direction and length."), + ], + }, + Tutorial { + id: "copy-colors", + title: "Copy colors from other art", + steps: &[ + tool("Select the object to color with the Selection tool.", "selection"), + tool("Choose the Eyedropper tool and click the art whose colors you want.", "eyedropper"), + ], + }, + ], + }, + Skill { + id: "type", + title: "Set type", + tutorials: &[ + Tutorial { + id: "area-type", + title: "Flow text into a shape", + steps: &[ + tool("Draw a rectangle for the text to fill.", "rectangle"), + tool("Choose the Area Type tool and click the rectangle's edge.", "areaType"), + say("Type or paste your text: it wraps inside the shape."), + ], + }, + Tutorial { + id: "type-on-path", + title: "Type along a path", + steps: &[ + tool("Draw a curved path with the Pen tool.", "pen"), + tool("Choose the Type on a Path tool and click the path.", "typeOnPath"), + say("Type your text: it follows the path."), + ], + }, + Tutorial { + id: "outline-type", + title: "Turn type into shapes", + steps: &[ + tool("Select a text object with the Selection tool.", "selection"), + command("Choose Type › Create Outlines to turn its letters into paths.", "type.createOutlines"), + ], + }, + ], + }, +]; + +/// The skill whose id is `id`. +pub fn skill(id: &str) -> Option<&'static Skill> { + SKILLS.iter().find(|s| s.id == id) +} + +/// The tutorial whose id is `id`, with its skill. +pub fn tutorial(id: &str) -> Option<(&'static Skill, &'static Tutorial)> { + SKILLS.iter().find_map(|s| s.tutorials.iter().find(|t| t.id == id).map(|t| (s, t))) +} diff --git a/crates/ui-egui/src/panels/learn/tests.rs b/crates/ui-egui/src/panels/learn/tests.rs new file mode 100644 index 0000000000..d4dbf8f00b --- /dev/null +++ b/crates/ui-egui/src/panels/learn/tests.rs @@ -0,0 +1,231 @@ +use std::collections::HashSet; + +use egui::accesskit::Node; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{ID, Tab, View, catalog, show}; +use crate::VectorcraftApp; +use crate::tests_labels::painted_text; + +const SCREEN: egui::Rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1400.0, 800.0)); + +fn app() -> VectorcraftApp { + crate::i18n::set_current(crate::i18n::Lang::EN); + VectorcraftApp::new(Session::new(), Default::default()) +} + +/// One frame of `draw` with screen-reader nodes on → the nodes. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, draw: fn(&mut VectorcraftApp, &mut egui::Ui)) -> Vec { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(SCREEN), ..Default::default() }, |ui| draw(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() +} + +/// The center of the node labeled `name`. +fn center(nodes: &[Node], name: &str) -> Option { + center_where(nodes, |label| label == name) +} + +/// The center of the first node whose label `pick` takes. +fn center_where(nodes: &[Node], pick: impl Fn(&str) -> bool) -> Option { + let b = nodes.iter().find(|n| n.label().is_some_and(&pick))?.bounds()?; + Some(egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// Click the node labeled `name` in what `draw` draws. +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, draw: fn(&mut VectorcraftApp, &mut egui::Ui)) { + frame(app, ctx, vec![], draw); + let at = center(&frame(app, ctx, vec![], draw), name).unwrap_or_else(|| panic!("{name} is drawn")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![egui::Event::PointerMoved(at), press(true)], draw); + frame(app, ctx, vec![press(false)], draw); +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + ctx +} + +fn app_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + crate::chrome::app_bar(app, ui); +} + +fn shown(app: &VectorcraftApp) -> bool { + crate::panel_docking::showing(&app.ui, ID) +} + +/// Every skill has tutorials and every tutorial steps; ids are unique; every tool and command a +/// step names exists. +#[test] +fn the_catalog_is_valid() { + let mut skills = HashSet::new(); + let mut tutorials = HashSet::new(); + assert!(!catalog::SKILLS.is_empty()); + for skill in catalog::SKILLS { + assert!(skills.insert(skill.id), "skill id {} is used twice", skill.id); + assert!(!skill.title.is_empty() && !skill.tutorials.is_empty(), "skill {} is empty", skill.id); + for tutorial in skill.tutorials { + assert!(tutorials.insert(tutorial.id), "tutorial id {} is used twice", tutorial.id); + assert!(!tutorial.title.is_empty() && !tutorial.steps.is_empty(), "tutorial {} is empty", tutorial.id); + for step in tutorial.steps { + assert!(step.text.ends_with('.'), "{}: {:?}", tutorial.id, step.text); + if let Some(tool) = step.tool { + assert!(vectorcraft_tools::catalog::tool_info(tool).is_some(), "{}: no tool {tool}", tutorial.id); + } + if let Some(cmd) = step.command { + let known = + crate::menus::UI_COMMANDS.iter().any(|c| c.0 == cmd) || vectorcraft_engine::cmd::command_specs().iter().any(|c| c.id == cmd); + assert!(known, "{}: no command {cmd}", tutorial.id); + } + } + } + } +} + +/// Explore tutorials at the right end of the app bar shows the Learn panel, and hides it again. +#[test] +fn explore_tutorials_on_the_app_bar_shows_and_hides_the_learn_panel() { + let mut app = app(); + let ctx = context(); + assert!(!shown(&app)); + let nodes = frame(&mut app, &ctx, vec![], app_bar); + let search = center_where(&nodes, |label| label.starts_with("Search commands and tools")); + let learn = center(&nodes, "Explore tutorials"); + let (search, learn) = (search.expect("the search icon shows"), learn.expect("the app bar has Explore tutorials")); + assert!(learn.x < search.x && (learn.y - search.y).abs() < 1.0, "beside the search icon: {learn:?}, {search:?}"); + click(&mut app, &ctx, "Explore tutorials", app_bar); + assert!(shown(&app), "{}", app.ui.status); + click(&mut app, &ctx, "Explore tutorials", app_bar); + assert!(!shown(&app)); +} + +/// The command and params of Window › Learn. +fn window_learn() -> (&'static str, serde_json::Value) { + use crate::menus::Item; + let window = crate::menus::menu_tree().into_iter().find(|(title, _)| *title == "Window").map(|(_, items)| items).unwrap(); + window + .iter() + .find_map(|item| match item { + Item::Cmd("Learn", cmd, p) => Some((*cmd, p.clone())), + _ => None, + }) + .expect("Window › Learn") +} + +/// Window › Learn shows and hides the panel, as `window.learn` does. +#[test] +fn window_learn_shows_and_hides_the_panel() { + let mut app = app(); + let (cmd, params) = window_learn(); + app.run(cmd, params.clone()).unwrap(); + assert!(shown(&app)); + assert_eq!(crate::menus::checked(&app, cmd, ¶ms), Some(true), "Window › Learn is checked"); + app.run(cmd, params.clone()).unwrap(); + assert!(!shown(&app)); + assert_eq!(crate::menus::checked(&app, cmd, ¶ms), Some(false)); + assert_eq!(app.run("window.learn", json!({"show": true})).unwrap(), json!(true)); + assert_eq!(app.run("window.learn", json!({"show": true})).unwrap(), json!(true), "shown stays shown"); + assert_eq!(app.run("window.learn", json!({})).unwrap(), json!(false)); + assert!(app.run("window.learn", json!({"show": "yes"})).is_err()); + assert!(!shown(&app)); +} + +/// With the dock hidden, Learn as the front panel is not visible: `window.learn`, Window › Learn +/// and Explore tutorials show the dock instead of closing the panel. +#[test] +fn window_learn_shows_a_hidden_dock() { + let mut app = app(); + let (cmd, params) = window_learn(); + assert_eq!(app.run("window.learn", json!({"show": true})).unwrap(), json!(true)); + app.ui.dock = false; + assert_eq!(crate::menus::checked(&app, cmd, ¶ms), Some(false), "Window › Learn is unchecked"); + assert_eq!(app.run("window.learn", json!({"show": false})).unwrap(), json!(false)); + assert!(shown(&app) && !app.ui.dock, "hiding a panel that cannot be seen changes nothing"); + app.run(cmd, params).unwrap(); + assert!(app.ui.dock && shown(&app), "Window › Learn shows the dock"); + // A full screen mode hides the panels: the panel stays the front one and shows when it ends. + app.ui.screen_mode = 3; + assert_eq!(app.run("window.learn", json!({})).unwrap(), json!(false)); + assert!(shown(&app)); + app.ui.screen_mode = 0; + assert_eq!(app.run("window.learn", json!({})).unwrap(), json!(false)); + assert!(!shown(&app)); +} + +/// The For you tab's Quick skill guide card opens the Skills tab, which lists every skill with its +/// count of tutorials. +#[test] +fn the_skills_tab_lists_every_skill() { + let mut app = app(); + let ctx = context(); + let text = painted_text(&mut app, show); + assert!(text.contains("Get started") && text.contains("Quick skill guide"), "{text}"); + click(&mut app, &ctx, "Quick skill guide", show); + assert_eq!(app.ui.learn.tab, Tab::Skills); + let text = painted_text(&mut app, show); + for skill in catalog::SKILLS { + assert!(text.contains(skill.title), "{} in {text}", skill.title); + assert!(text.contains(&format!("0/{}", skill.tutorials.len())), "{text}"); + } + let skill = &catalog::SKILLS[1]; + click(&mut app, &ctx, skill.title, show); + let text = painted_text(&mut app, show); + for tutorial in skill.tutorials { + assert!(text.contains(tutorial.title), "{} in {text}", tutorial.title); + } +} + +/// Choosing a tutorial previews its numbered steps; Back goes to its skill, then to the skills. +#[test] +fn a_tutorial_previews_its_steps() { + let mut app = app(); + let ctx = context(); + let (skill, tutorial) = catalog::tutorial("pen-paths").unwrap(); + app.ui.learn = View { tab: Tab::Skills, skill: Some(skill.id), tutorial: None }; + click(&mut app, &ctx, tutorial.title, show); + assert_eq!(app.ui.learn.tutorial, Some(tutorial.id)); + let text = painted_text(&mut app, show); + for (i, step) in tutorial.steps.iter().enumerate() { + assert!(text.contains(&format!("{}.", i + 1)) && text.contains(step.text), "{} in {text}", step.text); + } + click(&mut app, &ctx, "Back", show); + assert_eq!(app.ui.learn, View { tab: Tab::Skills, skill: Some(skill.id), tutorial: None }); + click(&mut app, &ctx, "Back", show); + assert_eq!(app.ui.learn, View { tab: Tab::Skills, skill: None, tutorial: None }); +} + +/// `learn.show` opens the panel on a tutorial's steps; `learn.list` lists every tutorial. +#[test] +fn learn_show_opens_a_tutorial_and_learn_list_lists_them() { + let mut app = app(); + let shown_tutorial = app.run("learn.show", json!({"tutorial": "gradient"})).unwrap(); + assert_eq!(shown_tutorial["skill"], "color"); + assert_eq!(shown_tutorial["steps"].as_array().map(Vec::len), Some(3)); + assert!(shown(&app)); + assert_eq!(app.ui.learn, View { tab: Tab::Skills, skill: Some("color"), tutorial: Some("gradient") }); + let list = app.run("learn.list", json!({})).unwrap(); + let skills = list["skills"].as_array().unwrap(); + assert_eq!(skills.len(), catalog::SKILLS.len()); + let count: usize = skills.iter().map(|s| s["tutorials"].as_array().map_or(0, Vec::len)).sum(); + assert_eq!(count, catalog::SKILLS.iter().map(|s| s.tutorials.len()).sum::()); + assert_eq!(skills[2]["tutorials"][1], json!({"id": "gradient", "title": "Add a gradient", "steps": 3})); +} + +/// A missing, mistyped or unknown tutorial id is an error and leaves the panel as it was. +#[test] +fn learn_show_rejects_a_missing_or_unknown_tutorial() { + let mut app = app(); + let before = app.ui.learn.clone(); + for (params, error) in [ + (json!({}), "missing `tutorial` (see learn.list)"), + (json!({"tutorial": 3}), "`tutorial` must be a string"), + (json!({"tutorial": "nope"}), "unknown tutorial `nope` (see learn.list)"), + ] { + assert_eq!(app.run("learn.show", params).unwrap_err(), error); + assert_eq!(app.ui.learn, before); + assert!(!shown(&app)); + } +} diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index ac92a42793..78ce76da32 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -827,8 +827,7 @@ pub(crate) fn import(app: &mut VectorcraftApp, p: Value) -> Result, filters: Vec<(&'static str, &'static [&'static str])>, ) -> Result, String> { - if path.is_none() - && let Some(f) = app.services.open_async.as_mut() - { - f(); + if path.is_none() && crate::picks::open_async(app) { return Ok(None); } path.or_else(|| { diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index 31976746e3..f28e7e5540 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -155,8 +155,9 @@ fn find_filters_list_view_and_arrows_step_through_the_libraries() { assert!(ctx.read_response(tile_id(panel, "#00FF00")).is_none()); let first = SWATCH_IDS[0]; let last = SwatchLibraries::list(&app).pop().unwrap().id; - assert_eq!(last, "geometric-patterns", "gradient and then pattern libraries come after the swatch libraries"); + assert_eq!(last, "grit-textures", "gradient and then pattern libraries come after the swatch libraries"); assert_eq!(neighbour::(&app, "radial-glows", 1).as_deref(), Some("geometric-patterns")); + assert_eq!(neighbour::(&app, "geometric-patterns", 1).as_deref(), Some("grit-textures")); assert_eq!(neighbour::(&app, first, -1), Some(last), "wraps around"); assert_eq!(neighbour::(&app, "web-safe-216", 1).as_deref(), Some(SWATCH_IDS[1])); } diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 32d15d715f..cabca387ae 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -877,6 +877,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + // Korean lines break between any two syllables, not only between words. + let anywhere = shared_para(app, |p| p.korean_line_break_anywhere) == Some(true); + if menu_item(ui, tl!("Korean Line Break Anywhere"), has, anywhere) { + toggle_korean_line_break_anywhere(app); + } } ui.separator(); let composer = shared_composer(app); @@ -899,12 +904,20 @@ fn set_kinsoku_type(app: &mut VectorcraftApp, key: &str) { format(app, json!({"kinsokuType": key})); } +/// Korean Line Break Anywhere (Paragraph panel menu): the menu item is checked when every paragraph +/// the panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for +/// all of them otherwise, in one undo step. +fn toggle_korean_line_break_anywhere(app: &mut VectorcraftApp) { + let on = shared_para(app, |p| p.korean_line_break_anywhere) == Some(true); + format(app, json!({"koreanLineBreakAnywhere": !on})); +} + /// Reset Panel: the paragraphs the panel acts on ([`format`]) take Auto alignment, no list, no /// indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification /// options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi /// Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Roman -/// Hanging Punctuation off, no kashidas and no tab stops, as one undo step named Reset Panel (inside -/// an undo group that is already open, as part of its step). +/// Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo +/// step named Reset Panel (inside an undo group that is already open, as part of its step). fn reset_panel(app: &mut VectorcraftApp) { let h = HyphenationOptions::default(); let j = vectorcraft_doc::JustificationOptions::default(); @@ -924,7 +937,7 @@ fn reset_panel(app: &mut VectorcraftApp) { "wordSpacing": j.word_spacing, "letterSpacing": j.letter_spacing, "glyphScaling": j.glyph_scaling, "autoLeading": j.auto_leading, "singleWordJustification": "fullJustify", "direction": "auto", "leadingModel": "romanBaseline", "mojikumi": "lineEndHalf", "burasagari": "standard", "kinsoku": "hard", - "kinsokuType": "pushOutOnly", "composer": "everyLine", "romanHangingPunctuation": false + "kinsokuType": "pushOutOnly", "composer": "everyLine", "romanHangingPunctuation": false, "koreanLineBreakAnywhere": false }), ); para_cmd(app, "text.tabs.clear", json!({})); diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index fe66d367f9..517ef1eeab 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -133,6 +133,39 @@ fn kinsoku_shori_type_sets_the_selected_paragraphs_in_one_undo_step() { assert_eq!(types(&app), (KinsokuShoriType::PushOutOnly, KinsokuShoriType::PushOutOnly)); } +/// Korean Line Break Anywhere: new type has it off; the menu item turns it on for the paragraphs +/// the Type tool's selection touches in one undo step, is unchecked while the selected paragraphs +/// differ, turns it on for all of them then and off again once they all have it. Reset Panel turns +/// it off. +#[test] +fn korean_line_break_anywhere_toggles_the_selected_paragraphs_in_one_undo_step() { + let (mut app, id) = editing_text("가나\n다라\n"); + app.session.prefs.show_east_asian_options = true; + let flags = |app: &VectorcraftApp| { + let node = app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("text") }; + (text.para_at(0).korean_line_break_anywhere, text.para_at(1).korean_line_break_anywhere) + }; + assert_eq!(flags(&app), (false, false), "new type has it off"); + select_range(&mut app, 0, 3); + let history = app.session.active().unwrap().history.undo.len(); + toggle_korean_line_break_anywhere(&mut app); + assert_eq!(flags(&app), (true, false)); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + app.session.set_tool_option("selectAll", &json!(true)); + assert_eq!(shared_para(&app, |p| p.korean_line_break_anywhere), None, "mixed: unchecked"); + toggle_korean_line_break_anywhere(&mut app); + assert_eq!(flags(&app), (true, true)); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_korean_line_break_anywhere(&mut app); + assert_eq!(flags(&app), (false, false)); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_korean_line_break_anywhere(&mut app); + app.session.set_tool_option("selectAll", &json!(true)); + reset_panel(&mut app); + assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); +} + #[test] fn paragraph_mixed_indent_fields_show_blank() { let (mut app, id) = editing_text("A\nB\n"); @@ -698,11 +731,43 @@ fn the_control_bar_shows_the_paragraph_alignment_of_the_selected_type() { assert!(control_bar_node(&nodes, "Justify all lines").is_none(), "a second click closes it"); } +/// The Control bar's Character and Paragraph groups hold the type controls; each off leaves the +/// other, and with Paragraph off the Align buttons fit a narrower window. +#[test] +fn the_character_and_paragraph_groups_hold_the_type_controls() { + let ctx = control_bar_ctx(); + let mut app = control_bar_app(&[json!({"x": 20, "y": 50, "text": "Point"})]); + let set = |app: &mut VectorcraftApp, group: &str, visible: bool| { + app.run("window.control.options", json!({ "group": group, "visible": visible })).unwrap(); + }; + // The narrowest window, in steps of 10 points, whose bar shows the Align buttons. + let narrowest = |app: &mut VectorcraftApp| { + (40..=240).map(|w| w as f32 * 10.0).find(|&w| control_bar_node(&control_bar_nodes(&ctx, app, w, vec![]), "Horizontal Align Left").is_some()) + }; + let nodes = control_bar_nodes(&ctx, &mut app, 1920.0, vec![]); + for name in ["Character:", "Paragraph:", "Align left"] { + assert!(control_bar_node(&nodes, name).is_some(), "{name} shows"); + } + let all = narrowest(&mut app).expect("the Align buttons show in a wide window"); + set(&mut app, "paragraph", false); + let nodes = control_bar_nodes(&ctx, &mut app, 1920.0, vec![]); + assert!(control_bar_node(&nodes, "Paragraph:").is_none() && control_bar_node(&nodes, "Align left").is_none(), "Paragraph is off"); + assert!(control_bar_node(&nodes, "Character:").is_some(), "Character stays"); + let fewer = narrowest(&mut app).expect("the Align buttons show without Paragraph"); + assert!(fewer < all, "the Align buttons fit {fewer} wide without Paragraph, {all} with it"); + set(&mut app, "paragraph", true); + set(&mut app, "character", false); + let nodes = control_bar_nodes(&ctx, &mut app, 1920.0, vec![]); + assert!(control_bar_node(&nodes, "Character:").is_none(), "Character is off"); + assert!(control_bar_node(&nodes, "Paragraph:").is_some(), "Paragraph stays"); +} + /// #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). +/// With type selected the inline X/Y/W/H fields go first, then the Distribute buttons, the Align To +/// menu and the 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(); @@ -717,12 +782,13 @@ fn the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right() groups.push(("vertical alignment", VERTICAL.to_vec())); } groups.push(("Align", vec!["Horizontal Align Left", "Vertical Align Bottom"])); + groups.push(("Align To", vec!["Align To:"])); 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) { + for width in (600..=2600).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 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 3dd7da7d6e..07b53cc6d8 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -159,6 +159,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { crate::panels::image_trace::trace_button(app, ui, ui.available_width()); actions.push((tl!("Crop Image"), "ui.cropImage")); actions.push((tl!("Mask"), "object.maskImage")); + // Remove Background at once with its defaults, as the reference app's Quick Actions do + // (). + actions.push((tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND)); } // Object › Path's Offset Path and Simplify take paths: type alone could only fail, and offsets // live through the Appearance panel's Effect › Path › Offset Path (#2238). @@ -1014,9 +1017,12 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { }); } super::paragraph::hyphenate_check(app, ui, ¶); + // Area type: Dynamic Text's Block and its gaps. + dynamic_text::rows(app, ui); } } +pub(crate) mod dynamic_text; pub(crate) mod vertical_align; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/properties/dynamic_text.rs b/crates/ui-egui/src/panels/properties/dynamic_text.rs new file mode 100644 index 0000000000..7caf9e41f5 --- /dev/null +++ b/crates/ui-egui/src/panels/properties/dynamic_text.rs @@ -0,0 +1,84 @@ +//! Dynamic Text in the Properties panel's Paragraph section: the Dynamic Text checkbox for the +//! selected area type (Block, `type.dynamicText`) and, while it is on, its Word Gap and Line Gap +//! rows ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) +//! describes Block and its spacing between words and between lines). + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_doc::{AreaOptions, NodeKind, TextKind}; + +use crate::VectorcraftApp; +use crate::widgets; + +/// What the selected area type shows: whether Block is on in every frame (`None` when they +/// differ), the gaps every frame shares (`None` when they differ), and whether every frame can +/// take it (none is threaded). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Shown { + pub(crate) on: Option, + pub(crate) word_gap: Option, + pub(crate) line_gap: Option, + pub(crate) enabled: bool, +} + +/// Dynamic Text of the selected area type (and area type in selected groups); `None` when the +/// selection holds no area type, or holds other type too (the command refuses it). +pub(crate) fn shown(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let threaded = |id| st.doc.text_threads.iter().any(|t| t.len() > 1 && t.contains(&id)); + let mut frames = vec![]; + let mut other = false; + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + let NodeKind::Text(t) = &c.kind else { return }; + if matches!(t.kind, TextKind::Area { .. }) { + let (word, line) = t.area.block_gaps(); + frames.push((t.dynamic_text, word, line, threaded(c.id))); + } else { + other = true; + } + }); + } + let &(on, word, line, _) = frames.first().filter(|_| !other)?; + Some(Shown { + on: frames.iter().all(|f| f.0 == on).then_some(on), + word_gap: frames.iter().all(|f| f.1 == word).then_some(word), + line_gap: frames.iter().all(|f| f.2 == line).then_some(line), + enabled: frames.iter().all(|f| !f.3), + }) +} + +fn run(app: &mut VectorcraftApp, p: Value) { + if let Err(e) = app.run("type.dynamicText", p) { + app.status(e); + } +} + +/// The checkbox, and the gap rows while every selected frame has Block on. Nothing shows without +/// area type. Returns whether anything was drawn. +pub(crate) fn rows(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { + let Some(s) = shown(app) else { return false }; + if widgets::check(ui, tl!("Dynamic Text"), s.on == Some(true), s.enabled) { + run(app, json!({ "on": s.on != Some(true) })); + } + if s.on != Some(true) { + return true; + } + let fw = super::super::field_width(ui); + let (lo, hi) = AreaOptions::WORD_GAP; + ui.horizontal(|ui| { + ui.label(tl!("Word Gap")); + if let Some(v) = widgets::spin_plain_named(ui, "props-dt-word", Some(tl!("Word Gap")), s.word_gap, "%", 0, fw, 10.0, lo, &[]) { + run(app, json!({ "wordGap": v.clamp(lo, hi) })); + } + }); + let (lo, hi) = AreaOptions::LINE_GAP; + let unit = app.session.general_unit(); + ui.horizontal(|ui| { + ui.label(tl!("Line Gap")); + if let Some(v) = widgets::spin_field_named(ui, "props-dt-line", Some(tl!("Line Gap")), s.line_gap, unit, fw, 1.0, lo, &[]) { + run(app, json!({ "lineGap": v.clamp(lo, hi) })); + } + }); + true +} diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index ea1a60095a..5ed020c326 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1733,7 +1733,7 @@ fn selected_guides_show_their_position_in_a_transform_section() { app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let v = app.run("guide.add", json!({"vertical": true, "pos": 30})).unwrap()["index"].as_u64().unwrap(); let h = app.run("guide.add", json!({"vertical": false, "pos": 20})).unwrap()["index"].as_u64().unwrap(); - let pos = |app: &VectorcraftApp, i: u64| app.session.doc().unwrap().doc.guides[i as usize].pos; + let pos = |app: &VectorcraftApp, i: u64| app.session.doc().unwrap().doc.ruler_guides()[i as usize].pos; let ctx = egui::Context::default(); // Steps the field labelled `label` up by one with ↑. let step = |app: &mut VectorcraftApp, label: &str| { @@ -1946,3 +1946,38 @@ fn vertical_alignment_buttons_align_the_selected_area_type() { app.run("select.set", json!({"ids": [a]})).unwrap(); assert_eq!(vertical_align::shown(&app).map(|s| s.enabled), Some(false)); } + +/// With area type selected, the Paragraph section shows a Dynamic Text checkbox, and Word Gap and +/// Line Gap while Block is on in every selected frame. Point type in the selection shows none; +/// threaded frames turn the checkbox off. +#[test] +fn dynamic_text_rows_follow_the_selected_area_type() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + let make = |app: &mut VectorcraftApp, x: f64, y: f64| { + app.run("text.create", json!({"x": x, "y": y, "text": "Panel\ntext", "area": {"width": 100, "height": 120}})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (make(&mut app, 10.0, 10.0), make(&mut app, 200.0, 10.0)); + let point = app.run("text.create", json!({"x": 10, "y": 350, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, point]})).unwrap(); + assert_eq!(dynamic_text::shown(&app), None, "point type selected too: no rows"); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let off = dynamic_text::Shown { on: Some(false), word_gap: Some(100.0), line_gap: Some(0.0), enabled: true }; + assert_eq!(dynamic_text::shown(&app), Some(off)); + let ctx = egui::Context::default(); + let texts = panel_frame(&mut app, &ctx, vec![], type_sections); + assert!(texts.iter().any(|(t, _)| t == "Dynamic Text") && !texts.iter().any(|(t, _)| t == "Word Gap"), "{texts:?}"); + app.run("type.dynamicText", json!({"on": true, "lineGap": 2})).unwrap(); + let on = dynamic_text::Shown { on: Some(true), word_gap: Some(100.0), line_gap: Some(2.0), enabled: true }; + assert_eq!(dynamic_text::shown(&app), Some(on)); + let texts = panel_frame(&mut app, &ctx, vec![], type_sections); + assert!(texts.iter().any(|(t, _)| t == "Word Gap") && texts.iter().any(|(t, _)| t == "Line Gap"), "{texts:?}"); + // Differing gaps and settings show as mixed. + app.run("type.dynamicText", json!({"ids": [b], "wordGap": 200})).unwrap(); + assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.word_gap, s.line_gap)), Some((Some(true), None, Some(2.0)))); + app.run("type.dynamicText", json!({"ids": [b], "on": false})).unwrap(); + assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.word_gap)), Some((None, None))); + // A threaded frame turns the checkbox off. + app.run("text.thread.create", json!({})).unwrap(); + assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.enabled)), Some((Some(false), false))); +} diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 04709b42c7..bf501113ab 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -76,7 +76,7 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { /// A dropdown of the `kind` profiles after `extra` (a built-in entry, shown in the UI language); /// profile names are shown as they are. Returns the chosen name. -fn profile_dropdown(ui: &mut Ui, id: &str, current: &str, kind: ProfileKind, extra: Option<&str>) -> Option { +pub(crate) fn profile_dropdown(ui: &mut Ui, id: &str, current: &str, kind: ProfileKind, extra: Option<&str>) -> Option { let names: Vec = extra.map(str::to_string).into_iter().chain(cms::profiles().into_iter().filter(|p| p.kind == kind).map(|p| p.name)).collect(); let refs: Vec<&str> = names.iter().map(|n| super::label_or_name(n, extra == Some(n.as_str()))).collect(); diff --git a/crates/ui-egui/src/panels/swatches/tiles.rs b/crates/ui-egui/src/panels/swatches/tiles.rs index 7e92f261bf..42ff8b381c 100644 --- a/crates/ui-egui/src/panels/swatches/tiles.rs +++ b/crates/ui-egui/src/panels/swatches/tiles.rs @@ -141,6 +141,8 @@ pub(crate) fn list_icons(ui: &Ui, r: Rect, paint: &Paint, global: bool, spot: bo let icon = match g.gradient.kind { GradientKind::Linear => "dc-grad-linear", GradientKind::Radial => "dc-grad-radial", + GradientKind::Conic => "dc-grad-conic", + GradientKind::Diamond => "dc-grad-diamond", GradientKind::Freeform => "dc-grad-freeform", }; icons::paint(ui, icon, kind.expand(1.0), t.icon); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index f42c474707..c9dd29efbb 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -1,5 +1,5 @@ -//! Symbols panel: the document's symbols as rendered thumbnails or a list. Click selects a symbol -//! (it becomes the Symbol Sprayer's current symbol); double-click opens it in symbol editing mode. Symbol +//! Symbols panel: the document's symbols as rendered thumbnails or in a small or large list. Click +//! selects a symbol (it becomes the Symbol Sprayer's current symbol); double-click opens it in symbol editing mode. Symbol //! libraries open in library panels ([`SymbolLibraries`]). use std::cell::RefCell; @@ -223,7 +223,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let Some((doc, keys)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d))) else { return }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); - let list: bool = pstate(ui.ctx(), "sym-list"); + let view: View = pstate(ui.ctx(), VIEW); let sel = current(app); let uid = app.session.active().map(|d| d.uid); let marked = marked(ui.ctx(), uid, &names); @@ -237,9 +237,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::empty_state(ui, "spray-can", tl!("No symbols in this document"), tl!("Select art and click New Symbol to make one.")); return ui.min_rect(); } - if list { + if let Some((h, side, text)) = view.row() { for n in &names { - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click_and_drag()); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); // Dragged onto the canvas, the symbol is placed there. widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); if on(n) { @@ -247,8 +247,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } - chip(ui, &doc, &keys, egui::Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(22.0, 22.0)), n); - ui.painter().text(r.left_center() + vec2(32.0, 0.0), egui::Align2::LEFT_CENTER, n, egui::FontId::proportional(12.5), t.text); + chip(ui, &doc, &keys, egui::Rect::from_center_size(r.left_center() + vec2(3.0 + side / 2.0, 0.0), vec2(side, side)), n); + ui.painter().text(r.left_center() + vec2(side + 10.0, 0.0), egui::Align2::LEFT_CENTER, n, egui::FontId::proportional(text), t.text); if resp.double_clicked() { clicked = Some((n.clone(), true)); } else if resp.clicked() { @@ -373,13 +373,18 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } set_pstate(ui.ctx(), MARKED, (uid, unused)); } - ui.separator(); - let list: bool = pstate(ui.ctx(), "sym-list"); - if menu_item(ui, tl!("Thumbnail View"), true, !list) { - set_pstate(ui.ctx(), "sym-list", false); + // The document's symbols in name order, as one undo step. + if menu_item(ui, tl!("Sort by Name"), names.len() > 1, false) + && let Err(e) = app.run("symbol.sortByName", json!({})) + { + app.status(e); } - if menu_item(ui, tl!("List View"), true, list) { - set_pstate(ui.ctx(), "sym-list", true); + ui.separator(); + let view: View = pstate(ui.ctx(), VIEW); + for (v, label) in View::ALL { + if menu_item(ui, tl!(label), true, view == v) { + set_pstate(ui.ctx(), VIEW, v); + } } ui.separator(); ui.menu_button(tl!("Open Symbol Library"), |ui| library_panel::library_menu::(app, ui)); @@ -392,6 +397,32 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { /// The panel state key of the symbols Select All Unused picked. const MARKED: &str = "sym-unused"; +/// The panel state key of the panel's [`View`]. +const VIEW: &str = "sym-view"; + +/// The panel's views: Thumbnail View (the default) and the Small and Large List Views, whose rows +/// show each symbol's thumbnail and name. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum View { + #[default] + Thumbnail, + SmallList, + LargeList, +} + +impl View { + const ALL: [(View, &'static str); 3] = + [(View::Thumbnail, "Thumbnail View"), (View::SmallList, "Small List View"), (View::LargeList, "Large List View")]; + /// Row height, thumbnail side and name size of the list views; None for the thumbnail grid. + fn row(self) -> Option<(f32, f32, f32)> { + match self { + View::Thumbnail => None, + View::SmallList => Some((18.0, 14.0, 12.0)), + View::LargeList => Some((26.0, 22.0, 12.5)), + } + } +} + /// The symbols Select All Unused picked in the active document (`uid`) that it still has (`names`); /// none once another document is active. fn marked(ctx: &egui::Context, uid: Option, names: &[String]) -> Vec { @@ -1022,7 +1053,7 @@ mod tests { vec![egui::Event::PointerMoved(at), button(at, true), button(at, false), button(at, true), button(at, false)] } - /// A double-click on a symbol in the panel, in Thumbnail View and in List View, opens it in + /// A double-click on a symbol in the panel, in Thumbnail View and in Large List View, opens it in /// symbol editing mode and places no instance; a single click only makes it current. #[test] fn double_clicking_a_symbol_in_the_panel_edits_it_in_either_view() { @@ -1041,10 +1072,10 @@ mod tests { assert_eq!(editing(&app).as_deref(), Some("Leaf")); assert_eq!(art(&app, "Leaf").0, 1, "no instance is placed"); app.run("symbol.exitEditing", json!({})).unwrap(); - // List View: the row named Dot. + // Large List View: the row named Dot. let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - set_pstate(&ctx, "sym-list", true); + set_pstate(&ctx, VIEW, View::LargeList); let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 400.0))), ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); out.textures_delta.clear(); @@ -1055,6 +1086,78 @@ mod tests { assert_eq!(art(&app, "Dot").0, 0, "no instance is placed"); } + /// The names the panel draws (none in Thumbnail View) and where, in one headless frame. + fn panel_labels(ctx: &egui::Context, app: &mut VectorcraftApp, names: &[&str]) -> Vec<(String, Pos2)> { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 400.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let labels = crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()); + labels.into_iter().filter(|(t, _)| names.contains(&t.trim())).map(|(t, r)| (t.trim().to_string(), r.center())).collect() + } + + /// The view items of the panel menu, each with whether it is checked. + fn view_items(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<(String, bool)> { + let labels = menu_frame(ctx, app, vec![]); + let items = labels.into_iter().map(|(t, _)| (t.trim_start_matches('✓').trim().to_string(), t.starts_with('✓'))); + items.filter(|(t, _)| t.ends_with("View")).collect() + } + + /// The panel menu's Sort by Name puts the symbols in name order, ignoring case, as one undo + /// step, and adds none when they are already in order. The menu offers Thumbnail View (the + /// default), Small List View and Large List View, one checked at a time. Both list views draw a + /// row with a thumbnail and the name for each symbol, the small one in shorter rows, and in each + /// view a click makes a symbol current and a double-click edits it. + #[test] + fn sort_by_name_and_the_small_and_large_list_views() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (i, name) in ["bee", "Cat", "ant"].into_iter().enumerate() { + app.run("shape.rectangle", json!({"x": 10.0 + 40.0 * i as f64, "y": 10, "width": 30, "height": 20})).unwrap(); + app.run("symbol.new", json!({"name": name})).unwrap(); + } + let undo = app.session.active().unwrap().history.undo.len(); + click_menu(&ctx, &mut app, "Sort by Name"); + assert_eq!(symbols(&mut app), ["ant", "bee", "Cat"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + let views = |checked: &str| ["Thumbnail View", "Small List View", "Large List View"].map(|v| (v.to_string(), v == checked)).to_vec(); + assert_eq!(view_items(&ctx, &mut app), views("Thumbnail View"), "Thumbnail View by default"); + assert!(panel_labels(&ctx, &mut app, &["ant", "bee", "Cat"]).is_empty(), "the thumbnails draw no names"); + // Each list view: a row per symbol in panel order, the small rows 18 points high and the + // large ones 26, with the list's 3-point spacing between them. + let mut gaps = vec![]; + for (view, gap) in [("Small List View", 21.0), ("Large List View", 29.0)] { + click_menu(&ctx, &mut app, view); + assert_eq!(view_items(&ctx, &mut app), views(view)); + let rows = panel_labels(&ctx, &mut app, &["ant", "bee", "Cat"]); + let order: Vec<&str> = rows.iter().map(|(t, _)| t.as_str()).collect(); + assert_eq!(order, ["ant", "bee", "Cat"], "{view}"); + let step = rows[1].1.y - rows[0].1.y; + assert!((step - gap).abs() < 0.5, "{view}: rows {step} apart"); + gaps.push(step); + // A click on the last row makes Cat current, a double-click edits it. + let row = rows[2].1; + app.run("symbol.setCurrent", json!({"name": "ant"})).unwrap(); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(row), button(row, true), button(row, false)]); + assert_eq!((editing(&app), current(&mut app)), (None, Some("Cat".into())), "{view}"); + let ctx2 = egui::Context::default(); + crate::theme::install_fonts(&ctx2); + set_pstate(&ctx2, VIEW, pstate::(&ctx, VIEW)); + frame(&ctx2, &mut app, vec![]); + frame(&ctx2, &mut app, double_click(row)); + assert_eq!(editing(&app).as_deref(), Some("Cat"), "{view}"); + app.run("symbol.exitEditing", json!({})).unwrap(); + } + assert!(gaps[0] < gaps[1], "the small rows are shorter"); + click_menu(&ctx, &mut app, "Thumbnail View"); + assert_eq!(view_items(&ctx, &mut app), views("Thumbnail View")); + // Already in order, Sort by Name adds no undo step. + let undo = app.session.active().unwrap().history.undo.len(); + click_menu(&ctx, &mut app, "Sort by Name"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + /// The panel menu's Edit Symbol edits the selected instance's symbol, and with no instance /// selected the symbol current in the panel. #[test] diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 57a99e433b..6a984a1ced 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -4,9 +4,11 @@ //! same distance. A stop placed or dragged on the ruler lands on the nearest whole point. With Snap //! to Unit on, or Shift held, it lands on the ruler's nearest tick. +use std::collections::HashSet; + use egui::{Sense, Stroke, Ui, vec2}; use serde_json::{Value, json}; -use vectorcraft_doc::{Node, NodeKind, ParaStyle, TabAlign, TabStop, TextKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject}; use super::{first_selected, pstate, set_pstate}; use crate::VectorcraftApp; @@ -18,7 +20,7 @@ const ALIGNS: [(TabAlign, &str); 4] = [(TabAlign::Left, "⇥"), (TabAlign::Cente /// The name of alignment `a`'s button: its tool tip and what screen readers call it. A line of /// vertical type runs from top to bottom, so in vertical type a Left stop is named Top-Justified /// and a Right stop is named Bottom-Justified. -fn align_name(a: TabAlign, vertical: bool) -> &'static str { +pub(crate) fn align_name(a: TabAlign, vertical: bool) -> &'static str { match (a, vertical) { (TabAlign::Left, false) => tl!("Left-Justified Tab"), (TabAlign::Left, true) => tl!("Top-Justified Tab"), @@ -64,40 +66,95 @@ struct IndentTarget { level: f64, } +fn indent_target(id: NodeId, text: &TextObject, i: usize, start: usize) -> IndentTarget { + let para = text.para_at(i); + let left = para.laid_out_left_indent(); + IndentTarget { id: id.0, start, left, first_line: para.first_line_indent, level: left - para.left_indent } +} + fn append_indent_targets(node: &Node, range: std::ops::Range, targets: &mut Vec) { let NodeKind::Text(text) = &node.kind else { return }; let plain = text.plain_text(); let mut starts = vec![0]; starts.extend(plain.bytes().enumerate().filter_map(|(i, c)| (c == b'\n').then_some(i + 1))); - targets.extend(range.filter_map(|i| { - let para = text.para_at(i); - let left = para.laid_out_left_indent(); - Some(IndentTarget { id: node.id.0, start: *starts.get(i)?, left, first_line: para.first_line_indent, level: left - para.left_indent }) - })); + targets.extend(range.filter_map(|i| Some(indent_target(node.id, text, i, *starts.get(i)?)))); } -/// Paragraphs touched by the Type selection (every paragraph of every frame after Select All in -/// threaded text), or all paragraphs of selected text objects. +/// One target for each paragraph of `story` (its frames in thread order), in story order. Where +/// one frame ends and the next begins, the last paragraph of the one and the first of the next are +/// pieces of one story paragraph: a paragraph that runs on into the next frame, or an empty piece +/// after a frame's last paragraph break. Such a paragraph is targeted once, by its last piece with +/// text in a frame that `selected` takes, the piece whose style the story keeps when it flows again. +/// A paragraph whose text lies only in frames that `selected` leaves out is not targeted. An empty +/// paragraph takes its style from its last piece when the story flows again, so it is targeted by +/// that piece when `selected` takes its frame, and otherwise not. +fn append_story_targets(doc: &Document, story: &[NodeId], selected: impl Fn(NodeId) -> bool, targets: &mut Vec) { + /// The part of a story paragraph in one frame: paragraph `index` there, starting at byte `start`. + struct Piece<'a> { + id: NodeId, + text: &'a TextObject, + index: usize, + start: usize, + has_text: bool, + } + // Each story paragraph's pieces, in thread order. + let mut paragraphs: Vec>> = vec![]; + for frame in story.iter().filter_map(|id| doc.node(*id)) { + let NodeKind::Text(text) = &frame.kind else { continue }; + let plain = text.plain_text(); + let mut start = 0; + for (index, part) in plain.split('\n').enumerate() { + let piece = Piece { id: frame.id, text, index, start, has_text: !part.is_empty() }; + start += part.len() + 1; + match paragraphs.last_mut() { + Some(last) if index == 0 => last.push(piece), + _ => paragraphs.push(vec![piece]), + } + } + } + for pieces in ¶graphs { + let pick = if pieces.iter().any(|p| p.has_text) { + pieces.iter().rev().find(|p| p.has_text && selected(p.id)) + } else { + pieces.last().filter(|p| selected(p.id)) + }; + if let Some(p) = pick { + targets.push(indent_target(p.id, p.text, p.index, p.start)); + } + } +} + +/// Paragraphs touched by the Type selection (every paragraph of the story after Select All in +/// threaded text), or all paragraphs of selected text objects. Each paragraph of a threaded story +/// is listed once, in story order ([`append_story_targets`]). fn indent_targets(app: &VectorcraftApp, node: &Node) -> Vec { let mut targets = Vec::new(); if let Some((_, a, b)) = super::character::text_editing(app) { if let (Some(story), Some(st)) = (super::character::text_story(app), app.session.active()) { - for frame in story.iter().filter_map(|id| st.doc.node(*id)) { - if let NodeKind::Text(text) = &frame.kind { - append_indent_targets(frame, 0..text.paragraph_count(), &mut targets); - } - } + append_story_targets(&st.doc, &story, |_| true, &mut targets); } else if let NodeKind::Text(text) = &node.kind { append_indent_targets(node, text.paragraphs_in(a, b), &mut targets); } } else if let Some(st) = app.session.active() { + // The selected text objects and the text in selected groups, each once. + let mut frames = Vec::new(); + let mut taken = HashSet::new(); for selected in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { selected.walk(&mut |child| { - if let NodeKind::Text(text) = &child.kind { - append_indent_targets(child, 0..text.paragraph_count(), &mut targets); + if matches!(child.kind, NodeKind::Text(_)) && taken.insert(child.id) { + frames.push(child.id); } }); } + let mut done = HashSet::new(); + for id in frames { + if done.contains(&id) { + continue; + } + let story = st.doc.story_of(id); + done.extend(story.iter().copied()); + append_story_targets(&st.doc, &story, |f| taken.contains(&f), &mut targets); + } } targets } @@ -629,15 +686,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // A click that lands on a stop's whole point or tick selects that stop and records no // undo step. let added = !stops.iter().any(|s| s.position == position); - if added { - stops.push(TabStop { position, align: ALIGNS[align_idx.min(3)].0, leader: String::new(), align_on: '.' }); - stops.sort_by(|a, b| a.position.total_cmp(&b.position)); - } - let i = stops.iter().position(|s| s.position == position).unwrap_or(0); - set_pstate::>(ui.ctx(), "tabs-marker-sel", None); - set_pstate(ui.ctx(), "tabs-sel", i); - if added { - apply(app, &stops); + let max = TabStop::MAX_STOPS; + if added && stops.len() >= max { + // A full list takes no more stops: the click leaves the stops and the + // selection as they are and shows the limit. + app.status(format!("at most {max} tab stops")); + } else { + if added { + stops.push(TabStop { position, align: ALIGNS[align_idx.min(3)].0, leader: String::new(), align_on: '.' }); + stops.sort_by(|a, b| a.position.total_cmp(&b.position)); + } + let i = stops.iter().position(|s| s.position == position).unwrap_or(0); + set_pstate::>(ui.ctx(), "tabs-marker-sel", None); + set_pstate(ui.ctx(), "tabs-sel", i); + if added { + apply(app, &stops); + } } } } @@ -672,7 +736,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } // Repeat Tab: copies of the selected stop across the ruler, spaced by its distance from the // previous stop, or from the paragraph's left indent plus its list level's indent when it is - // the first stop. + // the first stop. The copies stop at the 256-stop limit, which the status bar then shows. if menu_item(ui, tl!("Repeat Tab"), sel < stops.len() && selected_marker.is_none(), false) { let step = match sel { 0 => (stops[0].position - left_indent).abs(), @@ -681,8 +745,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { .max(1.0); let base = stops[sel].clone(); stops.truncate(sel + 1); + let max = TabStop::MAX_STOPS; let mut pos = base.position + step; while pos <= base.position + step * 20.0 && pos < 2000.0 { + if stops.len() >= max { + app.status(format!("at most {max} tab stops")); + break; + } stops.push(TabStop { position: pos, ..base.clone() }); pos += step; } diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index bc71e34080..97e8c8a00a 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -538,6 +538,139 @@ fn indent_markers_after_select_all_follow_text_that_reflows_into_the_next_frame( } } +/// A story of twelve paragraphs that wrap, threaded through three frames: the first two frames each +/// end inside a paragraph, which runs on into the next frame. → the app and the frames in thread +/// order. +fn split_story_app() -> (VectorcraftApp, [u64; 3]) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 1000})).unwrap(); + // Each paragraph takes more lines than a short frame holds. + let words = "aaa bbb ccc ddd eee fff ggg hhh iii jjj ".repeat(3); + let story = (1..=12).map(|i| format!("p{i} {}", words.trim_end())).collect::>().join("\n"); + let a = app.run("text.create", json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 50}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [300, 10, 150, 50]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [600, 10, 250, 950]})).unwrap()["id"].as_u64().unwrap(); + for id in [b, c] { + assert!(text_of(&app, id).first_para_continues, "frame {id} starts inside a paragraph: {:?}", text_of(&app, id).plain_text()); + } + (app, [a, b, c]) +} + +fn text_of(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::TextObject { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each paragraph of the story of `frames` by its first word, with its left indent and first-line +/// position, counted once; each piece of a paragraph split between frames has the same values. +fn story_paragraphs(app: &VectorcraftApp, frames: &[u64]) -> Vec<(String, f64, f64)> { + let mut out: Vec<(String, f64, f64)> = vec![]; + for (k, id) in frames.iter().enumerate() { + let t = text_of(app, *id); + for (i, text) in t.plain_text().split('\n').enumerate() { + let p = t.para_at(i); + let values = (p.left_indent, p.left_indent + p.first_line_indent); + if i == 0 && k > 0 && t.first_para_continues { + let last = out.last().unwrap(); + assert_eq!((last.1, last.2), values, "both pieces of {} agree", last.0); + } else if !text.is_empty() { + out.push((text.split(' ').next().unwrap_or_default().to_string(), values.0, values.1)); + } + } + } + out +} + +/// Where each target is in the story: its frame's place in `frames` and its start there. +fn story_positions(targets: &[IndentTarget], frames: &[u64]) -> Vec<(usize, usize)> { + targets.iter().map(|p| (frames.iter().position(|f| *f == p.id).unwrap(), p.start)).collect() +} + +/// With the Selection tool on every frame of a threaded story, selected last frame first, the +/// indent markers list each paragraph of the story once, in the story's order, and a marker drag +/// over mixed indents sets every paragraph in one undo step, the two split paragraphs included. +#[test] +fn indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once() { + let (mut app, [a, b, c]) = split_story_app(); + app.run("text.setFormat", json!({"ids": [c], "leftIndent": 10})).unwrap(); + app.run("select.set", json!({"ids": [c, b, a]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), vec![c, b, a]); + let before = story_paragraphs(&app, &[a, b, c]); + assert_eq!(before.len(), 12, "{before:?}"); + assert!(before.iter().any(|p| p.1 == 0.0) && before.iter().any(|p| p.1 == 10.0), "{before:?}"); + let (node, para, span) = current_para(&app).unwrap(); + let targets = indent_targets(&app, &node); + let positions = story_positions(&targets, &[a, b, c]); + assert_eq!(positions.len(), 12, "one target for each paragraph of the story: {positions:?}"); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "the targets follow the story: {positions:?}"); + let undo = app.session.active().unwrap().history.undo.len(); + set_marker(&mut app, IndentMarker::Upper, 60.0, ¶, span, &targets, false); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + let after = story_paragraphs(&app, &[a, b, c]); + assert_eq!(after.iter().map(|p| &p.0).collect::>(), before.iter().map(|p| &p.0).collect::>()); + for (was, now) in before.iter().zip(&after) { + assert_eq!((now.1, now.2), (was.1, 60.0), "{} keeps its left indent and starts at 60 pt: {after:?}", now.0); + } +} + +/// After Select All in threaded text, a paragraph split between two frames is one target. +#[test] +fn indent_markers_after_select_all_list_a_split_paragraph_once() { + let (mut app, [a, b, c]) = split_story_app(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + let ids = [a, b, c].map(vectorcraft_doc::NodeId); + assert_eq!(super::super::character::text_story(&app), Some(ids.to_vec())); + let (node, _, _) = current_para(&app).unwrap(); + let positions = story_positions(&indent_targets(&app, &node), &[a, b, c]); + assert_eq!(positions.len(), 12, "{positions:?}"); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{positions:?}"); +} + +/// With the Selection tool on some frames of a threaded story, only the paragraphs with text in +/// those frames are listed, each once: a selected frame that starts inside a paragraph lists that +/// paragraph, and so does a selected frame that ends inside one. Text in a selected group is +/// listed with the story's frames, and an empty text object keeps its one paragraph. +#[test] +fn indent_markers_on_some_threaded_frames_list_their_paragraphs_once() { + let (mut app, [a, b, c]) = split_story_app(); + let count = |app: &VectorcraftApp, id: u64| text_of(app, id).paragraph_count(); + let targets_of = |app: &mut VectorcraftApp, ids: Vec| { + app.run("select.set", json!({"ids": ids})).unwrap(); + let (node, _, _) = current_para(app).unwrap(); + story_positions(&indent_targets(app, &node), &[a, b, c]) + }; + // The continuing frame alone: its first paragraph is the one the frame before ends inside. + let only_b = targets_of(&mut app, vec![b]); + assert_eq!(only_b.len(), count(&app, b), "{only_b:?}"); + assert_eq!(only_b.first(), Some(&(1, 0)), "{only_b:?}"); + let only_a = targets_of(&mut app, vec![a]); + assert_eq!(only_a.len(), count(&app, a), "{only_a:?}"); + // Two frames that share a paragraph list it once, by the later frame's piece. + let both = targets_of(&mut app, vec![c, a, b]); + assert_eq!(both.len(), count(&app, a) + count(&app, b) + count(&app, c) - 2, "{both:?}"); + assert!(both.windows(2).all(|w| w[0] < w[1]), "{both:?}"); + // The first and last frames of the story, and a grouped empty text object besides. + let empty = app.run("text.create", json!({"x": 10, "y": 900, "text": "", "area": {"width": 100, "height": 40}})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [empty, c]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, a]})).unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)).unwrap().clone(); + let targets = indent_targets(&app, &node); + let ids: Vec = targets.iter().map(|p| p.id).collect(); + assert_eq!(ids.iter().filter(|id| **id == empty).count(), 1, "{ids:?}"); + let story: Vec = targets.into_iter().filter(|p| p.id != empty).collect(); + let positions = story_positions(&story, &[a, b, c]); + assert_eq!(positions.len(), count(&app, a) + count(&app, c), "{positions:?}"); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{positions:?}"); +} + #[test] fn lower_marker_bounds_cover_each_touched_first_line() { let targets = [ @@ -1122,6 +1255,35 @@ fn panel_menu_does_not_change_stops_while_an_indent_marker_is_selected() { assert_eq!(current(&app).unwrap().1, before); } +/// With 256 stops, a click on an empty part of the ruler adds none and shows the limit in the +/// status bar. Repeat Tab near the end of the list adds copies only up to 256 stops and shows the +/// limit too. +#[test] +fn the_ruler_and_repeat_tab_stop_at_256_stops() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + // 250 stops 1 pt apart from 0 pt, then six 2 pt apart from 260 pt. + let start: Vec = (0..250).map(f64::from).chain((0..6).map(|i| 260.0 + 2.0 * f64::from(i))).collect(); + let stops: Vec = start.iter().map(|p| json!({"position": p})).collect(); + app.session.execute("text.tabs.set", &json!({ "stops": stops })).unwrap(); + let ctx = egui::Context::default(); + let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::>(); + set_pstate(&ctx, "tabs-sel", 3usize); + drag_on_ruler(&ctx, &mut app, 290.0, 290.0, false); + assert_eq!(positions(&app), start); + assert_eq!(pstate::(&ctx, "tabs-sel"), 3); + assert_eq!(app.ui.status, "at most 256 tab stops"); + // Repeat Tab on the stop at 260 pt (11 pt past the one before it): five copies, not 20. + app.status(""); + set_pstate(&ctx, "tabs-sel", 250usize); + choose(&ctx, &mut app, "Repeat Tab"); + let repeated = positions(&app); + assert_eq!(repeated.len(), 256); + assert_eq!(repeated[249..], [249.0, 260.0, 271.0, 282.0, 293.0, 304.0, 315.0]); + assert_eq!(app.ui.status, "at most 256 tab stops"); +} + /// Repeat Tab on the first stop spaces the copies by the stop's distance from the paragraph's /// left indent (18 pt further in for each list level past the first), from the paragraph the /// caret is in while the Type tool edits text. diff --git a/crates/ui-egui/src/panels/tests_blend.rs b/crates/ui-egui/src/panels/tests_blend.rs index b79823237b..46521d3a65 100644 --- a/crates/ui-egui/src/panels/tests_blend.rs +++ b/crates/ui-egui/src/panels/tests_blend.rs @@ -1,8 +1,8 @@ //! The Blend panel drawn headless: Window › Blend opens it, and its controls do nothing until the //! selection allows them. Make needs two or more objects, Spacing and Orientation need a blend or -//! two or more objects, and the other buttons need a blend. Make blends the selection, Spacing and -//! Orientation edit the selected blend through `object.blend.options`, and each other button runs -//! its Object › Blend command. +//! two or more objects, and the other buttons need a blend. Make blends the selection, Create Spine +//! sets whether new blends get a spine, Spacing and Orientation edit the selected blend through +//! `object.blend.options`, and each other button runs its Object › Blend command. use egui::{Event, Pos2, Rect, pos2, vec2}; use serde_json::json; @@ -39,6 +39,11 @@ impl Frames { /// The center of the text `label` the panel draws. fn text(&mut self, app: &mut VectorcraftApp, label: &str) -> Pos2 { + self.find_text(app, label).unwrap_or_else(|texts| panic!("no {label:?} in {texts:?}")) + } + + /// The center of the text `label` the panel draws, or every text it draws. + fn find_text(&mut self, app: &mut VectorcraftApp, label: &str) -> Result> { self.run(app, vec![]); let out = self.run(app, vec![]); let mut texts = vec![]; @@ -50,7 +55,7 @@ impl Frames { } } out.shapes.iter().for_each(|c| collect(&c.shape, &mut texts)); - texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")).1.center() + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).ok_or(texts) } /// The center of the button that screen readers name `label`. @@ -124,7 +129,19 @@ fn window_blend_opens_the_panel() { crate::menus::invoke(&mut app, "window.panel", item.params.clone()); assert!(crate::panel_docking::showing(&app.ui, ID)); let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::show_icon_panel(app, ui, ID)); - for label in ["Make", "Spacing:", "Orientation:", "Direction:", "Reverse Front to Back", "Reverse Spine", "Replace Spine", "Expand", "Release"] { + for label in [ + "Make", + "Create Spine:", + "Auto", + "Spacing:", + "Orientation:", + "Direction:", + "Reverse Front to Back", + "Reverse Spine", + "Replace Spine", + "Expand", + "Release", + ] { assert!(text.contains(label), "{label} in {text}"); } assert!(!text.contains("on the roadmap"), "{text}"); @@ -226,6 +243,39 @@ fn each_button_runs_its_blend_command() { assert!(objects.len() >= 2 && objects.iter().all(|(_, blend)| !blend), "the keys are back: {objects:?}"); } +#[test] +fn create_spine_sets_what_new_blends_get_whatever_is_selected() { + let (mut app, id) = blended(); + let (before, depth) = (spec(&app, id), undo_depth(&app)); + let mode = |app: &mut VectorcraftApp| app.session.execute("object.blend.createSpine", &json!({})).unwrap()["mode"].clone(); + let mut f = Frames::new(); + f.text(&mut app, "Create Spine:"); + f.click_text(&mut app, "Auto"); + f.click_text(&mut app, "Never"); + assert_eq!(mode(&mut app), "never"); + assert_eq!((spec(&app, id), undo_depth(&app)), (before, depth), "the selected blend and the undo history stay as they were"); + f.text(&mut app, "Never"); + // Nothing selected: the dropdown still shows and sets the setting. + app.run("select.none", json!({})).unwrap(); + f.click_text(&mut app, "Never"); + f.click_text(&mut app, "Always"); + assert_eq!(mode(&mut app), "always"); + f.click_text(&mut app, "Always"); + f.click_text(&mut app, "Never"); + // A blend made now has no spine: Reverse Spine and easing are dimmed for it. + app.run("edit.undo", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + f.click_text(&mut app, "Make"); + let (g, blend) = top(&app)[0]; + assert!(blend && spec(&app, g).no_spine, "{:?}", top(&app)); + let made = spec(&app, g); + let depth = undo_depth(&app); + f.click_text(&mut app, "Reverse Spine"); + f.click_text(&mut app, "Ease In"); + assert!(f.find_text(&mut app, "Ease Out In").is_err(), "the Type menu did not open"); + assert_eq!((spec(&app, g), undo_depth(&app), app.ui.status.as_str()), (made, depth, ""), "nothing ran"); +} + #[test] fn panel_easing_type_ramp_and_shift_edit_the_blend_and_undo() { // Type and Ramp need a spine: Align to Path gives the blend one. diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 22f863fbd9..4d8959f262 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -127,7 +127,18 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Brush Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.brushLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("art-ribbons"), json!("calligraphic-nibs"), json!("pattern-borders"), json!("scatter-shapes"), json!("game-trails")]); + assert_eq!( + opened, + [ + json!("art-ribbons"), + json!("calligraphic-nibs"), + json!("bristle-brushes"), + json!("pattern-borders"), + json!("scatter-shapes"), + json!("game-trails"), + json!("energy-beams") + ] + ); let enabled = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(enabled("window.brushLibrary.other"), Some(true)); assert_eq!(enabled("ui.saveBrushLibrary"), Some(true), "a new document has the default brushes"); diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index 619be4d70b..e03fc9a59c 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -146,3 +146,23 @@ fn export_says_in_the_status_bar_when_an_image_could_not_be_decoded() { assert_eq!(app.ui.status, format!("Exported /tmp/site/site.css with 1 note: {WARNING}")); assert_eq!(log.borrow().len(), 3, "the sheet and the image's picture are still written"); } + +/// A CSS export with several notes: the status bar names the first, counts them, and keeps every +/// one of them for its hover. +#[test] +fn export_keeps_every_note_for_the_hover() { + let (mut app, _) = app(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); + // Type painted with a gradient is rasterized, and its picture is drawn in the fallback font. + app.run("text.create", json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}})).unwrap(); + let r = app.run("css.exportFile", json!({"path": "/tmp/site/site.css", "scope": "all", "rasterize": true})).unwrap(); + let notes = crate::io::notes_of(&r); + assert_eq!(notes.len(), 2, "{r}"); + assert_eq!(app.ui.status, format!("Exported /tmp/site/site.css with 2 notes: {}", notes[0])); + assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes))); +} diff --git a/crates/ui-egui/src/panels/tests_style_libraries.rs b/crates/ui-egui/src/panels/tests_style_libraries.rs index a776819381..46c274dee6 100644 --- a/crates/ui-egui/src/panels/tests_style_libraries.rs +++ b/crates/ui-egui/src/panels/tests_style_libraries.rs @@ -101,6 +101,30 @@ fn clicking_a_library_style_adds_and_applies_it_in_one_step() { assert!(last_open(&app.ui).is_none()); } +#[test] +fn painted_and_sketched_opens_from_the_window_menu_and_a_click_applies_its_style() { + let mut app = app(); + let entry = crate::menus::menu_entries(&app) + .into_iter() + .find(|e| e.path == ["Window", "Graphic Style Libraries"] && e.label == "Painted and Sketched") + .expect("a Window menu item"); + assert_eq!((entry.command.as_deref(), &entry.params["library"]), (Some("window.graphicStyleLibrary"), &json!("painted-sketched"))); + let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run(entry.command.as_deref().unwrap(), entry.params.clone()).unwrap(); + assert_eq!(last_open(&app.ui).map(|p| (p.kind.as_str(), p.id.as_str())), Some(("graphicStyles", "painted-sketched"))); + let ctx = context(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Charcoal Shade", Modifiers::NONE, 0.0); + let (g, linked) = app.session.selection_graphic_style().expect("applied to the selection"); + assert_eq!((g.name.as_str(), linked), ("Charcoal Shade", true)); + assert_eq!(undo_len(&app), undo + 1, "added and applied as one undo step"); + let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).unwrap().appearance.effects.clone(); + assert_eq!(node.iter().map(|e| e.id.as_str()).collect::>(), ["sketch.charcoal"]); + let lib = GraphicStyleLibraries::get(&app, "painted-sketched").unwrap().1; + let rows = GraphicStyleLibraries::rows(&lib, "ink"); + assert_eq!(rows.iter().map(|r| r.name).collect::>(), ["Ink Contour", "Wet Ink"]); +} + #[test] fn the_window_menu_and_the_panel_open_every_library() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index a6c1cb4cb5..1e71583a4b 100644 --- a/crates/ui-egui/src/panels/tests_symbol_libraries.rs +++ b/crates/ui-egui/src/panels/tests_symbol_libraries.rs @@ -113,7 +113,7 @@ fn the_window_menu_and_the_symbols_panel_open_symbol_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Symbol Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.symbolLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers"), json!("inventory-icons")]); + assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers"), json!("inventory-icons"), json!("skill-icons")]); let has = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(has("window.symbolLibrary.other"), Some(true)); assert_eq!(has("ui.saveSymbolLibrary"), Some(false), "no symbols to save yet"); diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index cee836a385..961c63074c 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -3,7 +3,7 @@ //! Click a style to apply it to the selected text (or the Type tool's selected characters); //! Alt-click applies it and clears overrides. Double-clicking a character style's row opens its //! Character Style Options (`ui.charStyleOptions`), as the panel menu does; a paragraph style's row -//! opens its Paragraph Style Options, the rename dialog the panel menu opens. The style of the +//! opens its Paragraph Style Options (`ui.paraStyleOptions`). The style of the //! selection is highlighted, with a "+" when the text overrides some of its attributes. New makes //! a style from the selected text; Alt-click on New first asks for its name (`ui.newCharStyle`, //! `ui.newParaStyle`). @@ -32,6 +32,7 @@ impl Kind { fn prefix(self) -> &'static str { if self == Kind::Char { "charStyle" } else { "paraStyle" } } + #[cfg(test)] fn what(self) -> &'static str { if self == Kind::Char { "Character" } else { "Paragraph" } } @@ -228,17 +229,11 @@ fn row_look(is_cur: bool, in_highlight: bool, hovered: bool, t: &Tokens) -> (Opt (fill, is_cur && in_highlight) } -/// Opens `name`'s options: Character Style Options for a character style, or the Paragraph Style -/// Options the Paragraph Styles panel menu opens, which rename the style (`ui.paramDialog` runs -/// `paraStyle.rename`). +/// Opens `name`'s options: Character Style Options for a character style, Paragraph Style Options +/// for a paragraph style. fn open_style_options(app: &mut VectorcraftApp, kind: Kind, name: &str) { - if kind == Kind::Char { - app.run("ui.charStyleOptions", json!({ "name": name })).ok(); - } else { - let label = format!("{} Style Options", kind.what()); - app.run("ui.paramDialog", json!({ "command": format!("{}.rename", kind.prefix()), "label": label, "params": { "name": name, "to": name } })) - .ok(); - } + let command = if kind == Kind::Char { "ui.charStyleOptions" } else { "ui.paraStyleOptions" }; + app.run(command, json!({ "name": name })).ok(); } /// The style list and its New and Delete buttons. Shift-click highlights every style from the @@ -251,7 +246,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { let normal = all.first().map(|s| s.0.clone()).unwrap_or_default(); let cur_name = cur.as_ref().map(|(n, _)| n.clone().unwrap_or_else(|| normal.clone())); let mut clicked: Option<(String, egui::Modifiers)> = None; - // A double-clicked Character Style's row, whose options open after the list is laid out. + // A double-clicked style's row, whose options open after the list is laid out. let mut options: Option = None; // Set on a double-click's second click, which must not apply the style again. let mut double_click = false; @@ -299,7 +294,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if resp.clicked() { clicked = Some((name.clone(), ui.input(|i| i.modifiers))); } - // A double-click on a user character style opens its Character Style Options, as the + // A double-click on a user style opens its Character or Paragraph Style Options, as the // panel menu's item does; with Shift, Cmd/Ctrl or Alt held it only follows the click // rules. The second click never applies the style again, also on the Normal style, // which has no options to open. diff --git a/crates/ui-egui/src/panels/text_styles/tests.rs b/crates/ui-egui/src/panels/text_styles/tests.rs index 2fe4ab11fe..6bafa25bbe 100644 --- a/crates/ui-egui/src/panels/text_styles/tests.rs +++ b/crates/ui-egui/src/panels/text_styles/tests.rs @@ -261,9 +261,9 @@ fn click_label(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, mut d app.run_count.wrapping_sub(before) } -/// Double-clicking a user character style's row opens its Character Style Options once: the first -/// click applies the style to the selected text, the second opens the dialog without applying it -/// again. A paragraph style's row opens none, and the built-in Normal style opens none either. +/// Double-clicking a user style's row opens its Character or Paragraph Style Options once: the +/// first click applies the style to the selected text, the second opens the dialog without applying +/// it again. #[test] fn double_clicking_a_character_style_row_opens_its_options() { for kind in [Kind::Char, Kind::Para] { @@ -290,10 +290,10 @@ fn double_clicking_a_character_style_row_opens_its_options() { assert_eq!(app.run_count.wrapping_sub(before), 2, "one apply and the dialog"); } else { let d = dialog.expect("double-clicking a Paragraph Style's row opens its options"); - assert_eq!(d.kind, "command"); - assert_eq!(d.str("__command"), "paraStyle.rename"); - assert_eq!(d.str("__label"), "Paragraph Style Options"); - // One apply from the first click and the rename dialog from the second. + assert_eq!(d.kind, "paraStyleOptions"); + assert_eq!(d.str("__style"), "Body"); + assert_eq!(d.str("section"), "general"); + // One apply from the first click and the dialog from the second. assert_eq!(app.run_count.wrapping_sub(before), 2, "one apply and the dialog"); } } @@ -1007,11 +1007,15 @@ fn new_character_style_without_selection_uses_japanese_defaults() { assert!(!crate::dialogs::char_style_options::edited_attrs(dialog).unwrap().contains_key("charAlign")); crate::dialogs::cancel(&mut app); + let defaults = vectorcraft_engine::cmd::textstyles::default_new_style_attrs(&app.session, true); crate::dialogs::new_text_style::open(&mut app, true, json!({})).unwrap(); - let dialog = app.ui.dialog.as_ref().unwrap(); - assert!(dialog.fields["__target"].get("attrs").is_none()); - assert!(dialog.fields.get("__attrs").is_none()); - crate::dialogs::cancel(&mut app); + let dialog = app.ui.dialog.as_mut().unwrap(); + assert_eq!(dialog.fields["__target"]["attrs"], Value::Object(defaults.clone())); + assert_eq!(crate::dialogs::para_style_options::edited_attrs(dialog).unwrap(), defaults); + dialog.fields.insert("name".into(), json!("Lead")); + crate::dialogs::confirm(&mut app).unwrap(); + let style = app.session.doc().unwrap().doc.para_styles.iter().find(|style| style.name == "Lead").unwrap(); + assert_eq!(style.attrs, defaults, "the new style has the paragraph defaults for the interface language"); } /// The dialog highlights its new style and scrolls the matching panel to its row. diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 2596b218b5..dc1e695481 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -223,7 +223,7 @@ pub(crate) fn selected_guides(app: &VectorcraftApp) -> Option<(Option, Opti return None; } let least = |vertical: bool| { - st.selection.guides.iter().filter_map(|i| st.doc.guides.get(*i)).filter(|g| g.vertical == vertical).map(|g| g.pos).min_by(f64::total_cmp) + st.selection.guides.iter().filter_map(|i| st.doc.ruler_guide(*i)).filter(|g| g.vertical == vertical).map(|g| g.pos).min_by(f64::total_cmp) }; Some((least(true), least(false))) } @@ -581,6 +581,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Measure Type by Glyph Bounds"), true, glyphs) { set_pref(app, "typeGlyphBounds", !glyphs); } + // The active document's Align New Objects to Pixel Grid (`document.setup`). + let align_new = app.session.active().map(|st| st.doc.setup.align_new_objects_to_pixel_grid); + if menu_item(ui, tl!("Align New Objects to Pixel Grid"), align_new.is_some(), align_new == Some(true)) + && let Err(e) = app.run("document.setup", json!({"alignNewObjectsToPixelGrid": align_new != Some(true)})) + { + app.status(e); + } ui.separator(); // What the panel transforms (Transform Object Only / Pattern Only / Both), one checked. let current = pattern_mode(app); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 67cebc7cd2..dd2752cb2b 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -567,3 +567,34 @@ fn align_to_pixel_grid_shows_and_sets_the_property() { app.run("select.set", json!({"ids": [member]})).unwrap(); assert_eq!(pixel_aligned_state(&app).map(|s| s.1), Some(false)); } + +/// The panel menu's Align New Objects to Pixel Grid shows and toggles the active document's +/// setting, follows a switch to another document, and is unavailable with no document open. +#[test] +fn align_new_objects_menu_item_toggles_the_active_document() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let item = "Align New Objects to Pixel Grid"; + let shown = + |ctx: &egui::Context, app: &mut VectorcraftApp| menu_texts(ctx, app).into_iter().find(|t| t.trim_start_matches('✓').trim_start() == item); + assert!(shown(&ctx, &mut app).is_some_and(|t| !t.starts_with('✓')), "no document"); + menu_click(&ctx, &mut app, item); + assert!(app.session.active().is_none()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("file.new", json!({"preset": "Web 1920×1080"})).unwrap(); + let on = |app: &VectorcraftApp, i: usize| app.session.documents()[i].doc.setup.align_new_objects_to_pixel_grid; + assert_eq!((on(&app, 0), on(&app, 1)), (false, true)); + assert!(shown(&ctx, &mut app).is_some_and(|t| t.starts_with('✓')), "the Web document"); + app.session.set_active(0); + assert!(shown(&ctx, &mut app).is_some_and(|t| !t.starts_with('✓')), "the Letter-sized document"); + menu_click(&ctx, &mut app, item); + assert_eq!((on(&app, 0), on(&app, 1)), (true, true)); + assert!(shown(&ctx, &mut app).is_some_and(|t| t.starts_with('✓'))); + let r = app.run("shape.rectangle", json!({"x": 10.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + assert!(app.session.active().unwrap().doc.node(id).unwrap().extras().pixel_aligned); + app.session.set_active(1); + menu_click(&ctx, &mut app, item); + assert_eq!((on(&app, 0), on(&app, 1)), (true, false)); +} diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index 4122c19410..d2b0a26d3f 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -105,6 +105,9 @@ struct Waiting { /// The automation roots in force when it was asked for: the entry runs again under them, not /// with the desktop's access of the frame the answer comes in. scope: ScopeHandle, + /// Automation asked for it ([`VectorcraftApp::automation_asked`]): the entry runs again as + /// automation's ([`as_automated`]). + automated: bool, } /// The app's file dialogs ([`VectorcraftApp`]'s `picks`). @@ -122,6 +125,20 @@ pub(crate) struct Picks { replacing: Option, /// The file that question's OK allows to be replaced while what asked runs again. replace_ok: Option, + /// The files that the OK of the question whether to replace the files a save or export writes + /// beside the one picked allows to be replaced while it runs that again + /// ([`crate::dialogs::confirm::ask_replace_files`]). + pub(crate) replace_files_ok: Vec, + /// The files each document's last save wrote beside its own file, by document uid: its next + /// save replaces them without asking. + pub(crate) written_beside: std::collections::HashMap>, + /// What runs now handles the answer of a file dialog automation opened ([`as_automated`]). + automated: bool, + /// The web's file pickers opened ([`open_async`]) that have not answered yet + /// (`Services::picked_inbox`). + web_opens: u32, + /// Automation opened one of them: their answers are automation's. + web_open_automated: bool, } /// A save dialog's answer that names, once the app gave it an extension, a file that is there. @@ -152,6 +169,24 @@ impl Picks { self.entry = None; self.answer = None; self.replace_ok = None; + self.replace_files_ok.clear(); + self.automated = false; + } + + /// What runs now handles the answer of a file dialog automation opened ([`as_automated`]). + pub(crate) fn automated(&self) -> bool { + self.automated + } + + /// One of the web's file pickers answered (a file, or canceled): whether the answer is + /// automation's. Once none is waiting, the next one the person opens answers for the person. + pub(crate) fn answer_web_open(&mut self) -> bool { + let automated = self.web_open_automated; + self.web_opens = self.web_opens.saturating_sub(1); + if self.web_opens == 0 { + self.web_open_automated = false; + } + automated } /// The kind of dialog open off the UI thread (`ui.inspect`'s `fileDialog`). @@ -188,6 +223,29 @@ pub(crate) fn as_entry(app: &mut VectorcraftApp, entry: impl FnOnce() -> Entr r } +/// Run `f` as handling the answer of a file dialog automation opened when `automated` (and inside +/// one already, as that): [`VectorcraftApp::automation_asked`] is true meanwhile. +pub(crate) fn as_automated(app: &mut VectorcraftApp, automated: bool, f: impl FnOnce(&mut VectorcraftApp) -> R) -> R { + let outer = app.picks.automated; + app.picks.automated = outer || automated; + let r = f(app); + app.picks.automated = outer; + r +} + +/// Opens the web's file picker, whose file arrives later through `Services::picked_inbox`, noting +/// whether automation asked for it ([`VectorcraftApp::automation_asked`]) → false when the host has +/// none. While a picker automation opened has not answered, every answer is automation's, also one +/// to a picker the person opened. +pub(crate) fn open_async(app: &mut VectorcraftApp) -> bool { + let automated = app.automation_asked(); + let Some(f) = app.services.open_async.as_mut() else { return false }; + f(); + app.picks.web_opens += 1; + app.picks.web_open_automated |= automated; + true +} + /// [`as_entry`] for a panel's or a dialog's button that `f` handles. pub(crate) fn button(app: &mut VectorcraftApp, f: impl Fn(&mut VectorcraftApp) + 'static) { let f = Rc::new(f); @@ -319,8 +377,8 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option { match (app.picks.entry.clone(), app.services.start_pick.as_mut()) { (Some(entry), Some(start)) => { if let Some(answer) = start(request.clone()) { - let doc = entry.document(app); - app.picks.waiting = Some(Waiting { request, answer, entry, doc, scope: ScopeHandle::capture() }); + let (doc, automated) = (entry.document(app), app.automation_asked()); + app.picks.waiting = Some(Waiting { request, answer, entry, doc, scope: ScopeHandle::capture(), automated }); return None; } } @@ -367,7 +425,7 @@ pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) { // The dialog's thread is gone: as cancelled. Err(TryRecvError::Disconnected) => vec![], }; - let Some(Waiting { request, entry, doc, scope, .. }) = app.picks.waiting.take() else { return }; + let Some(Waiting { request, entry, doc, scope, automated, .. }) = app.picks.waiting.take() else { return }; app.picks.refused = false; // Once more: what waited for the dialog (files from the Finder, the menu bar) goes on. ctx.request_repaint(); @@ -379,7 +437,7 @@ pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } app.picks.answer = Some((request, answer)); - rerun(app, entry); + as_automated(app, automated, |app| rerun(app, entry)); // An entry that took another way this time leaves the answer unused. app.picks.answer = None; }); @@ -388,7 +446,7 @@ pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) { /// Make the document an entry asked for (`doc`, by its uid) active again before it runs again: /// another may be active by now (opened from the Finder, by an agent), or it may be gone → false /// when it can't run (the status bar says why). -fn on_document(app: &mut VectorcraftApp, doc: Option) -> bool { +pub(crate) fn on_document(app: &mut VectorcraftApp, doc: Option) -> bool { let Some(uid) = doc else { return true }; let Some(i) = app.session.documents().iter().position(|d| d.uid == uid) else { app.status(tl!("The document was closed while its file dialog was open")); diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index ebb42852a9..de9407e2f3 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -577,8 +577,8 @@ pub fn image_summary(i: &Value) -> (String, String) { } /// The Control bar for the one selected image: Linked File or Embedded, its file name, colour mode -/// and effective resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask and -/// Crop Image. Whether one image is selected. +/// and effective resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask, +/// Crop Image and Remove Background. Whether one image is selected. pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool { let Some(i) = selected_image_info(app) else { return false }; let (name, details) = image_summary(i); @@ -595,7 +595,11 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool ui.separator(); link_buttons(app, ui, id, linked, &name, None); crate::panels::image_trace::trace_button(app, ui, crate::panels::image_trace::TRACE_BUTTON_W); - for (label, cmd, w) in [(tl!("Mask"), "object.maskImage", 52.0), (tl!("Crop Image"), "ui.cropImage", 84.0)] { + for (label, cmd, w) in [ + (tl!("Mask"), "object.maskImage", 52.0), + (tl!("Crop Image"), "ui.cropImage", 84.0), + (tl!("Remove Background"), crate::addons::image::REMOVE_BACKGROUND, 128.0), + ] { if widgets::flat_button(ui, label, w).clicked() { crate::menus::invoke(app, cmd, json!({})); } diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index a1711ee8f8..b80f15a9db 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -13,7 +13,9 @@ //! A filter of plug-in API level 2 may report how far it has got (`vc_progress`): the progress //! window then shows a bar with the share done. Its Cancel also makes the filter's `vc_cancelled` //! return 1, so a filter that checks it stops at once; one that doesn't stops at the next slice of -//! its budget. +//! its budget. A light filter that may report its progress (the `progress` permission) and calls +//! no commands runs here too, under its light budget, so its progress and Cancel show while it +//! computes. use std::sync::Arc; use std::sync::mpsc::{Receiver, TryRecvError, channel}; @@ -152,7 +154,7 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { } } -/// The progress window's Cancel (also Esc): every heavy filter running stops (at once when it checks +/// The progress window's Cancel (also Esc): every filter running in the background stops (at once when it checks /// `vc_cancelled`, else at the next slice of its budget) and changes nothing → `{cancelled: n}`. pub fn cancel_all(app: &mut VectorcraftApp) -> Value { let mut n = 0; diff --git a/crates/ui-egui/src/recovery.rs b/crates/ui-egui/src/recovery.rs index 443d4aad3f..f6188babca 100644 --- a/crates/ui-egui/src/recovery.rs +++ b/crates/ui-egui/src/recovery.rs @@ -105,8 +105,8 @@ fn write(app: &mut VectorcraftApp, store: &Arc, pick: impl Fn let mut started = 0; for job in jobs { let (uid, label, title) = (job.uid, format!("Saving recovery data for {}", job.title), job.title.clone()); - let (done, store) = (job.clone(), store.clone()); - let work = move |_: Writer| job.write(store.as_ref()); + let done = job.clone(); + let work = move |_: Writer| job.write(); let then = move |app: &mut VectorcraftApp, r: Result| { let r = r?; done.finish(&mut app.session); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 901c0a3409..3e74ad394f 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -43,10 +43,14 @@ pub type ReadHeadFn = Box Result, String>>; pub type WriteFn = Box Result<(), String>>; -pub type ExistsFn = Box bool>; +/// Shared, so Background Save and Export can check from a worker thread too. +pub type ExistsFn = Arc bool + Send + Sync>; pub type Inbox = Arc)>>>; +/// The web open picker's answers in order: the picked file, or `None` when it was canceled. +pub type PickedInbox = Arc)>>>>; + /// Starts a browser download of the bytes under a file name; an error when it couldn't be started /// (the save or export then fails as a refused write does: #1693). pub type DownloadFn = Box Result<(), String>>; @@ -86,14 +90,21 @@ pub struct Services { pub read_head: Option, pub write: Option, /// Is there a file or folder at a path (desktop)? The app asks before replacing a file that a - /// save panel's name names once the app gives it an extension ([`picks::ask_to_replace`]). - /// Without it, no file counts as there. + /// save panel's name names once the app gives it an extension ([`picks::ask_to_replace`]), and + /// before a save or export replaces a file it writes beside that one (a file per artboard, a + /// linked image). Without it, no file counts as there. pub exists: Option, - /// Files that arrived asynchronously (web open / drops): (name, bytes). + /// Files that arrived asynchronously (web drops): (name, bytes). pub inbox: Option, + /// Web: the open picker's answers (`open_async`). A file opens as automation's when automation + /// opened a picker that has not answered yet. + pub picked_inbox: Option, + /// Web: files the page's script handed over (`window.vectorcraft.openFile`). They open as + /// automation's. + pub page_inbox: Option, /// Web: trigger a browser download instead of writing a path. pub download: Option, - /// Web: start an async open (bytes arrive via `inbox`). + /// Web: start an async open (bytes arrive via `picked_inbox`). pub open_async: Option>, /// Read the system clipboard's text (desktop). Without it, pasted text only arrives with /// egui's Paste event (web, and keyboard paste everywhere). @@ -179,6 +190,10 @@ pub struct Services { /// reports for a window on that monitor. Empty on the web, and where the host cannot place a /// window by these points, which sends floating panels to the main window's monitor. pub dock_monitors: Vec, + /// The text Help › Copy Troubleshooting Info copies (desktop: the platform, the graphics + /// processor, recent commands and frame times, and the hang reports of this session and the + /// one before). Without it the command copies the version only ([`crate::troubleshooting`]). + pub troubleshooting: Option String>>, } /// Rewrites one window's raw input before egui reads it ([`Services::native_input_hook`]). diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index b17a4c47a2..7ada99ee5c 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -374,12 +374,48 @@ pub(crate) struct Snapshot { /// a live-effect or filter plug-in installed later has its row, and one removed has none. pub(crate) fn snapshot() -> Arc { static LAST: Mutex>> = Mutex::new(None); - let revision = menus::plugin_revision(); + let mut revision = menus::plugin_revision(); let last = LAST.lock().unwrap_or_else(|e| e.into_inner()).clone(); - if let Some(s) = last.filter(|s| s.revision == revision) { + // A test's walk hook runs even when a snapshot of this revision is already stored. + #[cfg(test)] + let hooked = { + let f = tests::WHILE_WALKING.take(); + let hooked = f.is_some(); + tests::WHILE_WALKING.set(f); + hooked + }; + #[cfg(not(test))] + let hooked = false; + if let Some(s) = last.filter(|s| s.revision == revision && !hooked) { return s; } + // When a plug-in is installed or removed during the walk, the entries may not match + // `revision`, and the keymap cached for it would lack rows or hold extra ones. The menus are + // walked again at the new revision, and a snapshot that still doesn't match is not cached. + let mut s = build_snapshot(revision); + for _ in 0..8 { + let now = menus::plugin_revision(); + if now == revision { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + // A newer snapshot another thread stored meanwhile stays. + if last.as_ref().is_none_or(|l| l.revision <= revision) { + *last = Some(s.clone()); + } + return s; + } + revision = now; + s = build_snapshot(revision); + } + s +} + +/// The snapshot of the menus as they are now, under plug-in revision `revision`. +fn build_snapshot(revision: u64) -> Arc { // Built without the lock held: the Effect menu is walked anew. + #[cfg(test)] + if let Some(f) = tests::WHILE_WALKING.take() { + f(); + } let effects: Arc<[EffectItem]> = build_effect_items().into(); let filters: Arc<[FilterItem]> = build_filter_items().into(); let (head, tail) = fixed_entries(); @@ -396,13 +432,7 @@ pub(crate) fn snapshot() -> Arc { })) .chain(tail.iter().cloned()) .collect(); - let s = Arc::new(Snapshot { revision, effects, filters, entries }); - let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); - // A newer snapshot another thread stored meanwhile stays. - if last.as_ref().is_none_or(|l| l.revision <= revision) { - *last = Some(s.clone()); - } - s + Arc::new(Snapshot { revision, effects, filters, entries }) } /// Every tool, command and panel the editor can give a shortcut; [`listed`] says which it lists. @@ -1496,6 +1526,39 @@ mod tests { panic!("the installed plug-ins kept changing"); } + thread_local! { + /// Run by [`snapshot`] on this thread once, after it reads the plug-in revision and before + /// it walks the menus. + pub(super) static WHILE_WALKING: std::cell::Cell>> = const { std::cell::Cell::new(None) }; + } + + /// A plug-in installed while the menus are walked doesn't leave a snapshot under the revision + /// read before the walk: the keymap built for that revision would then lack the plug-in's row. + #[test] + fn a_plugin_installed_while_the_menus_are_walked_gets_a_new_snapshot() { + use vectorcraft_plugins::wat as tpl; + let install = |id: &str| { + let manifest = format!(r#"{{"id":"{id}","name":"{id}","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + }; + let (before, during) = ("test.ui.walk-before", "test.ui.walk-during"); + install(before); + // Stores the snapshot of this revision, as another test thread may already have done. + snapshot(); + WHILE_WALKING.set(Some(Box::new(move || { + // Another caller builds the snapshot and keymap of the revision read before the walk. + crate::keymap::template_for(&snapshot()); + install(during); + }))); + let s = snapshot(); + let keys: Vec<&str> = s.entries.iter().map(|e| e.key.as_str()).collect(); + let catalog = crate::keymap::template_for(&s).catalog().len(); + vectorcraft_plugins::registry::remove(before); + vectorcraft_plugins::registry::remove(during); + assert!(keys.contains(&"plugin:test.ui.walk-during"), "the walk lists the plug-in"); + assert_eq!(catalog, s.entries.len(), "the keymap of the snapshot's revision has every entry"); + } + #[test] fn format_parse_round_trip_for_every_default() { for e in entries().iter() { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index df87187a65..83d53d700c 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -194,6 +194,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { } ctx.input(|i| crate::shortcut_editor::note_backtick_text(&i.events)); note_key_surfaces(app, ctx); + forget_opening_key(ctx); let focused = ctx.input(|input| input.focused) || app.forwarded_frame && ctx.viewport_id() == egui::ViewportId::ROOT; // A held tool shortcut that is let go returns to the tool active before it. held_tool::follow(app, ctx, focused); @@ -364,6 +365,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { let ran = !hits.is_empty(); for c in hits { run_hit(app, ctx, &c); + if dialog_or_palette_open(app) { + break; + } } if settings_on_a_mac(app, ctx, mac(ctx)) || ran { return; @@ -423,10 +427,54 @@ fn note_key_surfaces(app: &VectorcraftApp, ctx: &egui::Context) { /// Removes this frame's presses of Enter and Escape when the key went down on something that has /// since changed: the press that opened or closed a dialog, and its repeats until the key is let -/// go, reach neither the new dialog nor what is under the old one. +/// go, reach neither the new dialog nor what is under the old one. Also removes the repeats of a +/// key without a modifier that opened a dialog or the palette ([`hold_back_opening_key`]). pub(crate) fn hold_back_keys(app: &VectorcraftApp, ctx: &egui::Context) { hold_back_key(app, ctx, Key::Enter); hold_back_key(app, ctx, Key::Escape); + hold_back_opening_key(ctx); +} + +/// The key of the mark of a key without a modifier whose command opened a dialog or the palette. +fn opening_key_id(ctx: &egui::Context) -> egui::Id { + egui::Id::unique("opening-key").with(ctx.viewport_id()) +} + +/// Removes this frame's repeats of the key without a modifier that opened a dialog or the +/// palette, and the text they type, until that key is let go: a held key does not type into the +/// field that takes the keyboard. +fn hold_back_opening_key(ctx: &egui::Context) { + let id = opening_key_id(ctx); + let Some(key) = ctx.data(|m| m.get_temp::(id)) else { return }; + let repeat_of = |e: Option<&egui::Event>| matches!(e, Some(egui::Event::Key { key: k, pressed: true, repeat: true, .. }) if *k == key); + ctx.input_mut(|i| { + let typed_by = typing_presses(&i.events); + let held: Vec = i + .events + .iter() + .zip(typed_by) + .map(|(e, by)| repeat_of(Some(e)) || matches!(e, egui::Event::Text(_)) && repeat_of(by.and_then(|k| i.events.get(k)))) + .collect(); + let mut held = held.into_iter(); + i.events.retain(|_| !held.next().unwrap_or(false)); + }); + // A repeat that comes in the same frame as the release is held back above; later presses are new. + let released = + ctx.input(|i| !i.key_down(key) || i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, pressed: false, .. } if *k == key))); + if released { + ctx.data_mut(|m| m.remove::(id)); + } +} + +/// Forgets the key that opened a dialog or the palette ([`hold_back_opening_key`]) once it is up +/// and this frame has none of its events. +fn forget_opening_key(ctx: &egui::Context) { + let id = opening_key_id(ctx); + if let Some(key) = ctx.data(|m| m.get_temp::(id)) + && ctx.input(|i| !i.key_down(key) && !i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, .. } if *k == key))) + { + ctx.data_mut(|m| m.remove::(id)); + } } fn hold_back_key(app: &VectorcraftApp, ctx: &egui::Context, key: Key) { @@ -549,17 +597,30 @@ fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { // Single-key command shortcuts (X, Shift+X, D, /, Shift+D, F, Shift+F by default) before // tools. let Some(hit) = hits.iter().find(|c| !c.id.starts_with("tool:")).or(hits.first()) else { continue }; + // A command runs as it does on a chord ([`run_hit`]): what its menu item runs. Smooth opens + // its slider, and Move opens its dialog. match hit.id.strip_prefix("tool:") { Some(tool) => held_tool::choose(app, ctx, tool, pressed, repeat), - None if let Some((id, p)) = menu_target(hit) => crate::menus::invoke(app, &id, p), - None if hit.params.is_null() => { - let _ = app.run(&hit.id, json!({})); + None => { + run_hit(app, ctx, hit); + if dialog_or_palette_open(app) { + if let Some(key) = pressed { + let id = opening_key_id(ctx); + ctx.data_mut(|m| m.insert_temp(id, key)); + } + break; + } } - None => crate::menus::invoke(app, &hit.id, shortcut_params(hit)), } } } +/// Is a dialog or the palette open? A shortcut that opens one stops the shortcuts after it in the +/// same frame. +fn dialog_or_palette_open(app: &VectorcraftApp) -> bool { + app.ui.dialog.is_some() || app.ui.palette_open +} + /// Route Alt+arrows to spacing controls when text objects are selected. fn alt_type_arrows(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { let m = ctx.input(|i| i.modifiers); @@ -615,6 +676,9 @@ fn type_tool_input(app: &mut VectorcraftApp, ctx: &egui::Context, composing: boo let hits = dispatch(app, ctx, |hit| hit.trigger.chord.mods.cmd); for c in hits { run_hit(app, ctx, &c); + if dialog_or_palette_open(app) { + break; + } } settings_on_a_mac(app, ctx, mac(ctx)); } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 44d438b73b..8d32a4de22 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -292,6 +292,200 @@ fn a_shortcut_runs_what_its_menu_item_runs() { } } +/// Commands whose menu item opens a slider or a dialog before anything changes: the sliders of +/// Smooth and Simplify, Offset Path, the Object › Transform dialogs, Average, Split Into Grid, +/// Vector Halftone, Rearrange All Artboards, Pathfinder Options, Arrange in Grid, Divide into +/// Dashes, Find Nearest Swatch, and four "…" items whose menu entry gives params. +const MENU_DIALOG_COMMANDS: [&str; 22] = [ + "object.path.smooth", + "object.path.simplify", + "object.path.offsetPath", + "object.move", + "object.rotate", + "object.scale", + "object.reflect", + "object.shear", + "object.transformEach", + "path.average", + "path.averageJoin", + "object.path.splitIntoGrid", + "object.vectorHalftone", + "artboard.rearrange", + "object.pathfinder.options", + "addon.arrange.grid", + crate::addons::pathtools::dashes::COMMAND, + crate::addons::color::nearest::COMMAND, + "object.path.cleanUp", + "object.mesh.create", + "type.smartPunctuation", + "edit.findReplace", +]; + +/// F pressed without a modifier. +fn press_f() -> Vec { + vec![ + egui::Event::Key { key: Key::F, physical_key: Some(Key::F), pressed: true, repeat: false, modifiers: Modifiers::NONE }, + egui::Event::Text("f".into()), + ] +} + +/// An app with a selected rectangle where `id` has the shortcut `shortcut` and F runs nothing else. +fn app_with_shortcut(id: &str, shortcut: &str) -> VectorcraftApp { + let mut app = app_with_a_selected_rectangle(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.screenMode", ""); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, id, shortcut); + app.ui.status.clear(); + app +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// A command given a key without a modifier runs what its menu item runs, as it does on a chord: +/// its slider or dialog opens and nothing changes until it is confirmed. +#[test] +fn a_single_key_shortcut_opens_the_dialog_its_menu_item_opens() { + let chord = vec![ + egui::Event::ModifiersChanged(cmd() | Modifiers::ALT | Modifiers::SHIFT), + egui::Event::Key { key: Key::F9, physical_key: None, pressed: true, repeat: false, modifiers: cmd() | Modifiers::ALT | Modifiers::SHIFT }, + ]; + let mut failures = vec![]; + for id in MENU_DIALOG_COMMANDS { + let mut opened = |shortcut: &str, events: Vec| { + let mut app = app_with_shortcut(id, shortcut); + let before = undo_len(&app); + frame(&mut app, events); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + if undo_len(&app) != before { + failures.push(format!("{id} on {shortcut} changed the document: {}", app.ui.status)); + } + app.ui.dialog.as_ref().map(|d| (d.kind.clone(), d.fields.get("__command").cloned())) + }; + let by_key = opened("F", press_f()); + let by_chord = opened("Cmd+Alt+Shift+F9", chord.clone()); + if by_key.is_none() || by_key != by_chord { + failures.push(format!("{id}: F opens {by_key:?}, the chord {by_chord:?}")); + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// Smooth on F opens its slider on a jagged path without smoothing it; confirming the slider keeps +/// the smoothed path as one undo step. +#[test] +fn smooth_on_a_single_key_waits_for_its_slider() { + let mut app = app_with_shortcut("object.path.smooth", "F"); + app.session.execute("edit.clear", &json!({})).unwrap(); + let anchors: Vec<_> = + (0..=60).map(|i| json!({"x": 20 + i * 5, "y": 150.0 + 40.0 * (f64::from(i) / 10.0).sin() + f64::from(i % 2) * 3.0})).collect(); + app.session.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let before = undo_len(&app); + frame(&mut app, press_f()); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + assert_eq!(open_dialog(&app).as_deref(), Some(crate::dialogs::smooth_slider::KIND), "{}", app.ui.status); + assert_eq!(undo_len(&app), before, "the path is not smoothed yet"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_len(&app), before + 1, "the slider's result is one undo step"); +} + +/// A command without a dialog still runs at once on a key without a modifier: Group given F, and +/// Swap Fill and Stroke on its default Shift+X. +#[test] +fn a_single_key_shortcut_without_a_dialog_runs_at_once() { + let mut app = app_with_shortcut("object.group", "F"); + let before = undo_len(&app); + frame(&mut app, press_f()); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + assert_eq!((open_dialog(&app), undo_len(&app)), (None, before + 1), "F groups: {}", app.ui.status); + let mut app = app_with_a_selected_rectangle(); + let before = undo_len(&app); + frame( + &mut app, + vec![ + egui::Event::ModifiersChanged(Modifiers::SHIFT), + egui::Event::Key { key: Key::X, physical_key: Some(Key::X), pressed: true, repeat: false, modifiers: Modifiers::SHIFT }, + egui::Event::Text("X".into()), + ], + ); + assert_eq!((open_dialog(&app), undo_len(&app)), (None, before + 1), "Shift+X swaps fill and stroke: {}", app.ui.status); +} + +/// With no document open, a command's key without a modifier reports what the same command +/// reports on a chord. +#[test] +fn a_single_key_shortcut_reports_what_its_chord_reports() { + let status = |shortcut: &str, events: Vec| { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.screenMode", ""); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "paint.default", shortcut); + app.ui.status.clear(); + frame(&mut app, events); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + (open_dialog(&app), app.ui.status.clone()) + }; + let by_key = status("F", press_f()); + let by_chord = status( + "Cmd+Alt+Shift+F9", + vec![ + egui::Event::ModifiersChanged(cmd() | Modifiers::ALT | Modifiers::SHIFT), + egui::Event::Key { key: Key::F9, physical_key: None, pressed: true, repeat: false, modifiers: cmd() | Modifiers::ALT | Modifiers::SHIFT }, + ], + ); + assert_eq!(by_key, by_chord); + assert!(!by_key.1.is_empty(), "the chord reports something: {by_chord:?}"); +} + +/// Holding a key without a modifier that opens a dialog types nothing into the dialog: neither the +/// key's character nor its repeats reach the field that takes the keyboard. +#[test] +fn holding_a_single_key_that_opens_a_dialog_types_nothing_into_it() { + // Move on F: the dialog and the text of the field with the keyboard after the press, eight + // more frames with F held down (repeating) or not, and the release, which comes in the same + // frame as a last repeat. + let hold = |repeats: bool| { + let mut app = app_with_shortcut("object.move", "F"); + let held = HeldKey::new(Key::F, Modifiers::NONE); + held.frame(&mut app, press_f()); + for _ in 0..8 { + held.frame(&mut app, if repeats { press_f() } else { vec![] }); + } + let release = egui::Event::Key { key: Key::F, physical_key: Some(Key::F), pressed: false, repeat: false, modifiers: Modifiers::NONE }; + held.frame(&mut app, if repeats { [press_f(), vec![release]].concat() } else { vec![release] }); + let field = held.ctx.memory(|m| m.focused()).and_then(|id| held.ctx.data_mut(|d| d.get_temp::(id))); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + (open_dialog(&app), field, app.ui.status.clone()) + }; + let let_go = hold(false); + assert_eq!(let_go.0.as_deref(), Some("move"), "{}", let_go.2); + assert!(let_go.1.is_some(), "its first field has the keyboard"); + assert_eq!(hold(true), let_go, "the held F typed nothing into Move"); +} + +/// A key that opens a dialog stops the keys after it in the same frame: G, given Group, does not +/// group the selection behind Move's dialog. The same holds for chords. +#[test] +fn keys_after_one_that_opens_a_dialog_in_the_same_frame_run_nothing() { + let mods = cmd() | Modifiers::ALT | Modifiers::SHIFT; + let chord = |key: Key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods }; + let single = |key: Key, text: &str| { + [egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }, egui::Event::Text(text.into())] + }; + let runs = [ + ("F", "G", [single(Key::F, "f"), single(Key::G, "g")].concat()), + ("Cmd+Alt+Shift+F9", "Cmd+Alt+Shift+F10", vec![egui::Event::ModifiersChanged(mods), chord(Key::F9), chord(Key::F10)]), + ]; + for (move_key, group_key, events) in runs { + let mut app = app_with_shortcut("object.move", move_key); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "object.group", group_key); + let before = undo_len(&app); + frame(&mut app, events); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + assert_eq!((open_dialog(&app).as_deref(), undo_len(&app)), (Some("move"), before), "{move_key} then {group_key}: {}", app.ui.status); + } +} + /// #2094: Cmd+Shift+O is Type › Create Outlines (not File › Open's Cmd+O, not the Artboard /// tool's Shift+O), with the Selection tool or while the Type tool edits the text. #[test] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 59553120c8..4a0e73da6b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -209,6 +209,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::three_d::ID, "3D and Materials", "dc-cube"), (crate::panels::variables::ID, "Variables", "chart-column"), (crate::panels::script_console::ID, "Script Console", "message-circle"), + (crate::panels::learn::ID, "Learn", "graduation-cap"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), @@ -401,10 +402,17 @@ pub struct UiState { /// Type › Find Font…'s last Find In choice (`find_font::FIND_IN`), kept while the app runs. #[serde(skip)] pub find_font_in: String, + /// The Learn panel's tab, skill and tutorial, kept while the app runs. + #[serde(skip)] + pub learn: crate::panels::learn::View, pub control_bar: bool, /// The Control bar is docked to the bottom of the window instead of the top /// (`window.control.dock`). pub control_bar_bottom: bool, + /// The groups of the Control bar's options (`chrome::CONTROL_BAR_GROUPS`) that its panel menu + /// has off (`window.control.options`); none: every group shows. + #[serde(deserialize_with = "crate::chrome::read_hidden_groups")] + pub control_bar_hidden_groups: std::collections::BTreeSet, pub toolbar: bool, pub toolbar_double: bool, /// Advanced toolbar (every tool group) instead of the categorized Basic toolbar. @@ -533,6 +541,11 @@ pub struct UiState { /// The Replace Font request behind the status bar's warning ([`ReplaceFontWarning`]). Not saved. #[serde(skip)] pub replace_font_warning: Option, + /// The notes of the last open that gave any, or of the last save or export, with the status + /// text that names the first of them: hovering that text lists them when there are several. + /// Not saved. + #[serde(skip)] + pub status_notes: Option<(String, Vec)>, pub palette_open: bool, pub palette_query: String, /// Screen mode: 0 normal, 1 full screen with menu, 2 full screen, 3 presentation. Not saved: @@ -652,6 +665,11 @@ pub struct UiState { /// [`crate::panels::color::deserialize_hide_options`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_hide_options")] pub color_hide_options: bool, + /// Color panel: Show Recent Colors, which draws its Recent Colors row while the options show + /// (`ui.colorPanel`, [`crate::panels::color::deserialize_show_recent_colors`]). The list of + /// recent colors keeps filling while the row is hidden. + #[serde(default = "yes", deserialize_with = "crate::panels::color::deserialize_show_recent_colors")] + pub color_show_recent_colors: bool, /// The SVG Options chosen last (`svg` object of the export/save commands; null: never used). #[serde(default)] pub svg_options: Value, @@ -1017,8 +1035,10 @@ impl Default for UiState { transient_focus: false, color_settings_scroll: false, find_font_in: String::new(), + learn: Default::default(), control_bar: false, control_bar_bottom: false, + control_bar_hidden_groups: Default::default(), toolbar: true, toolbar_double: false, toolbar_advanced: false, @@ -1060,6 +1080,7 @@ impl Default for UiState { group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), status: String::new(), replace_font_warning: None, + status_notes: None, palette_open: false, palette_query: String::new(), screen_mode: 0, @@ -1094,6 +1115,7 @@ impl Default for UiState { align_spacing: 0.0, color_mode: None, color_hide_options: false, + color_show_recent_colors: true, svg_options: Value::Null, place_link: true, dialog_file: None, diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index f725a0819c..26406a4992 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -107,6 +107,27 @@ fn control_saves_take_the_native_save_options() { let _ = std::fs::remove_dir_all(base); } +/// A save without a path writes the document's own file in the write root: `app.save` and +/// `file.save` leave its path out of the reply, since it is outside the read root, and keep a path +/// the client gives. +#[test] +fn control_saves_leave_out_the_documents_file_outside_the_read_root() { + let (mut app, tx, base) = confined("save-own"); + app.run("file.new", json!({"width": 100, "height": 50})).unwrap(); + let own = s(base.join("out/doc.vectorcraft")); + app.run("file.saveAs", json!({"path": own})).unwrap(); + for (method, params) in [("app.save", json!({})), ("engine.execute", json!({"command": "file.save", "params": {}}))] { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let r = request(&mut app, &tx, method, params); + assert_eq!(r["ok"], true, "{method}: {r}"); + assert!(r["result"].get("path").is_none() && !r.to_string().contains(&s(base.join("out"))), "{method}: {r}"); + assert_eq!(app.session.active().map(|d| d.is_dirty()), Some(false), "{method}: saved"); + } + let r = request(&mut app, &tx, "app.save", json!({"path": own})); + assert_eq!(r["result"]["path"], json!(own), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + /// With Background Save and Background Export on, `app.save` and `app.export` with `wait: true` /// (MCP's `save_file` in the app) reply with the write root's refusal, and write a file inside it /// before they reply. Without `wait` the refusal reaches only the status bar. @@ -425,6 +446,33 @@ fn ui_inspect_leaves_out_paths_outside_the_read_root() { let _ = std::fs::remove_dir_all(base); } +/// Two libraries loaded from outside the read root under the same file name, only the second of them +/// in a library panel: `ui.inspect` and `swatch.library.list` show the second under the same id, and +/// that id finds it. +#[test] +fn ui_inspect_and_library_commands_show_a_hidden_library_under_one_id() { + let (mut app, tx, base) = confined("one-id"); + let (x, y) = (base.join("outside/x/Kit.gpl"), base.join("outside/y/Kit.gpl")); + for (path, colors) in [(&x, "0 0 0 Black\n"), (&y, "0 0 0 Black\n255 255 255 White\n")] { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, format!("GIMP Palette\nName: Kit\n{colors}")).unwrap(); + app.session.execute("swatch.library.load", &json!({"path": s(path.clone())})).unwrap(); + } + let second = format!("loaded/{}", s(y.clone())); + app.ui.library_panels = vec![serde_json::from_value(json!({"kind": "swatches", "id": second, "path": s(y.clone())})).unwrap()]; + + let r = request(&mut app, &tx, "ui.inspect", json!({})); + assert_eq!(r["result"]["ui"]["library_panels"][0]["id"], "loaded/Kit.gpl (2)", "{r}"); + let r = request(&mut app, &tx, "engine.execute", json!({"command": "swatch.library.list", "params": {}})); + let libs = r["result"]["libraries"].as_array().unwrap_or_else(|| panic!("{r}")); + let loaded: Vec<&Value> = libs.iter().filter(|l| l["category"] == "loaded").map(|l| &l["id"]).collect(); + assert_eq!(loaded, [&json!("loaded/Kit.gpl"), &json!("loaded/Kit.gpl (2)")], "{r}"); + let r = request(&mut app, &tx, "engine.execute", json!({"command": "swatch.library.get", "params": {"library": "loaded/Kit.gpl (2)"}})); + assert_eq!(r["result"]["swatches"].as_array().map(Vec::len), Some(2), "the second library: {r}"); + assert!(!r.to_string().contains("outside"), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + /// A closed panel's former place, as `ui.docking_hidden` keeps it. fn hidden_place() -> craft_ui::docking::Location { serde_json::from_value(json!({"floating": null, "anchor": null, "placement": {"Tab": {"before": null}}, "size": null, "stack": null})).unwrap() @@ -603,9 +651,11 @@ fn an_unidentifiable_stale_injected_batch_fails_closed() { let _ = std::fs::remove_dir_all(base); } -/// A plug-in's permissions are approved only by a person. A control request (or MCP, which comes -/// through it) can't pass `grant`, can't answer the approval dialog or rewrite what it installs, -/// and a frame of synthetic input can't press its OK; the person at the keyboard can. +/// A plug-in's permissions are approved only by a person who asked for the install. A control +/// request (or MCP, which comes through it) can't pass `grant`, can't answer the approval dialog or +/// rewrite what it installs, and a frame of synthetic input can't press its OK. The person can't +/// approve the question automation asked either: they start Install Plug-in… themselves, which asks +/// again, and its OK installs. #[test] fn automation_cannot_approve_a_plugin_install() { let (tx, rx) = std::sync::mpsc::channel(); @@ -623,8 +673,9 @@ fn automation_cannot_approve_a_plugin_install() { let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {"dataBase64": data}})); assert_eq!(r["result"]["pending"], crate::dialogs::plugin::INSTALL_KIND, "{r}"); + assert_eq!(r["result"]["approval"], crate::dialogs::plugin::PERSON_MUST_START_INSTALL, "{r}"); let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); - refused(&r, "Only the person at the keyboard"); + refused(&r, ASKED); assert!(app.ui.dialog.is_some(), "the refused answer leaves it open"); assert!(vectorcraft_plugins::registry::get(id).is_none()); @@ -635,18 +686,293 @@ fn automation_cannot_approve_a_plugin_install() { let r = request(&mut app, &tx, "ui.dialog.set", json!({"fields": [{"field": "__params", "value": {"dataBase64": "AAAA"}}]})); assert!(r.get("error").is_none(), "{r}"); let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); - refused(&r, "Only the person at the keyboard"); + refused(&r, ASKED); assert!(app.ui.dialog.is_some() && vectorcraft_plugins::registry::get(id).is_none()); + // Shown for long enough for a person's OK, it still refuses automation, and the person too. + super::plugins::show_approval(&mut app); + let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); + refused(&r, ASKED); app.synthetic_frame = true; - assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains("Only the person at the keyboard")); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED)); assert!(vectorcraft_plugins::registry::get(id).is_none()); app.synthetic_frame = false; + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "a person's OK on automation's question"); + assert!(app.ui.dialog.is_some() && vectorcraft_plugins::registry::get(id).is_none() && vectorcraft_plugins::registry::granted(id).is_none()); + // The person starts Install Plug-in… with the file: a new question, which a person's OK approves + // once it was shown for the delay, and which automation still can't. + let r = app.run("ui.installPlugin", json!({"dataBase64": data})).unwrap(); + assert_eq!(r, json!({"pending": crate::dialogs::plugin::INSTALL_KIND}), "the person's question"); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap()["pending"], crate::dialogs::plugin::INSTALL_KIND, "not shown yet"); + super::plugins::show_approval(&mut app); + let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); + refused(&r, "Only the person at the keyboard"); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&bytes))); app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// The refusal of an OK on an install question automation asked. +const ASKED: &str = "Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself."; + +/// The approval module `id` that lists `doc.read`, and its bytes as base64. +fn approval_module(id: &str) -> (Vec, String) { + let manifest = format!(r#"{{"id":"{id}","name":"Approval","version":"1","kind":"filter","permissions":["doc.read"]}}"#); + let bytes = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let data = vectorcraft_format::base64_encode(&bytes); + (bytes, data) +} + +/// An install question that a control request asked keeps OK disabled in the person's window, even +/// once it was shown for the delay: a person's click, Enter or Space install nothing, and the dialog +/// says to start Install Plug-in…. Cancel still closes it at once. +#[test] +fn a_person_cannot_approve_an_install_question_automation_asked() { + use super::plugins::{at, click_ok, ok_enabled, waiting, window}; + use egui_kittest::kittest::Queryable; + let id = "test.ui.approval.asked"; + let (tx, rx) = std::sync::mpsc::channel(); + let app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + let mut h = window(app); + let (_, data) = approval_module(id); + let r = request(h.state_mut(), &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {"dataBase64": data}})); + assert_eq!(r["result"]["approval"], crate::dialogs::plugin::PERSON_MUST_START_INSTALL, "{r}"); + at(&mut h, 10.0); + at(&mut h, 10.0); + at(&mut h, 10.6); + assert!(!ok_enabled(&h), "OK stays disabled past the delay"); + assert!(h.query_by_label(ASKED).is_some(), "the dialog says what to do"); + click_ok(&mut h, 10.7); + at(&mut h, 10.8); + assert!(waiting(h.state(), id), "a person's click"); + for (key, time) in [(egui::Key::Enter, 10.9), (egui::Key::Space, 11.0)] { + h.key_press(key); + at(&mut h, time); + assert!(waiting(h.state(), id), "{key:?}"); + } + assert!(crate::dialogs::confirm(h.state_mut()).unwrap_err().contains(ASKED), "a confirm that skips the button"); + assert!(waiting(h.state(), id)); + h.get_by_label("Cancel").click(); + at(&mut h, 11.1); + assert!(h.state().ui.dialog.is_none() && h.state().pending_plugin_install.is_none(), "Cancel"); + assert!(vectorcraft_plugins::registry::get(id).is_none() && vectorcraft_plugins::registry::granted(id).is_none()); +} + +/// A question automation asks in place of the one a person asked can't be approved: it keeps +/// automation's origin, though the person's question was shown and ready. +#[test] +fn automation_replacing_a_persons_install_question_does_not_take_its_approval() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + let (mine, theirs) = ("test.ui.approval.mine", "test.ui.approval.theirs"); + app.run("ui.installPlugin", json!({"dataBase64": approval_module(mine).1})).unwrap(); + super::plugins::show_approval(&mut app); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {"dataBase64": approval_module(theirs).1}})); + assert_eq!(r["result"]["approval"], crate::dialogs::plugin::PERSON_MUST_START_INSTALL, "{r}"); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED)); + for id in [mine, theirs] { + assert!(vectorcraft_plugins::registry::get(id).is_none() && vectorcraft_plugins::registry::granted(id).is_none(), "{id}"); + } + // Asked again by automation with the same file, it is still automation's. + let r = request(&mut app, &tx, "engine.execute", json!({"command": "ui.installPlugin", "params": {"dataBase64": approval_module(mine).1}})); + assert_eq!(r["result"]["approval"], crate::dialogs::plugin::PERSON_MUST_START_INSTALL, "{r}"); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED)); + assert!(vectorcraft_plugins::registry::get(mine).is_none()); +} + +/// A file a person picks in the file dialog that a control request opened (Install Plug-in… or +/// File › Open with no path) is automation's request: its question can't be approved. The file +/// dialog a person opens asks a question they can approve. On the desktop the dialog answers later +/// ([`crate::picks`]); on the web the file arrives through the picker's inbox, apart from drops and +/// the page's script, which is automation. +#[test] +fn a_file_picked_in_a_dialog_automation_opened_stays_automations() { + let base = std::env::temp_dir().join(format!("vc-ui-approval-picked-{}", std::process::id())); + std::fs::create_dir_all(&base).unwrap(); + let (desktop, web) = ("test.ui.approval.picked", "test.ui.approval.picked.web"); + let (bytes, _) = approval_module(desktop); + let wasm = base.join("picked.wasm"); + std::fs::write(&wasm, &bytes).unwrap(); + let mut services = Services::default(); + let (shown, _) = super::picks::off_the_ui_thread(&mut services); + services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), services).with_control(rx); + let pick = |app: &mut VectorcraftApp| { + shown.answer(&[&s(wasm.clone())]); + crate::picks::poll(app, &egui::Context::default()); + }; + for command in ["ui.installPlugin", "file.open"] { + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": command, "params": {}})); + assert!(app.file_dialog_open(), "{command}: {r}"); + pick(&mut app); + assert!(super::plugins::waiting(&app, desktop), "{command}: {:?}", app.ui.status); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "{command}"); + crate::dialogs::cancel(&mut app); + } + let _ = app.run("ui.installPlugin", json!({})); + assert!(app.file_dialog_open()); + pick(&mut app); + super::plugins::show_approval(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(vectorcraft_plugins::registry::granted(desktop).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&bytes))); + app.run("plugin.remove", json!({"id": desktop})).unwrap(); + + // The web: the browser's file picker answers through its own inbox, apart from the files a + // person drops and the ones the page's script hands over. + let (dropped, page) = <(crate::services::Inbox, crate::services::Inbox)>::default(); + let picked = crate::services::PickedInbox::default(); + let services = Services { + open_async: Some(Box::new(|| {})), + inbox: Some(dropped.clone()), + picked_inbox: Some(picked.clone()), + page_inbox: Some(page.clone()), + ..Default::default() + }; + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), services).with_control(rx); + let (by_drop, by_page) = ("test.ui.approval.picked.dropped", "test.ui.approval.picked.page"); + let file = |id: &str| (format!("{id}.wasm"), approval_module(id).0); + let hand_over = |app: &mut VectorcraftApp, inbox: &crate::services::Inbox, id: &str| { + inbox.lock().unwrap().push(file(id)); + app.drain_inbox(); + }; + // The picker answers with a file, or `None` when it is canceled. + let answer = |app: &mut VectorcraftApp, id: Option<&str>| { + picked.lock().unwrap().push(id.map(file)); + app.drain_inbox(); + }; + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {}})); + assert!(r.get("error").is_none(), "{r}"); + // A file the person drops before the picker answers stays the person's. + hand_over(&mut app, &dropped, by_drop); + super::plugins::show_approval(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(vectorcraft_plugins::registry::granted(by_drop).is_some()); + answer(&mut app, Some(web)); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "the web"); + crate::dialogs::cancel(&mut app); + app.run("ui.installPlugin", json!({})).unwrap(); + answer(&mut app, Some(web)); + super::plugins::show_approval(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(vectorcraft_plugins::registry::granted(web).is_some()); + // Opening the picker again as the person before it answers automation leaves the answer + // automation's. + let (again, after) = ("test.ui.approval.picked.again", "test.ui.approval.picked.after"); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {}})); + assert!(r.get("error").is_none(), "{r}"); + app.run("ui.installPlugin", json!({})).unwrap(); + answer(&mut app, Some(again)); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "opened again"); + crate::dialogs::cancel(&mut app); + // Once the other picker is canceled, the next one the person opens answers for them again. + answer(&mut app, None); + app.run("ui.installPlugin", json!({})).unwrap(); + answer(&mut app, Some(after)); + super::plugins::show_approval(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(vectorcraft_plugins::registry::granted(after).is_some()); + // The page's script is automation. + hand_over(&mut app, &page, by_page); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "the page's script"); + crate::dialogs::cancel(&mut app); + assert!(vectorcraft_plugins::registry::granted(by_page).is_none()); + for id in [web, by_drop, after] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A `.wasm` that a control request opens by path (`app.open`) asks a question that can't be +/// approved; one the person opens can be. +#[test] +fn a_plugin_automation_opened_by_path_asks_a_question_no_one_approves() { + let base = std::env::temp_dir().join(format!("vc-ui-approval-open-{}", std::process::id())); + std::fs::create_dir_all(&base).unwrap(); + let id = "test.ui.approval.opened"; + let (bytes, _) = approval_module(id); + let wasm = base.join("opened.wasm"); + std::fs::write(&wasm, &bytes).unwrap(); + let services = Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), ..Default::default() }; + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), services).with_control(rx); + let r = request(&mut app, &tx, "app.open", json!({"path": s(wasm.clone())})); + assert!(r.get("error").is_none(), "{r}"); + assert!(super::plugins::waiting(&app, id)); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED)); + crate::dialogs::cancel(&mut app); + crate::io::open_path(&mut app, &s(wasm.clone())).unwrap(); + super::plugins::show_approval(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(vectorcraft_plugins::registry::granted(id).is_some()); + app.run("plugin.remove", json!({"id": id})).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// A module that takes the place of another with its id, and asks for nothing else: automation's +/// `replace: true` doesn't skip the question and its question can't be approved. The question a +/// person asked keeps what it installs out of reach of `ui.dialog.set`, refuses a control confirm, +/// and the person's own OK replaces. +#[test] +fn automation_cannot_approve_replacing_a_plugin() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + let id = "test.ui.approval.replaced"; + let plain = |output: &str| { + wat::parse_str(vectorcraft_plugins::wat::returning(&format!(r#"{{"id":"{id}","name":"Plain","kind":"filter"}}"#), output)).unwrap() + }; + let (first, other) = (plain(r#"{"objects":[]}"#), plain(r#"{"objects":[],"error":null}"#)); + let installed = || vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()); + let first_hash = vectorcraft_plugins::permissions::sha256_hex(&first); + let data = vectorcraft_format::base64_encode(&other); + app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&first)})).unwrap(); + assert_eq!(installed(), Some(first_hash.clone())); + + for params in [json!({"dataBase64": data}), json!({"dataBase64": data, "replace": true})] { + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": params})); + assert_eq!(r["result"]["pending"], crate::dialogs::plugin::INSTALL_KIND, "{params}: {r}"); + assert_eq!(r["result"]["approval"], crate::dialogs::plugin::PERSON_MUST_START_INSTALL, "{params}: {r}"); + let pending = app.pending_plugin_install.as_ref().unwrap(); + assert_eq!(pending.message, "Install “Plain” in place of the plug-in with the same ID?"); + super::plugins::show_approval(&mut app); + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "{params}"); + let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); + assert!(r["error"].as_str().is_some_and(|e| e.contains(ASKED)), "{r}"); + crate::dialogs::cancel(&mut app); + assert_eq!(installed(), Some(first_hash.clone()), "{params}"); + } + + // The person's question: a control request can't point its OK at other bytes, nor press it. + let r = app.run("ui.installPlugin", json!({"dataBase64": data})).unwrap(); + assert_eq!(r, json!({"pending": crate::dialogs::plugin::INSTALL_KIND})); + let evil = vectorcraft_format::base64_encode(&plain(r#"{"objects":[{"name":"x"}]}"#)); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"fields": [{"field": "__params", "value": {"dataBase64": evil, "replace": true}}]})); + assert!(r.get("error").is_none(), "{r}"); + super::plugins::show_approval(&mut app); + let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); + assert!(r["error"].as_str().is_some_and(|e| e.contains("Only the person at the keyboard")), "{r}"); + assert_eq!(installed(), Some(first_hash.clone())); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(installed(), Some(vectorcraft_plugins::permissions::sha256_hex(&other)), "the bytes the question showed"); + app.run("plugin.remove", json!({"id": id})).unwrap(); + // A module that asks for nothing still installs at once when automation asks. + let free = "test.ui.approval.free"; + let module = wat::parse_str(vectorcraft_plugins::wat::returning(&format!(r#"{{"id":"{free}","name":"Free","kind":"filter"}}"#), "{}")).unwrap(); + let params = json!({"dataBase64": vectorcraft_format::base64_encode(&module)}); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": params})); + assert!(r["result"]["pending"].is_null() && app.ui.dialog.is_none(), "{r}"); + assert!(vectorcraft_plugins::registry::get(free).is_some()); + app.run("plugin.remove", json!({"id": free})).unwrap(); +} + type DialogHarness = egui_kittest::Harness<'static, VectorcraftApp>; /// Runs one UI pass of `h` for each batch of synthetic input the control path queued, each taken @@ -671,10 +997,10 @@ fn still_waiting(h: &DialogHarness, id: &str) -> bool { && vectorcraft_plugins::registry::granted(id).is_none() } -/// Keys and pointer input sent through the control path approve nothing at the open install -/// approval: Enter and Space press nothing with no button focused, and with OK focused they and a -/// `ui.click` on it press it and are refused. `ui.pointer` drives the canvas. A person's click on -/// the same button approves. +/// Keys and pointer input sent through the control path approve nothing at the install approval a +/// person asked for: Enter and Space press nothing with no button focused, and with OK focused they +/// and a `ui.click` on it press it and are refused. `ui.pointer` drives the canvas. A person's click +/// on the same button approves. #[test] fn injected_keys_and_pointer_input_cannot_approve_a_plugin_install() { use egui_kittest::kittest::{NodeT, Queryable}; @@ -686,8 +1012,8 @@ fn injected_keys_and_pointer_input_cannot_approve_a_plugin_install() { let manifest = format!(r#"{{"id":"{id}","name":"Approval","version":"1","kind":"filter","permissions":["doc.read"]}}"#); let bytes = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); let data = vectorcraft_format::base64_encode(&bytes); - let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {"dataBase64": data}})); - assert_eq!(r["result"]["pending"], crate::dialogs::plugin::INSTALL_KIND, "{r}"); + let r = app.run("ui.installPlugin", json!({"dataBase64": data})).unwrap(); + assert_eq!(r, json!({"pending": crate::dialogs::plugin::INSTALL_KIND}), "the person's question"); let mut fonts = false; let mut h: DialogHarness = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { diff --git a/crates/ui-egui/src/tests/background.rs b/crates/ui-egui/src/tests/background.rs index add53156e8..a71a55d1fe 100644 --- a/crates/ui-egui/src/tests/background.rs +++ b/crates/ui-egui/src/tests/background.rs @@ -122,6 +122,29 @@ fn exports_run_in_the_background_and_the_preference_turns_both_off() { assert!(app.background.jobs.is_empty()); } +/// A Background Export with a file per artboard checks for files there from its worker: one with +/// an artboard file's name is asked about once the export ends, before anything is written, and +/// the question's OK writes every file. +#[test] +fn a_background_export_asks_before_replacing_an_artboard_file() { + let gate = Gate::default(); + let (mut app, files) = app(gate.clone()); + app.services.exists = Some(Arc::new(|p: &str| p == "/out/a-B.png")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80, "name": "B"})).unwrap(); + let r = io::export(&mut app, Some("png"), Some("/out/a.png".into()), &json!({"useArtboards": true})).unwrap(); + assert_eq!(r["background"].as_bool(), Some(true), "{r}"); + gate.open(); + background::wait_all(&mut app); + assert!(files.lock().unwrap().is_empty(), "nothing is written while it asks"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("message").as_str()), (crate::dialogs::confirm::REPLACE_FILES, "“a-B.png” already exists. Replace it?")); + crate::dialogs::confirm(&mut app).unwrap(); + background::wait_all(&mut app); + let names: Vec = files.lock().unwrap().iter().map(|(p, _)| p.clone()).collect(); + assert_eq!(names, ["/out/a-Artboard-1.png", "/out/a-B.png"]); +} + /// A save that returns before the file is written still says what it writes and which options it /// does not use, as `app.save` (MCP's `save_file`) replies with it: what the format loses first, as /// the reply of a save written at once. diff --git a/crates/ui-egui/src/tests/guide_escape.rs b/crates/ui-egui/src/tests/guide_escape.rs index 90c77f47dd..113d2b1e2f 100644 --- a/crates/ui-egui/src/tests/guide_escape.rs +++ b/crates/ui-egui/src/tests/guide_escape.rs @@ -90,7 +90,7 @@ impl GuideDrag { let point = |at| if vertical { Point::new(at, 60.0) } else { Point::new(60.0, at) }; (f.from, f.to, f.end) = (xf.to_screen(point(100.0)), xf.to_screen(point(140.0)), xf.to_screen(point(160.0))); assert!([f.from, f.to, f.end].into_iter().all(|p| rect.contains(p))); - assert_eq!(f.selection.guides, vec![0, 1]); + assert_eq!(vectorcraft_engine::cmd::guide_indexes(&f.before, &f.selection.guides), vec![0, 1]); f.app.session.active_mut().unwrap().mark_saved(); f.unchanged(); f @@ -140,17 +140,30 @@ impl GuideDrag { } fn guides_at_target(&self) { - let mut moved = self.before.guides.clone(); + let line = |g: &vectorcraft_doc::Guide| (g.vertical, g.pos, g.artboard, g.layer); + let before: Vec<_> = self.before.ruler_guides().iter().map(line).collect(); + let mut moved = before.clone(); for guide in &mut moved { - if guide.vertical == self.vertical { - guide.pos += 40.0; + if guide.0 == self.vertical { + guide.1 += 40.0; } } - let expected = if self.copy { self.before.guides.iter().cloned().chain(moved).collect::>() } else { moved }; + let expected = if self.copy { before.into_iter().chain(moved).collect::>() } else { moved }; let st = self.app.session.active().unwrap(); - assert_eq!(st.doc.guides, expected); - assert_eq!(st.doc.layers, self.before.layers); - assert_eq!(st.selection.guides, if self.copy { vec![2, 3] } else { vec![0, 1] }); + assert_eq!(st.doc.ruler_guides().iter().map(line).collect::>(), expected); + let art = |d: &vectorcraft_doc::Document| { + d.layers + .iter() + .map(|l| { + let mut l = vectorcraft_doc::Node::clone(l); + l.strip_ruler_guides(); + l + }) + .collect::>() + }; + assert_eq!(art(&st.doc), art(&self.before)); + let selected = vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides); + assert_eq!(selected, if self.copy { vec![2, 3] } else { vec![0, 1] }); } fn unchanged(&self) { diff --git a/crates/ui-egui/src/tests/nativeoptions.rs b/crates/ui-egui/src/tests/nativeoptions.rs index 5f136d514c..e97443eb36 100644 --- a/crates/ui-egui/src/tests/nativeoptions.rs +++ b/crates/ui-egui/src/tests/nativeoptions.rs @@ -64,6 +64,98 @@ fn save_as_native_asks_for_its_options_and_writes_every_artboard() { assert_eq!(written.borrow().len(), 10); } +/// The paths written so far. +fn names(written: &crate::tests_svg::Written) -> Vec { + written.borrow().iter().map(|(p, _)| p.clone()).collect() +} + +/// Save As with a file per artboard: a file there with an artboard file's name, which the save +/// panel did not ask about, is asked about before anything is written. Cancel writes nothing; OK +/// writes every file, and Save to the document's own file then writes them again without asking. +#[test] +fn save_as_asks_before_replacing_an_artboard_file_that_is_there() { + let (mut app, written) = app("/tmp/doc.vectorcraft"); + three_boards(&mut app); + let there = ["/tmp/doc-B.vectorcraft", "/tmp/doc-D.vectorcraft", "/tmp/doc-E.vectorcraft"]; + app.services.exists = Some(std::sync::Arc::new(move |p: &str| there.contains(&p))); + let pick = |app: &mut crate::VectorcraftApp| { + app.run("file.saveAs", Value::Null).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("separateArtboards".into(), json!(true)); + d.fields.insert("all".into(), json!(true)); + dialogs::confirm(app).unwrap() + }; + let r = pick(&mut app); + assert_eq!(r["pending"], dialogs::confirm::REPLACE_FILES, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("message").as_str()), (dialogs::confirm::REPLACE_FILES, "“doc-B.vectorcraft” already exists. Replace it?")); + assert_eq!(d.fields["files"], json!(["/tmp/doc-B.vectorcraft"])); + assert!(written.borrow().is_empty(), "nothing is written while it asks"); + dialogs::cancel(&mut app); + assert!(written.borrow().is_empty(), "Cancel writes nothing"); + assert!(app.session.active().unwrap().path.is_none()); + pick(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/tmp/doc.vectorcraft", "/tmp/doc-Artboard-1.vectorcraft", "/tmp/doc-B.vectorcraft", "/tmp/doc-C.vectorcraft"]); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/tmp/doc.vectorcraft")); + app.run("file.save", Value::Null).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(written.borrow().len(), 8); + // A new artboard's file is not one the last save wrote: Save asks about it alone. + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 100, "height": 80, "name": "D"})).unwrap(); + let r = app.run("file.save", Value::Null).unwrap(); + assert_eq!(r["pending"], dialogs::confirm::REPLACE_FILES, "{r}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["files"], json!(["/tmp/doc-D.vectorcraft"])); + assert_eq!(written.borrow().len(), 8); + // An artboard added while it asks writes a file the question did not name: OK asks about it. + app.run("artboard.new", json!({"x": 800, "y": 0, "width": 100, "height": 80, "name": "E"})).unwrap(); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["files"], json!(["/tmp/doc-E.vectorcraft"])); + assert_eq!(written.borrow().len(), 8); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(written.borrow().len(), 14); + assert!(!app.session.active().unwrap().is_dirty()); +} + +/// A question asked when a Background Save or Export ends waits for a dialog open then to close. +#[test] +fn the_question_waits_for_an_open_dialog() { + let (mut app, _) = app("/tmp/doc.vectorcraft"); + let uid = app.session.active().unwrap().uid; + dialogs::confirm::tell(&mut app, "Open", ""); + dialogs::confirm::ask_replace_files(&mut app, uid, &["/tmp/doc-B.vectorcraft".into()], &[], "file.save", json!({})); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("message")), Some("Open".to_string())); + dialogs::cancel(&mut app); + frame(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::REPLACE_FILES)); +} + +/// Export with a file per artboard asks the same way, naming every file that is there; OK writes +/// them. +#[test] +fn export_asks_before_replacing_artboard_files_that_are_there() { + let (mut app, written) = app("/tmp/art.png"); + three_boards(&mut app); + let there = ["/tmp/art-B.png", "/tmp/art-C.png"]; + app.services.exists = Some(std::sync::Arc::new(move |p: &str| there.contains(&p))); + let r = crate::io::export(&mut app, Some("png"), Some("/tmp/art.png".into()), &json!({"useArtboards": true})).unwrap(); + assert_eq!(r["pending"], dialogs::confirm::REPLACE_FILES, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!( + (d.str("message").as_str(), d.str("detail").as_str(), d.str("__command").as_str()), + ("“art-B.png” already exists. Replace it?", "art-B.png\nart-C.png", "file.exportAs") + ); + assert!(written.borrow().is_empty()); + // Another document made active meanwhile: OK exports the one that asked. + let uid = app.session.active().unwrap().uid; + let question = app.ui.dialog.take(); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + app.ui.dialog = question; + dialogs::confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/tmp/art-Artboard-1.png", "/tmp/art-B.png", "/tmp/art-C.png"]); + assert_eq!(app.session.active().map(|d| d.uid), Some(uid)); +} + #[test] fn save_a_copy_and_save_dont_ask_and_options_reach_the_file() { let (mut app, written) = app("/tmp/plain.vectorcraft"); diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index c1e3f822cd..90e6fdc78d 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -539,7 +539,7 @@ fn preset_dialogs_export_asks_off_the_ui_thread() { #[test] fn a_sheets_answer_given_its_extension_asks_before_replacing() { let (mut app, shown, written) = app(); - app.services.exists = Some(Box::new(|p: &str| p == "/art/card.vectorcraft")); + app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/art/card.vectorcraft")); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); assert!(app.run("file.save", json!({})).is_err()); shown.answer(&["/art/card"]); @@ -566,7 +566,7 @@ fn a_preset_dialogs_export_asks_before_replacing_over_it() { w.borrow_mut().push(path.to_string()); Ok(()) })), - exists: Some(Box::new(|_: &str| true)), + exists: Some(std::sync::Arc::new(|_: &str| true)), ..Default::default() }; let mut app = VectorcraftApp::new(Session::new(), services); diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 000667dba1..60f80f4fa4 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -606,6 +606,34 @@ fn the_control_bar_and_properties_trace_a_selected_image() { assert!(selected_trace(&app).is_none() && g.children().unwrap().iter().all(|c| !matches!(c.kind, NodeKind::Image(_))), "expanded"); } +/// With the Control bar's Image Options group off, a selected image or Image Trace object shows +/// neither its own controls nor Fill and Stroke in their place; its label and Opacity stay. +#[test] +fn the_image_options_group_holds_the_image_and_trace_controls() { + use crate::tests_removeanchors::{control_frame, has}; + let mut app = app(); + let data = vectorcraft_format::base64_encode(&png(30, 30, 72.0)); + app.run("file.place", json!({"name": "red.png", "dataBase64": data, "link": false})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let set = |app: &mut VectorcraftApp, on: bool| app.run("window.control.options", json!({"group": "imageOptions", "visible": on})).unwrap(); + set(&mut app, false); + let bar = control_frame(&mut app, &ctx, vec![]); + for s in ["Unembed…", "Image Trace", "Crop Image", "Stroke:"] { + assert!(!has(&bar, s), "{s}: {bar:?}"); + } + assert!(has(&bar, "Embedded") && has(&bar, "Opacity:"), "{bar:?}"); + set(&mut app, true); + click_label(&mut app, &ctx, "Image Trace"); + assert!(has(&control_frame(&mut app, &ctx, vec![]), "Expand"), "traced"); + set(&mut app, false); + let bar = control_frame(&mut app, &ctx, vec![]); + for s in ["Preset:", "Expand", "Stroke:"] { + assert!(!has(&bar, s), "{s}: {bar:?}"); + } + assert!(has(&bar, "Image Tracing") && has(&bar, "Opacity:"), "{bar:?}"); +} + #[test] fn the_control_bars_mask_clips_the_image_and_selects_the_clipping_path() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index c3bd9df302..32cc241027 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -1,6 +1,7 @@ //! Heavy plug-in filters in the app ([`crate::plugin_runs`]): installing one asks first, its dialog //! has no Preview, and it runs off the UI thread, its result applied as one undo step once it is -//! done, unless the document changed meanwhile. Cancel stops it; its progress window shows it. +//! done, unless the document changed meanwhile. Cancel stops it; its progress window shows it. A +//! light filter that reports its progress runs there too. use std::time::{Duration, Instant}; @@ -77,6 +78,7 @@ fn installing_a_heavy_filter_asks_first() { assert_eq!(pending.message, format!("Install “Test {id}”, which asks for a heavy budget?")); assert!(pending.detail.contains("up to 5 minutes and do 20 times the work"), "{}", pending.detail); assert!(registry::get(id).is_none(), "not before the user agrees"); + super::plugins::show_approval(&mut app); dialogs::confirm(&mut app).unwrap(); assert_eq!(registry::get(id).map(|p| p.manifest().name.clone()), Some(format!("Test {id}"))); assert_eq!(app.ui.status, format!("Installed plug-in Test {id}")); @@ -214,6 +216,150 @@ fn a_filter_that_reports_progress_shows_a_bar_and_sees_cancel() { assert_eq!(app.ui.status, vectorcraft_engine::EngineError::Cancelled.to_string()); } +/// The triangle the light test filters return. +const TRIANGLE: &str = r#"{"objects":[{"path":{"subpaths":[{"anchors":[{"p":[0,0]},{"p":[30,0]},{"p":[15,20]}]}]}}]}"#; + +/// Installs a light filter `id` of plug-in API level 2 with `params` that returns [`TRIANGLE`], +/// granted as the user would grant it. With `progress` it lists the `progress` permission, and its +/// `vc_run` first runs `first`, which may report its progress. +fn install_light(app: &mut VectorcraftApp, id: &str, progress: bool, params: &str, first: &str) { + let may: &[&str] = if progress { &["doc.read", "doc.write", "progress"] } else { &["doc.read", "doc.write"] }; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{},"params":{params}}}"#, json!(may)); + // Without `progress` the module may not import the host functions. + let src = if progress { tpl::reporting(&manifest, first, TRIANGLE) } else { tpl::returning(&manifest, TRIANGLE) }; + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + app.run("plugin.install", json!({"dataBase64": data, "grant": may})).unwrap(); +} + +/// Applies the runs' results as the frames would, until none is left (each run ends: it returns, +/// or its budget stops it). +fn finish_runs(app: &mut VectorcraftApp) { + while !app.plugin_runs.running.is_empty() { + plugin_runs::poll(app); + std::thread::yield_now(); + } +} + +/// A light filter that may report its progress runs off the UI thread when it runs at once, as a +/// heavy one does: the status bar says so, and its result is one undo step named after it. +#[test] +fn a_light_filter_that_reports_progress_runs_off_the_ui_thread() { + let mut app = app(); + let id = "test.ui.light.progress.run"; + install_light(&mut app, id, true, "{}", "(call $vc_progress (i64.const 1) (i64.const 2))"); + let undo = app.session.doc().unwrap().history.undo.len(); + let r = app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(r["background"], true, "{r}"); + assert_eq!(app.ui.status, format!("Running “Test {id}”…")); + finish_runs(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); + assert_eq!(st.history.undo.last().unwrap().label, format!("Test {id}")); + assert_eq!(st.selection.objects.len(), 1, "the triangle it added, selected"); +} + +/// A light filter that reports its progress shows it in the progress window, and Cancel there +/// makes its `vc_cancelled` return 1: it stops, changing nothing. +#[test] +fn a_light_filter_s_progress_window_shows_its_share_and_cancel_stops_it() { + let mut app = app(); + let id = "test.ui.light.progress.cancel"; + let first = "(call $vc_progress (i64.const 250) (i64.const 1000)) (block $stop (loop $l (br_if $stop (call $vc_cancelled)) (br $l)))"; + install_light(&mut app, id, true, "{}", first); + let doc = app.session.doc().unwrap().doc.clone(); + assert_eq!(app.run("plugin.dialog", json!({"id": id})).unwrap()["background"], true); + // Waits for the run's thread to report the share (a handshake: the thread never stops before + // it is cancelled or its budget runs out, and a run that ended leaves the loop). + loop { + plugin_runs::poll(&mut app); + match app.plugin_runs.running.first() { + Some(r) if r.progress.counts() != (250, 1000) => std::thread::yield_now(), + _ => break, + } + } + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + progress(&mut app, &ctx, 0.0); + progress(&mut app, &ctx, 1.0); + let shown = progress(&mut app, &ctx, 1.1); + assert!(shown.contains(&format!("Running “Test {id}”…")) && shown.contains("25 %") && shown.contains("Cancel"), "{shown}"); + assert_eq!(app.run("plugin.cancelRuns", json!({})).unwrap()["cancelled"], 1); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().doc, doc); + assert_eq!(app.ui.status, vectorcraft_engine::EngineError::Cancelled.to_string()); +} + +/// In the dialog of a light filter that reports its progress, OK with Preview off runs it in the +/// background, also right after Preview was turned off; with Preview on, OK keeps the previewed +/// run, as for any light filter. +#[test] +fn ok_runs_a_light_progress_filter_in_the_background_without_a_preview() { + let mut app = app(); + let id = "test.ui.light.progress.dialog"; + install_light(&mut app, id, true, r#"{"size":{"type":"number","min":1,"max":9,"default":3}}"#, ""); + let undo = app.session.doc().unwrap().history.undo.len(); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + frame(&mut app); + assert!(!app.session.in_interaction(), "nothing previewed"); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.plugin_runs.running.len(), 1, "running in the background"); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + // Preview on: OK keeps the previewed run, and nothing runs in the background. + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("preview"), Some(&json!(true))); + frame(&mut app); + assert!(app.session.in_interaction(), "previewed"); + dialogs::confirm(&mut app).unwrap(); + assert!(app.plugin_runs.running.is_empty()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2); + // Preview turned off after a preview and OK before the next frame: the preview is rolled back + // and the run goes to the background. + app.run("plugin.dialog", json!({"id": id})).unwrap(); + frame(&mut app); + assert!(app.session.in_interaction(), "previewed"); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.session.in_interaction(), "the preview was rolled back"); + assert_eq!(app.plugin_runs.running.len(), 1, "running in the background"); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 3); +} + +/// In the dialog of a light filter that reports its progress, a failed preview is not kept: OK +/// rolls it back and runs the filter in the background instead of again on the UI thread. +#[test] +fn ok_after_a_failed_preview_runs_a_light_progress_filter_in_the_background() { + let mut app = app(); + let id = "test.ui.light.progress.fails"; + install_light(&mut app, id, true, r#"{"size":{"type":"number","min":1,"max":9,"default":3}}"#, "(unreachable)"); + let doc = app.session.doc().unwrap().doc.clone(); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + frame(&mut app); + assert!(app.session.in_interaction(), "the preview's interaction"); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("__refused"), "the preview failed"); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(!app.session.in_interaction(), "the failed preview was rolled back"); + assert_eq!(app.plugin_runs.running.len(), 1, "running in the background"); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().doc, doc); +} + +/// A light filter without the `progress` permission still runs at once, on the UI thread. +#[test] +fn a_light_filter_that_does_not_report_progress_runs_at_once() { + let mut app = app(); + let id = "test.ui.light.plain"; + install_light(&mut app, id, false, "{}", ""); + let r = app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert!(r.get("background").is_none(), "{r}"); + assert!(app.plugin_runs.running.is_empty()); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the triangle, added at once"); +} + /// `CRAFT_UI_HEAVY_FILTER_WASM=` writes a heavy test filter to install in the app /// (`order-paths-test-filter.wasm`): it computes until it is cancelled or its budget runs out, so /// its progress window stays up for a picture. diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 22cd5caffb..0a80254db0 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -27,6 +27,68 @@ fn frame(app: &mut VectorcraftApp) { out.textures_delta.clear(); } +/// Shows the open install approval in one window, frame after frame a quarter of a second apart, +/// until its OK takes input ([`dialogs::plugin::APPROVAL_DELAY`]), as a person sees it before +/// pressing OK. +pub(super) fn show_approval(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + for k in 0..12 { + let input = egui::RawInput { time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + if app.pending_plugin_install.as_ref().is_some_and(|p| p.shown.ready()) { + return; + } + } + panic!("the approval's OK never took input"); +} + +pub(super) type Window = egui_kittest::Harness<'static, VectorcraftApp>; + +/// The dialog layer of `app` in a window, each frame drawn at the time [`at`] gives it. Building it +/// draws frames at times of its own, so a test opens the dialog after. +pub(super) fn window(app: VectorcraftApp) -> Window { + let mut fonts = false; + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + theme::install_fonts(ui.ctx()); + return; + } + dialogs::show(app, ui.ctx()); + }, + app, + ) +} + +/// Draws a frame of `h` at `time` seconds. +pub(super) fn at(h: &mut Window, time: f64) { + h.input_mut().time = Some(time); + h.step(); +} + +/// Whether the approval's OK is enabled, as a screen reader reads it. +pub(super) fn ok_enabled(h: &Window) -> bool { + use egui_kittest::kittest::{NodeT, Queryable}; + !h.get_by_label("OK").accesskit_node().is_disabled() +} + +/// Clicks the approval's OK as a person does, on a frame at `time` seconds. +pub(super) fn click_ok(h: &mut Window, time: f64) { + use egui_kittest::kittest::Queryable; + h.get_by_label("OK").click(); + at(h, time); +} + +/// The approval is open and plug-in `id` neither installed nor granted. +pub(super) fn waiting(app: &VectorcraftApp, id: &str) -> bool { + app.ui.dialog.as_ref().is_some_and(|d| d.kind == dialogs::plugin::INSTALL_KIND) + && vectorcraft_plugins::registry::get(id).is_none() + && vectorcraft_plugins::registry::granted(id).is_none() +} + fn red_rect(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId { let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); @@ -122,7 +184,7 @@ fn plugin_effects_open_the_effect_dialog_with_their_schema() { /// A filter `id` named `name` whose manifest lists `permissions` (a JSON list), at a version with /// a bidirectional override, a tab and a bell in it. -fn asking(id: &str, name: &str, permissions: &str) -> Vec { +pub(super) fn asking(id: &str, name: &str, permissions: &str) -> Vec { let manifest = json!({"id": id, "name": name, "version": "3.0\u{202E}\t\u{0007}", "kind": "filter"}).to_string(); let manifest = format!(r#"{},"permissions":{permissions}}}"#, manifest.trim_end_matches('}')); wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap() @@ -163,6 +225,7 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { // File › Open asks too, and OK installs it with what it lists granted. io::open_bytes(&mut app, "tidy.wasm", &bytes, None).unwrap(); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::plugin::INSTALL_KIND)); + show_approval(&mut app); dialogs::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); assert!(vectorcraft_plugins::registry::get(id).is_some()); @@ -195,6 +258,7 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some(name.into()), "Cancel keeps the one installed"); assert_ne!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(again_hash), "Cancel records no grant"); app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&again)})).unwrap(); + show_approval(&mut app); dialogs::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none(), "one question"); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some("Tidy 2".into())); @@ -209,14 +273,257 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some("Tidy 2".into()), "Cancel keeps the one installed"); // OK keeps the `replace` it was asked with: `false` leaves the installed one in place. app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&more), "replace": false})).unwrap(); + show_approval(&mut app); let _ = dialogs::confirm(&mut app); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some("Tidy 2".into()), "replace: false is kept"); app.run("plugin.remove", json!({"id": id})).unwrap(); } -/// A module with other bytes than the one installed with its id asks before taking its place: in -/// the ordinary confirm when it needs nothing that only a person can approve, and in the approval -/// dialog, with its id and file hash, when it also asks for a heavy budget. +/// The approval's OK takes no click, Enter or Space, and a confirm installs nothing, until its +/// question has been on screen for [`dialogs::plugin::APPROVAL_DELAY`]; then a click installs it. +/// Cancel works on the first frame. +#[test] +fn the_install_approval_takes_ok_only_once_its_question_was_shown_for_a_moment() { + use egui_kittest::kittest::Queryable; + let id = "test.ui.approval.delay"; + let module = json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "Delay", r#"["doc.read"]"#))}); + let mut h = window(app()); + h.state_mut().run("ui.installPlugin", module.clone()).unwrap(); + assert_eq!(dialogs::confirm(h.state_mut()).unwrap(), json!({"pending": dialogs::plugin::INSTALL_KIND}), "not drawn yet"); + assert!(waiting(h.state(), id)); + at(&mut h, 10.0); + at(&mut h, 10.0); + assert!(!ok_enabled(&h), "disabled when it first shows"); + click_ok(&mut h, 10.1); + assert!(waiting(h.state(), id), "a click"); + for (key, time) in [(egui::Key::Enter, 10.2), (egui::Key::Space, 10.3)] { + h.get_by_label("OK").focus(); + at(&mut h, time); + h.key_press(key); + at(&mut h, time + 0.05); + assert!(waiting(h.state(), id), "{key:?}"); + } + at(&mut h, 10.49); + assert!(!ok_enabled(&h), "still disabled just before the delay"); + assert_eq!(dialogs::confirm(h.state_mut()).unwrap()["pending"], dialogs::plugin::INSTALL_KIND, "a confirm"); + assert!(waiting(h.state(), id)); + at(&mut h, 10.5); + assert!(ok_enabled(&h), "enabled once shown for the delay"); + click_ok(&mut h, 10.6); + assert!(h.state().ui.dialog.is_none(), "{}", h.state().ui.status); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); + + h.state_mut().run("ui.installPlugin", module).unwrap(); + at(&mut h, 20.0); + at(&mut h, 20.0); + h.get_by_label("Cancel").click(); + at(&mut h, 20.0); + assert!(h.state().ui.dialog.is_none() && h.state().pending_plugin_install.is_none(), "Cancel doesn't wait"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); +} + +/// The wait starts over for each question: one that takes the place of the question shown just +/// before a click lands, which the click doesn't approve; the same question asked again; and the +/// question shown when the window gets the focus back. +#[test] +fn the_install_approval_waits_again_for_a_new_question_and_after_the_focus_comes_back() { + let (a, b) = ("test.ui.approval.swap.a", "test.ui.approval.swap.b"); + let module = |id: &str| json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "Same", r#"["doc.read"]"#))}); + let mut h = window(app()); + h.state_mut().run("ui.installPlugin", module(a)).unwrap(); + at(&mut h, 10.0); + at(&mut h, 10.0); + at(&mut h, 10.6); + assert!(ok_enabled(&h)); + // Between two frames, a request closes the question and asks about another module. + dialogs::cancel(h.state_mut()); + h.state_mut().run("ui.installPlugin", module(b)).unwrap(); + click_ok(&mut h, 10.7); + assert!(waiting(h.state(), b) && vectorcraft_plugins::registry::get(a).is_none(), "the click approves neither"); + assert!(!ok_enabled(&h)); + at(&mut h, 11.19); + assert!(!ok_enabled(&h)); + at(&mut h, 11.2); + assert!(ok_enabled(&h), "the new question waits its own delay"); + // The same question again, from the same bytes. + dialogs::cancel(h.state_mut()); + h.state_mut().run("ui.installPlugin", module(b)).unwrap(); + at(&mut h, 11.3); + assert!(!ok_enabled(&h), "asked again, it waits again"); + at(&mut h, 11.8); + assert!(ok_enabled(&h)); + // The window loses the focus and gets it back. + h.input_mut().focused = false; + at(&mut h, 11.9); + assert!(!ok_enabled(&h), "not while the window doesn't have the focus"); + assert_eq!(dialogs::confirm(h.state_mut()).unwrap()["pending"], dialogs::plugin::INSTALL_KIND); + h.input_mut().focused = true; + at(&mut h, 12.0); + at(&mut h, 12.49); + assert!(!ok_enabled(&h), "back in front, it waits again"); + at(&mut h, 12.5); + click_ok(&mut h, 12.6); + assert!(h.state().ui.dialog.is_none(), "{}", h.state().ui.status); + assert!(vectorcraft_plugins::registry::get(b).is_some() && vectorcraft_plugins::registry::get(a).is_none()); + h.state_mut().run("plugin.remove", json!({"id": b})).unwrap(); +} + +/// A press on OK that began before OK took input approves nothing when it is let go after; a new +/// click does. +#[test] +fn a_press_on_the_install_approval_from_before_ok_took_input_approves_nothing() { + use egui_kittest::kittest::Queryable; + let id = "test.ui.approval.held"; + let mut h = window(app()); + let module = json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "Held", r#"["doc.read"]"#))}); + h.state_mut().run("ui.installPlugin", module).unwrap(); + at(&mut h, 10.0); + at(&mut h, 10.0); + let pos = h.get_by_label("OK").rect().center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.input_mut().events.extend([egui::Event::PointerMoved(pos), button(true)]); + at(&mut h, 10.1); + at(&mut h, 10.6); + assert!(ok_enabled(&h)); + h.input_mut().events.push(button(false)); + at(&mut h, 10.7); + assert!(waiting(h.state(), id), "the press began before OK took input"); + click_ok(&mut h, 10.8); + assert!(h.state().ui.dialog.is_none(), "{}", h.state().ui.status); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); +} + +/// A press of another button after OK took input doesn't let a primary press from before it +/// approve when that press is let go of. +#[test] +fn a_later_press_on_the_install_approval_keeps_an_early_press_from_approving() { + use egui_kittest::kittest::Queryable; + let id = "test.ui.approval.held.two"; + let mut h = window(app()); + let module = json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "Two", r#"["doc.read"]"#))}); + h.state_mut().run("ui.installPlugin", module).unwrap(); + at(&mut h, 10.0); + at(&mut h, 10.0); + let pos = h.get_by_label("OK").rect().center(); + let button = |button, pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() }; + // The primary button goes down away from any widget and moves over OK. + let away = egui::pos2(2.0, 2.0); + h.input_mut().events.extend([ + egui::Event::PointerMoved(away), + egui::Event::PointerButton { pos: away, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + ]); + at(&mut h, 10.1); + h.input_mut().events.push(egui::Event::PointerMoved(pos)); + at(&mut h, 10.2); + at(&mut h, 10.5); + assert!(ok_enabled(&h)); + h.input_mut().events.push(button(egui::PointerButton::Secondary, true)); + at(&mut h, 10.55); + h.input_mut().events.push(button(egui::PointerButton::Primary, false)); + at(&mut h, 10.6); + assert!(waiting(h.state(), id), "the primary press began before OK took input"); + h.input_mut().events.push(button(egui::PointerButton::Secondary, false)); + at(&mut h, 10.65); + click_ok(&mut h, 10.8); + assert!(h.state().ui.dialog.is_none(), "{}", h.state().ui.status); + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); +} + +/// A press on the OK of one question that is still held when another question takes its place +/// doesn't approve the new one when it is let go of. +#[test] +fn a_press_held_from_the_question_before_approves_nothing() { + use egui_kittest::kittest::Queryable; + let (a, b) = ("test.ui.approval.carried.a", "test.ui.approval.carried.b"); + let module = |id: &str| json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "Carried", r#"["doc.read"]"#))}); + let mut h = window(app()); + h.state_mut().run("ui.installPlugin", module(a)).unwrap(); + at(&mut h, 10.0); + at(&mut h, 10.0); + at(&mut h, 10.6); + assert!(ok_enabled(&h)); + let pos = h.get_by_label("OK").rect().center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.input_mut().events.extend([egui::Event::PointerMoved(pos), button(true)]); + at(&mut h, 10.65); + // While the button is down, a request closes the question and asks about another module. + dialogs::cancel(h.state_mut()); + h.state_mut().run("ui.installPlugin", module(b)).unwrap(); + at(&mut h, 10.7); + at(&mut h, 11.0); + at(&mut h, 11.2); + assert!(ok_enabled(&h)); + h.input_mut().events.push(button(false)); + at(&mut h, 11.25); + assert!(waiting(h.state(), b) && vectorcraft_plugins::registry::get(a).is_none(), "the press began on the question before"); + click_ok(&mut h, 11.4); + assert!(h.state().ui.dialog.is_none(), "{}", h.state().ui.status); + assert!(vectorcraft_plugins::registry::get(b).is_some()); + h.state_mut().run("plugin.remove", json!({"id": b})).unwrap(); +} + +/// Enter or Space held down while OK is disabled doesn't approve through its key repeat once OK +/// has the keyboard focus; a new press after it is let go of does. +#[test] +fn a_key_held_on_the_install_approval_from_before_ok_took_input_approves_nothing() { + use egui_kittest::kittest::Queryable; + for (n, key) in [egui::Key::Enter, egui::Key::Space].into_iter().enumerate() { + let id = format!("test.ui.approval.key.{n}"); + let mut h = window(app()); + let module = json!({"dataBase64": vectorcraft_format::base64_encode(&asking(&id, "Key", r#"["doc.read"]"#))}); + h.state_mut().run("ui.installPlugin", module).unwrap(); + at(&mut h, 10.0); + at(&mut h, 10.0); + let event = |pressed, repeat| egui::Event::Key { key, physical_key: Some(key), pressed, repeat, modifiers: Default::default() }; + h.input_mut().events.push(event(true, false)); + at(&mut h, 10.1); + at(&mut h, 10.6); + assert!(ok_enabled(&h)); + h.get_by_label("OK").focus(); + at(&mut h, 10.65); + h.input_mut().events.push(event(true, true)); + at(&mut h, 10.7); + assert!(waiting(h.state(), &id), "{key:?}: the key went down before OK took input"); + h.input_mut().events.push(event(false, false)); + at(&mut h, 10.75); + h.get_by_label("OK").focus(); + at(&mut h, 10.8); + h.key_press(key); + at(&mut h, 10.85); + assert!(h.state().ui.dialog.is_none(), "{key:?}: {}", h.state().ui.status); + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// The wait starts over when the window loses the focus and gets it back between two frames. +#[test] +fn the_install_approval_waits_again_when_the_focus_leaves_and_comes_back_between_frames() { + let id = "test.ui.approval.blink"; + let mut h = window(app()); + let module = json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "Blink", r#"["doc.read"]"#))}); + h.state_mut().run("ui.installPlugin", module).unwrap(); + at(&mut h, 10.0); + at(&mut h, 10.0); + at(&mut h, 10.6); + assert!(ok_enabled(&h)); + h.input_mut().events.extend([egui::Event::WindowFocused(false), egui::Event::WindowFocused(true)]); + at(&mut h, 10.7); + assert!(!ok_enabled(&h), "the focus left since the frame before"); + click_ok(&mut h, 10.8); + assert!(waiting(h.state(), id)); + at(&mut h, 11.19); + assert!(!ok_enabled(&h)); + at(&mut h, 11.2); + assert!(ok_enabled(&h), "back in front, it waits again"); + click_ok(&mut h, 11.3); + assert!(h.state().ui.dialog.is_none(), "{}", h.state().ui.status); + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); +} + +/// A module with other bytes than the one installed with its id asks before taking its place, in +/// the approval dialog, with its id and file hash, also when it asks for a heavy budget. #[test] fn installing_a_plugin_over_another_module_asks_first() { let mut app = app(); @@ -230,10 +537,13 @@ fn installing_a_plugin_over_another_module_asks_first() { let other = plain(r#"{"objects":[],"error":null}"#); let other_hash = vectorcraft_plugins::permissions::sha256_hex(&other); let r = app.run("ui.installPlugin", module(&other)).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::KIND); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("message"), "Install “Plain” in place of the plug-in with the same ID?"); - assert_eq!(d.str("detail"), format!("ID: {id}\nFile SHA-256: {other_hash}\n\n{takes_place}")); + assert_eq!(r, json!({"pending": dialogs::plugin::INSTALL_KIND})); + let pending = app.pending_plugin_install.as_ref().unwrap(); + assert_eq!(pending.message, "Install “Plain” in place of the plug-in with the same ID?"); + assert_eq!(pending.detail, format!("ID: {id}\nFile SHA-256: {other_hash}\n\n{takes_place}")); + assert_eq!(pending.params["replace"], json!(true), "OK replaces the one installed"); + assert_eq!(dialogs::confirm(&mut app).unwrap()["pending"], dialogs::plugin::INSTALL_KIND, "it waits like any other question"); + show_approval(&mut app); dialogs::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(other_hash)); @@ -246,6 +556,7 @@ fn installing_a_plugin_over_another_module_asks_first() { let pending = app.pending_plugin_install.as_ref().unwrap(); assert!(pending.detail.ends_with(&format!("\n\nID: {id}\nFile SHA-256: {heavy_hash}\n\n{takes_place}")), "{}", pending.detail); assert_eq!(pending.params["replace"], json!(true), "OK replaces the one installed"); + show_approval(&mut app); dialogs::confirm(&mut app).unwrap(); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(heavy_hash)); app.run("plugin.remove", json!({"id": id})).unwrap(); @@ -404,6 +715,7 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); let detail = app.pending_plugin_install.as_ref().unwrap().detail.clone(); assert!(detail.ends_with("• Read the objects it is given\n• Show its progress, see Cancel and write log lines"), "{detail}"); + show_approval(&mut app); dialogs::confirm(&mut app).unwrap(); assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); diff --git a/crates/ui-egui/src/tests/rotateview.rs b/crates/ui-egui/src/tests/rotateview.rs index dbdb0283fd..715610f08e 100644 --- a/crates/ui-egui/src/tests/rotateview.rs +++ b/crates/ui-egui/src/tests/rotateview.rs @@ -117,7 +117,8 @@ fn control_rotate_view_keeps_press_coordinates_and_shift_snapping_across_request send(&mut app, &ctx, "ui.pointer", json!({"mods": {"shift": true}, "events": [{"kind": "drag", "x": x, "y": y}]})); assert_eq!(app.view().unwrap().rotation, 45.0, "the same document point does not turn again as the view changes"); } - send(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "up", "x": x, "y": y}]})); + // Null `mods` keep the default, as an omitted value does. + send(&mut app, &ctx, "ui.pointer", json!({"mods": null, "events": [{"kind": "up", "x": x, "y": y, "mods": null}]})); assert_eq!(app.view().unwrap().rotation, 45.0); } diff --git a/crates/ui-egui/src/tests/ruler_origin.rs b/crates/ui-egui/src/tests/ruler_origin.rs index de4a0501e6..5e93993fe3 100644 --- a/crates/ui-egui/src/tests/ruler_origin.rs +++ b/crates/ui-egui/src/tests/ruler_origin.rs @@ -80,7 +80,7 @@ fn ruler_origin_drag_uses_the_rotated_zoomed_view_and_commits_only_on_release() assert!(st.doc.ruler_origin_for(0).distance(goal) < 1e-4, "{:?}", st.doc.ruler_origin_for(0)); assert_eq!(st.history.undo.len(), undo + 1); assert_eq!(st.doc.art_bounds(), None, "the drawing tool never receives the corner drag"); - assert!(st.doc.guides.is_empty()); + assert!(st.doc.ruler_guides().is_empty()); let origin = st.doc.ruler_origin_for(0); app.run("edit.undo", json!({})).unwrap(); assert_eq!(&*app.session.doc().unwrap().doc, &*before); @@ -88,6 +88,27 @@ fn ruler_origin_drag_uses_the_rotated_zoomed_view_and_commits_only_on_release() assert_eq!(app.ruler_origin(), origin); } +/// The origin snaps as a drawn point does: dragged next to a rectangle's corner, it is set on it. +#[test] +fn ruler_origin_drag_snaps_onto_the_art() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("select.none", json!({})).unwrap(); + // The Hand tool shows no smart guides of its own as the pointer passes over the corner. + app.select_tool("hand"); + let ctx = context(); + frame(&mut app, &ctx, vec![], canvas::show); + let to = canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(Point::new(100.4, 99.6)); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)], canvas::show); + assert!(app.session.overlays(app.view_info()).is_empty()); + start_drag(&mut app, &ctx, to); + frame(&mut app, &ctx, vec![], canvas::show); + assert!(!app.session.overlays(app.view_info()).is_empty(), "the guide showing what it snapped to"); + frame(&mut app, &ctx, vec![press(to, false)], canvas::show); + assert_eq!(app.ruler_origin(), Point::new(100.0, 100.0)); + assert!(app.session.overlays(app.view_info()).is_empty()); +} + #[test] fn ruler_origin_double_click_resets_to_the_active_artboard() { let mut app = app(); @@ -132,8 +153,9 @@ fn ruler_origin_cancelled_drags_do_not_modify_either_document() { Escape, Focus, Document, + HideRulers, } - for cancel in [Cancel::Outside, Cancel::Escape, Cancel::Focus, Cancel::Document] { + for cancel in [Cancel::Outside, Cancel::Escape, Cancel::Focus, Cancel::Document, Cancel::HideRulers] { let mut app = app(); app.run("document.setRulerOrigin", json!({"x": 25, "y": 30})).unwrap(); let ctx = context(); @@ -146,6 +168,7 @@ fn ruler_origin_cancelled_drags_do_not_modify_either_document() { Cancel::Outside => pos2(4.0, 4.0), Cancel::Escape => { frame(&mut app, &ctx, vec![key(Key::Escape)], canvas::show); + assert!(app.session.overlays(app.view_info()).is_empty(), "the snapping guides go too"); to } Cancel::Focus => { @@ -157,6 +180,14 @@ fn ruler_origin_cancelled_drags_do_not_modify_either_document() { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); to } + Cancel::HideRulers => { + assert!(!app.session.overlays(app.view_info()).is_empty(), "the snapping guides show"); + app.ui.view.rulers = false; + frame(&mut app, &ctx, vec![], canvas::show); + assert!(app.session.overlays(app.view_info()).is_empty(), "the snapping guides go with the rulers"); + assert!(!canvas::ruler_origin_dragging(&ctx)); + to + } }; frame(&mut app, &ctx, vec![Event::PointerMoved(release), press(release, false)], canvas::show); if cancel == Cancel::Document { diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index 497ac0c749..b8bb2ee6e4 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -215,7 +215,7 @@ fn a_typed_extension_of_a_format_the_save_does_not_write_is_replaced() { #[test] fn a_replaced_extension_asks_before_replacing_a_file_there() { let (mut app, shown, written) = portal_app(); - app.services.exists = Some(Box::new(|p: &str| p == "/art/card.vectorcraft")); + app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/art/card.vectorcraft")); assert_eq!(saved_from(&mut app, &shown, &written, "file.save", &["/art/card.png"]), "/art/card.vectorcraft"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::REPLACE)); assert!(written.borrow().is_empty()); @@ -254,7 +254,7 @@ fn a_document_in_another_format_saves_as_the_type_picked() { #[test] fn a_name_given_the_picked_types_extension_asks_before_replacing() { let (mut app, shown, written) = portal_app(); - app.services.exists = Some(Box::new(|p: &str| p == "/art/poster.ai")); + app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/art/poster.ai")); assert_eq!(saved_from(&mut app, &shown, &written, "file.save", &["/art/poster", "ai"]), "/art/poster.ai"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::REPLACE)); assert!(written.borrow().is_empty()); @@ -284,7 +284,7 @@ fn on_disk(tag: &str, typed: &str) -> (VectorcraftApp, std::path::PathBuf) { let picked = dir.join(typed).to_string_lossy().into_owned(); let services = Services { write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), - exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())), + exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())), pick_save: Some(Box::new(move |_: &FilePick| Some(picked.clone()))), ..Default::default() }; @@ -371,7 +371,7 @@ fn every_write_through_a_save_panel_asks_before_replacing() { ]; for (cmd, params, path) in cases { let (mut app, w) = saving_app("/tmp/out"); - app.services.exists = Some(Box::new(|_: &str| true)); + app.services.exists = Some(std::sync::Arc::new(|_: &str| true)); app.run("select.all", json!({})).unwrap(); assert!(app.run(cmd, params).is_err(), "{cmd}"); assert!(w.borrow().is_empty(), "{cmd}: nothing is written while it asks"); @@ -382,7 +382,7 @@ fn every_write_through_a_save_panel_asks_before_replacing() { } // Export As: the question's OK picks the file again, and PNG Options follows. let (mut app, w) = saving_app("/tmp/out"); - app.services.exists = Some(Box::new(|_: &str| true)); + app.services.exists = Some(std::sync::Arc::new(|_: &str| true)); app.run("file.exportAs", json!({"format": "png"})).unwrap(); assert!(dialogs::confirm(&mut app).is_err()); let open = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| (d.kind.clone(), d.str("path"))); diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 751bd528a6..7cfa5fe2b5 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -353,6 +353,50 @@ fn the_folder_is_read_at_the_first_frame_and_when_the_window_becomes_active() { let _ = std::fs::remove_dir_all(dir); } +/// A macOS menu bar that reports a menu opening at its next drain when `0` is set. +struct Opens(std::rc::Rc>); + +impl native_menu::Backend for Opens { + fn sync(&mut self, _: &native_menu::MenuBar) {} + fn drain(&mut self) -> Vec { + if self.0.replace(false) { vec![native_menu::Event::Opened] } else { Vec::new() } + } +} + +#[test] +fn a_menu_of_the_macos_menu_bar_opening_reads_the_folder_again() { + let dir = folder("native-open"); + let mut app = app(&dir); + write(&dir, "first.js", ""); + read(&app); + let opens = std::rc::Rc::new(std::cell::Cell::new(false)); + app.services.native_menu = Some(native_menu::NativeMenu::new(Box::new(Opens(opens.clone())))); + let ctx = egui::Context::default(); + let mut frame = |opened: bool| { + opens.set(opened); + assert_eq!(app.services.native_menu.as_mut().map(native_menu::NativeMenu::take_keys), Some(Vec::new())); + native_menu::run(&mut app, &ctx); + scripts_menu::wait(); + native_menu::layout(&app).bar + }; + let listed = |bar: &native_menu::MenuBar| { + let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); + let scripts = file.children.iter().find_map(|n| match n { + Node::Submenu { label, children } if label == "Scripts" => Some(children.as_slice()), + _ => None, + }); + scripts.unwrap_or_default().iter().filter_map(|n| if let Node::Item(it) = n { Some(it.label.clone()) } else { None }).collect::>() + }; + // While the window stays active and no menu opens, the folder is left alone. + write(&dir, "second.js", ""); + let bar = frame(false); + assert_eq!(listed(&bar)[..1], ["first"], "{:?}", listed(&bar)); + assert!(!listed(&bar).iter().any(|l| l == "second"), "{:?}", listed(&bar)); + let bar = frame(true); + assert_eq!(listed(&bar)[..2], ["first", "second"], "{:?}", listed(&bar)); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_read_asked_for_during_another_runs_when_that_one_ends() { let dir = folder("pending"); diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 595d12b51f..1da5b93322 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -174,8 +174,9 @@ pub(super) fn pasted(app: &VectorcraftApp) -> Vec { st.selection.objects.iter().map(|id| st.doc.node(*id).unwrap().clone()).collect() } +/// The objects on the first layer (its ruler guides left out). pub(super) fn count(app: &VectorcraftApp) -> usize { - app.session.active().unwrap().doc.layers[0].children().unwrap().len() + app.session.active().unwrap().doc.layers[0].children().unwrap().iter().filter(|c| !c.is_ruler_guide()).count() } /// An egui `PasteImage` from the host is the signal to read the rich system clipboard: it must diff --git a/crates/ui-egui/src/tests/sysclip_guides.rs b/crates/ui-egui/src/tests/sysclip_guides.rs index a54bd57eb6..50c4535c37 100644 --- a/crates/ui-egui/src/tests/sysclip_guides.rs +++ b/crates/ui-egui/src/tests/sysclip_guides.rs @@ -14,7 +14,7 @@ use crate::tests_sysclip::{app, app_with_busy_worker, copy_elsewhere, copy_rect, use crate::{Services, VectorcraftApp, background}; fn guides(app: &VectorcraftApp) -> usize { - app.session.active().unwrap().doc.guides.len() + app.session.active().unwrap().doc.ruler_guides().len() } /// Add a vertical guide at `pos`, select only it and copy it. @@ -35,7 +35,8 @@ fn a_guides_only_copy_pastes_the_guides_not_what_another_app_copied_before() { run(&mut app, "edit.paste", json!({})); assert_eq!(guides(&app), 2, "the copied guide was pasted"); assert_eq!(count(&app), 0, "and not the other app's text"); - assert_eq!(app.session.active().unwrap().selection.guides, [1]); + let st = app.session.active().unwrap(); + assert_eq!(vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides), [1]); // A second Paste takes the guides again. run(&mut app, "edit.paste", json!({})); assert_eq!((guides(&app), count(&app)), (3, 0)); diff --git a/crates/ui-egui/src/tests/sysclip_probe.rs b/crates/ui-egui/src/tests/sysclip_probe.rs index 48e4f2e348..05cab31bf7 100644 --- a/crates/ui-egui/src/tests/sysclip_probe.rs +++ b/crates/ui-egui/src/tests/sysclip_probe.rs @@ -14,11 +14,13 @@ use vectorcraft_engine::cmd::clipboard::Flavour; use crate::tests_sysclip::{copy_rect, run}; use crate::{Services, SystemClipboard, VectorcraftApp, menus}; -/// What the clipboard handles saw: the thread each `has()` ran on, and how many handles are alive. +/// What the clipboard handles saw: the thread each `has()` ran on, how many handles are alive, and +/// the thread each handle was dropped on, in order. #[derive(Default)] struct Recorder { threads: Mutex>>, alive: AtomicUsize, + drops: Mutex>>, } impl Recorder { @@ -44,10 +46,42 @@ impl Slow { impl Drop for Slow { fn drop(&mut self) { + self.rec.drops.lock().unwrap().push(std::thread::current().name().map(str::to_owned)); self.rec.alive.fetch_sub(1, Ordering::SeqCst); } } +/// The probe's clipboard: its `has()` tells `looking` it started, then waits until `answer` sends +/// (an owner that answers only once the app is quitting). +struct Held { + rec: Arc, + looking: std::sync::mpsc::Sender<()>, + answer: std::sync::mpsc::Receiver<()>, +} + +impl Drop for Held { + fn drop(&mut self) { + self.rec.drops.lock().unwrap().push(std::thread::current().name().map(str::to_owned)); + } +} + +impl SystemClipboard for Held { + fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> { + Ok(()) + } + fn holds_ours(&mut self) -> bool { + false + } + fn read(&mut self, _mimes: &[&'static str]) -> Option { + None + } + fn has(&mut self, _mimes: &[&'static str]) -> bool { + let _ = self.looking.send(()); + let _ = self.answer.recv(); + false + } +} + impl SystemClipboard for Slow { fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> { Ok(()) @@ -143,6 +177,35 @@ fn the_probe_rests_after_a_copy_and_stops_with_the_app() { assert_eq!(rec.alive.load(Ordering::SeqCst), 0, "the probe's thread kept its clipboard"); } +#[test] +fn quitting_drops_the_probes_clipboard_before_the_apps() { + let rec = Arc::new(Recorder::default()); + let (looking, looked) = std::sync::mpsc::channel(); + let (answer, answered) = std::sync::mpsc::channel::<()>(); + let make = { + let rec = Arc::clone(&rec); + move || -> Box { Box::new(Held { rec, looking, answer: answered }) } + }; + let services = Services { + system_clipboard: Some(Slow::boxed(&rec, Duration::ZERO, Some(false))), + clipboard_probe: Some(Box::new(make)), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + frame(&mut app); + frame(&mut app); + // The probe's thread is waiting on the clipboard's owner when the user quits. + looked.recv_timeout(Duration::from_secs(60)).expect("the probe never looked"); + drop(answer); + drop(app); + // On X11 the last handle dropped hands what the app copied to the clipboard manager: it must be + // the app's own, dropped on the UI thread before the process exits. + let drops = rec.drops.lock().unwrap().clone(); + let ui = std::thread::current().name().map(str::to_owned); + assert_eq!(drops, vec![Some("vectorcraft-clip".to_owned()), ui], "handles dropped on: {drops:?}"); +} + #[test] fn without_its_thread_the_check_runs_in_line_again() { let rec = Arc::new(Recorder::default()); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 96e4533449..7c93308ec5 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -184,6 +184,82 @@ fn type_on_a_path_offers_its_options() { assert_eq!(d.fields.get("effect"), Some(&json!("skew"))); } +/// Type on a path offers Dynamic Text, which turns it on and off; type in a thread does not. +#[test] +fn type_on_a_path_offers_dynamic_text() { + let mut app = app(); + let path = id(app.run("path.create", json!({"d": "M60 150 L340 150"})).unwrap()); + let t = id(app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Along", "at": [60, 150]})).unwrap()); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + select(&mut app, &[t]); + let dynamic = |app: &VectorcraftApp| matches!(kind(app, t), NodeKind::Text(ref t) if t.dynamic_text); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Dynamic Text"), "{texts:?}"); + click(&mut app, "Dynamic Text"); + assert!(dynamic(&app)); + click(&mut app, "Dynamic Text"); + assert!(!dynamic(&app)); + // Threaded, it is not offered. + let frame = id(app.run("shape.rectangle", json!({"x": 60, "y": 200, "width": 200, "height": 100})).unwrap()); + select(&mut app, &[t, frame]); + app.run("text.thread.create", json!({})).unwrap(); + select(&mut app, &[t]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Dynamic Text"), "{texts:?}"); +} + +/// Type on a closed path offers Center on Top and Center on Bottom; type on an open path does not. +#[test] +fn type_on_a_closed_path_offers_center_on_top_and_bottom() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("path.create", json!({"d": "M60 150 L340 150"})).unwrap()); + let open = id(app.run("text.createInPath", json!({"path": line, "mode": "onPath", "text": "Along", "at": [60, 150]})).unwrap()); + select(&mut app, &[open]); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Type on a Path Options") && !has(&texts, "Center on Top") && !has(&texts, "Center on Bottom"), "{texts:?}"); + let circle = id(app.run("path.create", json!({"d": "M100 300 A100 100 0 1 1 300 300 A100 100 0 1 1 100 300 Z"})).unwrap()); + let t = id(app.run("text.createInPath", json!({"path": circle, "mode": "onPath", "text": "Round", "at": [90, 300]})).unwrap()); + select(&mut app, &[t]); + let start = |app: &VectorcraftApp| match kind(app, t) { + NodeKind::Text(t) => match t.kind { + TextKind::OnPath { start, .. } => start, + k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Center on Top") && has(&texts, "Center on Bottom"), "{texts:?}"); + click(&mut app, "Center on Top"); + assert!((start(&app) - 0.75).abs() < 1e-3, "{}", start(&app)); + click(&mut app, "Center on Bottom"); + assert!((start(&app) - 0.25).abs() < 1e-3, "{}", start(&app)); +} + +/// Area type offers Dynamic Text beside Convert To Point Type, which turns Block on and off; area +/// type in a thread does not. +#[test] +fn area_type_offers_dynamic_text() { + let mut app = app(); + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "area": {"width": 200, "height": 100}, "text": "Fit me"})).unwrap()); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + select(&mut app, &[t]); + let dynamic = |app: &VectorcraftApp| matches!(kind(app, t), NodeKind::Text(ref t) if t.dynamic_text); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Convert To Point Type") && has(&texts, "Dynamic Text"), "{texts:?}"); + click(&mut app, "Dynamic Text"); + assert!(dynamic(&app)); + click(&mut app, "Dynamic Text"); + assert!(!dynamic(&app)); + // Threaded, it is not offered. + let frame = id(app.run("shape.rectangle", json!({"x": 60, "y": 300, "width": 200, "height": 100})).unwrap()); + select(&mut app, &[t, frame]); + app.run("text.thread.create", json!({})).unwrap(); + select(&mut app, &[t]); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Convert To Point Type") && !has(&texts, "Dynamic Text"), "{texts:?}"); +} + /// The path's anchors (its first subpath). fn anchors(app: &VectorcraftApp, id: u64) -> Vec { match kind(app, id) { diff --git a/crates/ui-egui/src/troubleshooting.rs b/crates/ui-egui/src/troubleshooting.rs new file mode 100644 index 0000000000..5624a7996d --- /dev/null +++ b/crates/ui-egui/src/troubleshooting.rs @@ -0,0 +1,72 @@ +//! Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`): puts the text the host +//! gives ([`crate::Services::troubleshooting`]) on the clipboard for a bug report. The desktop app +//! gives the platform, the graphics processor, recent commands and frame times, and the hang reports +//! of this session and the one before (its `hang_watch` module); without the service the text is +//! the version only. + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; + +/// The status message after the text was put on the clipboard. +pub const COPIED: &str = "Copied the troubleshooting info"; + +/// The status message at launch when the last session stopped responding and was closed before it +/// answered again. +pub const LAST_SESSION_STOPPED: &str = + "The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report"; + +/// The text the command copies. +pub fn text(app: &VectorcraftApp) -> String { + match &app.services.troubleshooting { + Some(text) => text(), + None => format!("VectorCraft {}\n", env!("CARGO_PKG_VERSION")), + } +} + +/// `help.copyTroubleshootingInfo`: put [`text`] on the clipboard. → `{chars}`, the text's length in +/// characters. +pub fn copy(app: &mut VectorcraftApp) -> Result { + let text = text(app); + let chars = text.chars().count(); + app.clipboard_out = Some(text); + app.status(COPIED); + Ok(json!({ "chars": chars })) +} + +/// Tell the user, at launch, that the last session stopped responding and was closed. +pub fn last_session_stopped(app: &mut VectorcraftApp) { + app.status(LAST_SESSION_STOPPED); +} + +#[cfg(test)] +mod tests { + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn the_command_copies_the_hosts_text_and_says_so() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.services.troubleshooting = Some(Box::new(|| "platform: test\n".to_string())); + let r = app.run("help.copyTroubleshootingInfo", json!({})).unwrap(); + assert_eq!(r["chars"], 15); + assert_eq!(app.clipboard_out.as_deref(), Some("platform: test\n")); + assert_eq!(app.ui.status, COPIED); + } + + #[test] + fn without_the_service_the_version_is_copied() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("help.copyTroubleshootingInfo", json!({})).unwrap(); + assert_eq!(app.clipboard_out, Some(format!("VectorCraft {}\n", env!("CARGO_PKG_VERSION")))); + } + + #[test] + fn running_a_command_marks_it_for_the_hang_report() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.beacon = Box::leak(Box::new(crate::hang_beacon::Beacon::new())); + app.run("help.copyTroubleshootingInfo", json!({})).unwrap(); + assert_eq!(app.beacon.recent_commands(), Some(vec!["help.copyTroubleshootingInfo".to_string()])); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2dd361a7d6..46fde93aad 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -730,6 +730,35 @@ mod gradient_chip_tests { assert_eq!(at(&up, 0, 2), at(&up, 4, 2)); } + /// A conic chip sweeps clockwise from its angle, or counterclockwise when the gradient is + /// mirrored. + #[test] + fn conic_chip_sweeps_the_way_the_gradient_turns() { + let at = |colors: &[Color32], i: usize, j: usize| colors[j * 5 + i].r(); + let mut gp = paint(GradientKind::Conic, 0.0); + let chip = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); + // From the right: a quarter turn on is below the center, halfway around left of it. + assert!(at(&chip, 2, 4).abs_diff(191) <= 2 && at(&chip, 2, 0).abs_diff(64) <= 2, "{chip:?}"); + assert!(at(&chip, 0, 2).abs_diff(128) <= 2, "{chip:?}"); + let c = vectorcraft_geom::kurbo::Point::new(50.0, 50.0); + gp.geom = + Some(vectorcraft_color::GradientGeom { start: c, end: c + vectorcraft_geom::kurbo::Vec2::new(10.0, 0.0), aspect: -1.0, focal: None }); + let mirrored = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); + assert!(at(&mirrored, 2, 4).abs_diff(64) <= 2 && at(&mirrored, 2, 0).abs_diff(191) <= 2, "{mirrored:?}"); + } + + /// A diamond chip runs from the center out to a square whose edges pass through the chip's + /// corners: halfway along an edge and halfway to a corner are the same color. + #[test] + fn diamond_chip_runs_out_to_the_corners() { + let at = |colors: &[Color32], i: usize, j: usize| colors[j * 5 + i].r(); + let chip = gradient_chip_colors(&paint(GradientKind::Diamond, 0.0), 20.0, 20.0, 4, 4); + assert_eq!((at(&chip, 2, 2), at(&chip, 0, 0), at(&chip, 4, 4)), (255, 0, 0), "{chip:?}"); + for (i, j) in [(2, 0), (0, 2), (1, 1), (3, 3)] { + assert!(at(&chip, i, j).abs_diff(128) <= 2, "({i}, {j}): {chip:?}"); + } + } + #[test] fn radial_chip_runs_from_the_centre_out() { let colors = gradient_chip_colors(&paint(GradientKind::Radial, 0.0), 20.0, 20.0, 4, 4); @@ -737,6 +766,85 @@ mod gradient_chip_tests { assert_eq!(colors[0], Color32::BLACK); } + /// A stop at opacity 0 is clear on the chip of every kind, and one at 50% half clear. + #[test] + fn chip_shows_the_stops_opacity() { + use vectorcraft_color::{Color, GradientStop}; + for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic] { + let mut gp = paint(kind, 0.0); + gp.gradient.stops = vec![ + GradientStop { opacity: 0.5, ..GradientStop::new(0.0, Color::BLACK) }, + GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) }, + ]; + let chip = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); + let (lo, hi) = chip.iter().fold((u8::MAX, 0), |(lo, hi), c| (lo.min(c.a()), hi.max(c.a()))); + // No grid point of a conic chip lands exactly at the end of its sweep. + assert!(lo <= if kind == GradientKind::Conic { 12 } else { 0 }, "{kind:?}: {chip:?}"); + assert!(hi.abs_diff(128) <= 1, "{kind:?}: {chip:?}"); + } + let at = |colors: &[Color32], i: usize, j: usize| colors[j * 5 + i]; + let mut gp = paint(GradientKind::Linear, 0.0); + gp.gradient.stops[1].opacity = 0.0; + let chip = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); + assert_eq!(at(&chip, 0, 2), Color32::WHITE); + assert_eq!(at(&chip, 4, 2).a(), 0); + // Radial: an opaque edge around a clear center. + let mut gp = paint(GradientKind::Radial, 0.0); + gp.gradient.stops[0].opacity = 0.0; + let chip = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); + assert_eq!(at(&chip, 2, 2).a(), 0); + assert_eq!(chip[0], Color32::BLACK); + } + + /// A chip with a clear stop draws a checkerboard under the gradient; an opaque one does not. + #[test] + fn a_clear_gradient_chip_has_a_checkerboard_under_it() { + let ctx = egui::Context::default(); + let shapes = |gp: &GradientPaint| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| gradient_chip(ui, Rect::from_min_size(pos2(10.0, 10.0), vec2(20.0, 20.0)), gp)); + out.textures_delta.clear(); + out.shapes.into_iter().map(|s| s.shape).collect::>() + }; + let opaque = shapes(&paint(GradientKind::Linear, 0.0)); + assert!(matches!(opaque[..], [egui::Shape::Mesh(_)]), "{opaque:?}"); + let mut gp = paint(GradientKind::Linear, 0.0); + gp.gradient.stops[1].opacity = 0.0; + let clear = shapes(&gp); + let n = clear.len(); + assert!(n > 2 && matches!(clear[n - 1], egui::Shape::Mesh(_)), "{clear:?}"); + let fills: std::collections::HashSet<_> = + clear[..n - 1].iter().filter_map(|s| if let egui::Shape::Rect(r) = s { Some(r.fill) } else { None }).collect(); + assert_eq!(fills, [Color32::WHITE, Color32::from_gray(204)].into_iter().collect(), "{clear:?}"); + } + + #[test] + fn freeform_chip_shows_the_points_opacity() { + use vectorcraft_color::{Color, Freeform, FreeformPoint}; + use vectorcraft_geom::kurbo::Point; + let mut gp = paint(GradientKind::Freeform, 0.0); + let clear = FreeformPoint { opacity: 0.0, ..FreeformPoint::new(Point::new(10.0, 10.0), Color::BLACK) }; + gp.freeform = Some(Freeform { points: vec![clear], ..Default::default() }); + let chip = gradient_chip_colors(&gp, 20.0, 20.0, 4, 4); + assert!(chip.iter().all(|c| c.a() == 0), "{chip:?}"); + } + + /// A Holographic glow's chip is clear at the corners and nearly opaque at the center; a foil's + /// chip is opaque everywhere. + #[test] + fn holographic_chips_show_a_glow_clear_at_its_edge_and_a_foil_opaque() { + use vectorcraft_color::Paint; + let lib = vectorcraft_color::libraries::builtin_library("holographic").unwrap(); + let chip = |name: &str| match &lib.swatch(name).unwrap().paint { + Paint::Gradient(g) => gradient_chip_colors(g, 20.0, 20.0, 4, 4), + p => panic!("{name}: {p:?}"), + }; + let glow = chip("Mint Halo"); + assert!([0, 4, 20, 24].iter().all(|&i| glow[i].a() == 0), "{glow:?}"); + assert!(glow[2 * 5 + 2].a() >= 240, "{glow:?}"); + let foil = chip("Prism Veil"); + assert!(foil.iter().all(|c| c.a() == 255), "{foil:?}"); + } + #[test] fn freeform_chip_mixes_points_in_the_model_they_share() { use vectorcraft_color::{Color, Freeform, FreeformPoint}; diff --git a/crates/ui-egui/src/widgets/chips.rs b/crates/ui-egui/src/widgets/chips.rs index a6b83f700d..017ba588ce 100644 --- a/crates/ui-egui/src/widgets/chips.rs +++ b/crates/ui-egui/src/widgets/chips.rs @@ -39,6 +39,10 @@ pub fn gradient_chip(ui: &Ui, rect: Rect, gradient: &vectorcraft_color::Gradient let cols = ((rect.width() / 3.0).ceil() as usize).clamp(1, max); let rows = ((rect.height() / 3.0).ceil() as usize).clamp(1, max); let colors = gradient_chip_colors(gradient, rect.width(), rect.height(), cols, rows); + // Stops below full opacity show a checkerboard through them. + if colors.iter().any(|c| c.a() < u8::MAX) { + checkerboard(ui, rect); + } let mut mesh = egui::Mesh::default(); for (k, color) in colors.into_iter().enumerate() { let (i, j) = (k % (cols + 1), k / (cols + 1)); @@ -55,14 +59,32 @@ pub fn gradient_chip(ui: &Ui, rect: Rect, gradient: &vectorcraft_color::Gradient ui.painter().add(egui::Shape::mesh(mesh)); } +/// A white and light gray checkerboard filling `rect`, with cells a quarter of its shorter side +/// (3 to 8 points). +fn checkerboard(ui: &Ui, rect: Rect) { + let p = ui.painter(); + p.rect_filled(rect, 0.0, Color32::WHITE); + let cell = (rect.width().min(rect.height()) / 4.0).clamp(3.0, 8.0); + let cols = (rect.width() / cell).ceil() as usize; + let rows = (rect.height() / cell).ceil() as usize; + for j in 0..rows { + for i in (j % 2..cols).step_by(2) { + let min = pos2(rect.left() + cell * i as f32, rect.top() + cell * j as f32); + let square = Rect::from_min_size(min, Vec2::splat(cell)).intersect(rect); + p.rect_filled(square, 0.0, Color32::from_gray(204)); + } + } +} + /// The colours at the `(cols + 1) x (rows + 1)` grid points (row by row) of a `width` x `height` -/// chip showing `gp` as it would look on an object of that size. +/// chip showing `gp` as it would look on an object of that size, with the gradient's opacity as +/// their alpha. pub(super) fn gradient_chip_colors(gp: &vectorcraft_color::GradientPaint, width: f32, height: f32, cols: usize, rows: usize) -> Vec { use vectorcraft_color::{GradientGeom, GradientKind}; let b = vectorcraft_geom::kurbo::Rect::new(0.0, 0.0, width as f64, height as f64); - let rgb = |c: vectorcraft_color::Color| { - let [r, g, b, _] = c.to_rgba8(1.0); - Color32::from_rgb(r, g, b) + let rgba = |(c, a): (vectorcraft_color::Color, f32)| { + let [r, g, b, a] = c.to_rgba8(if a.is_finite() { a } else { 1.0 }); + Color32::from_rgba_unmultiplied(r, g, b, a) }; let at = |k: usize| { let (i, j) = (k % (cols + 1), k / (cols + 1)); @@ -74,19 +96,23 @@ pub(super) fn gradient_chip_colors(gp: &vectorcraft_color::GradientPaint, width: let field = gp.freeform_on(painted).model_field(vectorcraft_color::freeform::spread_scale(painted)); return (0..n) .map(|k| { - let ([r, g, b], _) = field.display_sample(at(k)); + let ([r, g, b], a) = field.display_sample(at(k)); let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - Color32::from_rgb(q(r), q(g), q(b)) + Color32::from_rgba_unmultiplied(q(r), q(g), q(b), q(if a.is_finite() { a } else { 1.0 })) }) .collect(); } // A placed gradient keeps its direction; a fresh one is fitted to the chip at its angle. let angle = gp.geom.map_or(gp.angle, |g| g.angle_deg()); - let geom = GradientGeom::fit(gp.gradient.kind, b, if angle.is_finite() { angle } else { 0.0 }); + let mut geom = GradientGeom::fit(gp.gradient.kind, b, if angle.is_finite() { angle } else { 0.0 }); + // A mirrored conic's chip turns the way the gradient does on its object. + if gp.gradient.kind == GradientKind::Conic && gp.geom.is_some_and(|g| g.is_mirrored()) { + geom.aspect = -1.0; + } (0..n) .map(|k| { let t = geom.param_at(gp.gradient.kind, at(k)).clamp(0.0, 1.0) as f32; - rgb(gp.gradient.sample(t).0) + rgba(gp.gradient.sample(t)) }) .collect() } diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index a6789916c6..1564025a41 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -30,7 +30,8 @@ pub enum PanelDrag { /// `place`). LibrarySymbol { library: String, name: String }, /// A Brushes panel brush (`def`: its definition, for the chip at the pointer): the path it is - /// dropped on takes it (`brush.apply`). + /// dropped on takes it (`brush.apply`); dropped where there is no art, a scatter, art or pattern + /// brush places a copy of its art there (`brush.placeArt`). Brush { name: String, def: serde_json::Value }, /// A brush of a brush library panel (`name`: its name in `library`): the path it is dropped on /// takes it (`brush.addFromLibrary` with `apply`), and the Brushes panel adds it. diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 7e3c9acc47..3466f78f4b 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -24,6 +24,10 @@ pub struct Workspace { /// The Control bar is docked to the bottom of the window (built-in workspaces, and workspaces /// saved without this field: the top). pub control_bar_bottom: bool, + /// The groups of the Control bar's options its panel menu has off (built-in workspaces, and + /// workspaces saved without this field: none). + #[serde(skip_serializing_if = "std::collections::BTreeSet::is_empty", deserialize_with = "crate::chrome::read_hidden_groups")] + pub control_bar_hidden_groups: std::collections::BTreeSet, pub rulers: bool, pub toolbar: bool, pub toolbar_double: bool, @@ -186,6 +190,7 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { name: name.into(), control_bar: ui.control_bar, control_bar_bottom: ui.control_bar_bottom, + control_bar_hidden_groups: ui.control_bar_hidden_groups.clone(), rulers: ui.view.rulers, toolbar: ui.toolbar, toolbar_double: ui.toolbar_double, @@ -216,6 +221,7 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { pub fn apply(ui: &mut UiState, w: &Workspace) { ui.control_bar = w.control_bar; ui.control_bar_bottom = w.control_bar_bottom; + ui.control_bar_hidden_groups = w.control_bar_hidden_groups.clone(); ui.view.rulers = w.rulers; ui.toolbar = w.toolbar; ui.toolbar_double = w.toolbar_double; @@ -806,4 +812,44 @@ mod tests { apply(&mut ui, &old); assert!(ui.control_bar && !ui.control_bar_bottom, "an older workspace docks the bar at the top"); } + + /// A workspace keeps the groups of Control bar options its panel menu has off: switching + /// brings each workspace's back, Reset turns a built-in workspace's on again, and they survive + /// the preferences' JSON. A workspace or preferences saved without them, or with groups the bar + /// does not have, show every group, or the ones they name that it has. + #[test] + fn saved_workspaces_restore_the_control_bar_groups() { + let hidden = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::>(); + let mut ui = UiState { control_bar: true, control_bar_hidden_groups: hidden(&["opacity", "transform"]), ..Default::default() }; + save_as(&mut ui, "Lean").unwrap(); + switch(&mut ui, ESSENTIALS).unwrap(); + assert!(ui.control_bar_hidden_groups.is_empty(), "Essentials shows every group"); + ui.control_bar_hidden_groups = hidden(&["snapping"]); + switch(&mut ui, "Lean").unwrap(); + assert_eq!(ui.control_bar_hidden_groups, hidden(&["opacity", "transform"]), "the saved workspace's groups"); + switch(&mut ui, ESSENTIALS).unwrap(); + assert_eq!(ui.control_bar_hidden_groups, hidden(&["snapping"]), "Essentials as it was left"); + reset(&mut ui); + assert!(ui.control_bar_hidden_groups.is_empty(), "Reset Essentials shows every group again"); + switch(&mut ui, "Lean").unwrap(); + let json = serde_json::to_value(&ui).unwrap(); + assert_eq!(json["custom_workspaces"][0]["controlBarHiddenGroups"], serde_json::json!(["opacity", "transform"])); + let back: UiState = serde_json::from_value(json).unwrap(); + assert_eq!(back.control_bar_hidden_groups, hidden(&["opacity", "transform"]), "kept in the preferences"); + assert_eq!(back.custom_workspaces[0].control_bar_hidden_groups, hidden(&["opacity", "transform"]), "kept with the workspace"); + let mut old = serde_json::to_value(&back.custom_workspaces[0]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("controlBarHiddenGroups").is_some()); + let old: Workspace = serde_json::from_value(old).unwrap(); + apply(&mut ui, &old); + assert!(ui.control_bar_hidden_groups.is_empty(), "an older workspace shows every group"); + let mut prefs = serde_json::to_value(&back).unwrap(); + prefs["control_bar_hidden_groups"] = serde_json::json!(["opacity", "stroke", 3, "paragraph"]); + prefs["custom_workspaces"][0]["controlBarHiddenGroups"] = serde_json::json!("opacity"); + let read: UiState = serde_json::from_value(prefs.clone()).unwrap(); + assert_eq!(read.control_bar_hidden_groups, hidden(&["opacity", "paragraph"]), "groups the bar does not have are dropped"); + assert!(read.custom_workspaces[0].control_bar_hidden_groups.is_empty(), "a value that is not a list shows every group"); + prefs.as_object_mut().unwrap().remove("control_bar_hidden_groups"); + let read: UiState = serde_json::from_value(prefs).unwrap(); + assert!(read.control_bar_hidden_groups.is_empty(), "older preferences show every group"); + } } diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 0000000000..c0ffb69fdf --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.vectorcraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.vectorcraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index e47ef9bbe2..246352e469 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -325,3 +325,33 @@ fn help_safe_mode_enables_a_plug_in_for_the_next_launch_only() { done(&launch_dir); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn help_safe_mode_lists_a_plug_in_found_under_several_files_once() { + let _f = fresh(); + let dir = store_with_two("help-files"); + let launch_dir = dir.join("Launch"); + let mut app = launch(&dir, &launch_dir, false); + let x = |file: &str| Item { id: Some("test.ui.x".into()), file: Some(file.into()), name: Some("X".into()) }; + let y = Item { id: Some("test.ui.y".into()), file: None, name: Some("Y".into()) }; + let z = Item { id: None, file: Some("z.wasm".into()), name: None }; + // x is turned off by its id, then found under two files, as loading a folder finds it. + let x_by_id = Item { file: None, ..x("") }; + for item in [&x_by_id, &y, &z] { + assert!(safe_mode::set_enabled(item, false)); + } + assert!(safe_mode::disable_file_of(&x("a.wasm"))); + assert!(safe_mode::disable_file_of(&x("b.wasm"))); + assert!(app.session.store_disabled_plugins()); + assert_eq!(safe_mode::disabled().len(), 4, "an entry for each of x's files"); + app.run("help.safeMode", json!({})).unwrap(); + let items = app.ui.dialog.as_ref().unwrap().fields["items"].as_array().unwrap().clone(); + let labels: Vec<&str> = items.iter().map(|v| v["label"].as_str().unwrap()).collect(); + assert_eq!(labels, ["X", "Y", "z.wasm"], "one row for each plug-in"); + frame(&mut app); + app.ui.dialog.as_mut().unwrap().fields["items"][0]["enable"] = json!(true); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(safe_mode::disabled(), [y, z], "every entry with x's id is turned on"); + done(&launch_dir); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 04715474d0..6619cffd6f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -107,24 +107,24 @@ the two can still win that race. | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.resize` / `ui.focus` | | | -| `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | +| `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`) counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF with Use Artboards | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | | `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary). `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set | -| `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab | +| `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. A save or export that writes other files beside that path (a file per artboard, linked images, image maps) checks them before it writes anything: when any of them exists, it writes nothing and opens a `replaceFiles` dialog (fields `message`, `detail` (each file's name when there are several), `files`, `__command`, `__params`; the reply is `{"pending": "replaceFiles"}`, or comes once a Background Save or Export ends): `ui.dialog.confirm` runs the save or export again and replaces them, `ui.dialog.cancel` writes nothing; a dialog open when a background job asks stays open, and the question follows it. A save does not ask about the files the document's last Save or Save As in this session wrote. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab | | SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them | | `app.export` raster options | `{path?, format: png \| jpg \| webp, ppi?, width?, height?, background?, antiAlias?, interlaced?, quality?}` | `ppi` sets the pixel size (72 = one pixel per point) and is stored in PNG and JPEG files (WebP files store no resolution); `width` or `height` sets the size of each file in pixels instead (`width` wins), and PNG and JPEG files store the resolution that results; `background` is `transparent`, `white`, `black` or `"#rrggbb"`; `antiAlias` is `none`, `art` or `type` (text snapped to pixels); `interlaced` writes an Adam7 PNG. The PNG Options dialog (`pngOptions`; `jpgOptions` / `webpOptions` for the other raster formats) has the same fields: fill them with `ui.dialog.set` and press OK with `ui.dialog.confirm` | | `app.export` JPEG options | `{path?, format: jpg, quality?: 0–100, colorModel?: rgb \| cmyk \| gray, method?: baseline \| optimized \| progressive, scans?: 3–5, embedIcc?, imageMap?: none \| client \| server}` | `cmyk` writes ink amounts in the working CMYK space (CMYK colours keep their inks; RGB ones are separated with the colour settings); `embedIcc` (default true) embeds sRGB, the working CMYK profile or a grey profile, generated by the CMS; `imageMap` also writes `.html` (client-side ``) or `.map` (NCSA) beside the image for the objects with a URL and an Image Map shape (`attributes.set`), returned in `linked`. The `jpgOptions` dialog has these fields too (`quality` is shown 0–10; a CMYK document defaults to `cmyk`) | | `app.export` PNG-8 and GIF | `{path?, format: png8 \| gif, colors?: 2–256, reduction?: perceptual \| selective \| adaptive \| web \| blackWhite \| gray, dither?: none \| diffusion \| pattern \| noise, ditherAmount?: 0–100, transparency?, matte?, interlaced?, …raster options}` | a palette of at most `colors` entries (art with that many colours or fewer keeps them exactly); pixels under half opacity become one transparent entry unless `transparency` is false, partly transparent edges are blended over `matte` (`none` keeps their colour). `png8` writes an indexed `.png` (1–8 bits per pixel); Export for Screens rows take both. The `png8Options` / `gifOptions` dialogs have these fields | | `app.export` Text and WebP | `{path?, format: txt, encoding?: utf8 \| utf16, lineEndings?: lf \| crlf, selectionOnly?}` / `{format: webp, lossless?, quality?}` | Text writes the stories in stacking order (back to front; a thread once; hidden objects and template layers left out), each line ended by `lineEndings`; `utf16` is little-endian with a byte order mark. Export As → Text opens `txtOptions` (fields `path`, `encoding`, `lineEndings`, `selectionOnly`; OK writes the file). WebP is always lossless: `lossless: false` adds a warning | -| `engine.execute` `document.exportForOffice` | `{}` / `{path?, ppi?: 72 \| 150 \| 300, transparent?, artboard?}` | File → Save for Office Documents…: without params opens `saveForOffice` (fields `ppi`, `transparent`, `artboard`; OK picks the file); with params writes the artboard as a PNG (`path`, else a picked file) → `{path}`, and the status bar shows the first of the export's `warnings` as Save As shows a save's notes. Headless it returns `{dataBase64, width, height, warnings}` | +| `engine.execute` `document.exportForOffice` | `{}` / `{path?, ppi?: 72 \| 150 \| 300, transparent?, artboard?}` | File → Save for Office Documents…: without params opens `saveForOffice` (fields `ppi`, `transparent`, `artboard`; OK picks the file); with params writes the artboard as a PNG (`path`, else a picked file) → `{path}`, and the status bar shows the export's `warnings` as Save As shows a save's notes. Headless it returns `{dataBase64, width, height, warnings}` | | Native file dialogs | any command with no `path` that needs one (`file.open`, `file.saveAs`, `file.place`, exports…) | on macOS (a sheet on the window) and Linux the dialog doesn't hold the window: the call returns `"cancelled"` at once, `ui.inspect` reports `fileDialog`, and when the person at the computer picks a file the command runs again on the document it was asked for. While it is open another dialog is refused: that call returns `"cancelled"` too, and the status bar (`ui.inspect` → `ui.status`) says `"A file dialog is open: choose there first"`; on macOS `app.quit`, `file.close` and `file.closeAll` return that message and the menu bar does nothing (#592, #867). On Windows the dialog is shown in line: the call returns once it closes. Pass `path` to skip the dialog | | Background Save / Export | `app.save`, `app.export {path}`, `file.save`, `file.saveAs`, `file.saveCopy`, `file.exportForScreens {folder, …}` | with the `backgroundSave` / `backgroundExport` preferences on (the default) the desktop app writes the file from a snapshot on a worker thread: the call returns `{path, background: true, status}` at once (`file.exportForScreens`: `{background: true, status}`, and the files are written into the folder from a snapshot taken at the call), `ui.inspect` lists the jobs still running in `background` (labels such as `"Saving a.vectorcraft"`), and the document counts as saved (as of the snapshot) once its file is written. Quit and Close wait for them. A job that fails reports the error in the status bar only (`ui.inspect` → `ui.status`), a path outside `--automation-write-root` included. With the preferences off (`prefs.set`), saves return once written. `app.save {path?, wait: true}` and `app.export {path, wait: true}` wait for the jobs already running, write the file before they reply whatever the preferences are set to, and return its result or the error. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the preferences. A `wait` that is not `true`, `false` or `null` is refused with "`wait` must be true or false", and nothing is written | | `engine.execute` `file.exportForScreens` | `{}` / `{…document.exportForScreens params}` | without params opens `exportForScreens` on the settings the document last exported with (`document.exportSettings`). While the Artboard tool is in use, the artboards it has selected (its `selected` option, the rows the Artboards panel highlights) are checked instead, and `select` is `range`, or `all` when every artboard is selected. Fields: `tab` (`artboards` \| `assets` \| `layers` \| `selection`; OK reads Export Layer or Export Selection on those), `layers` ([layer id…] checked), `selectionMode` (`one` \| `each`), `name` (the file name pattern of `document.exportForScreens`), `counterStart`, `folders` (`none` \| `rows` \| `format` \| `item` \| `itemFormat`), `exportPreset` (the preset applied last), `__savePreset` (the name typed to save one), `select` (`all` \| `range` \| `full`), `range` ("1-3, 5"), `boards` (a bool per artboard; checking them sets `select` and `range`), `includeBleed`, `folder` (desktop; default the Desktop, else home), `openLocation`, `subfolders`, `prefix`, `preset` (`""` \| `mobile` \| `density`), `formats` (rows `{format, scale: "2x" \| "100w" \| "100h" \| "72ppi", suffix, quality?, folder?}`), `settings` (`{png \| png8 \| jpg \| webp \| gif \| svg \| pdf: {…options}}`, the gear's Format Settings; `__settings` names the format shown). `ui.dialog.confirm` exports (a bad range or no folder keeps it open); on the web OK reads "Download" and the files download (several as one `.zip`). With params it runs `document.exportForScreens`: no `folder` returns the files (or with `zip: true` one zip) as `dataBase64`; with `openLocation` the first file is shown in the file manager. When `warnings` is not empty, an export into a folder or a download shows the first in the status bar as Save As shows a save's notes | | Export for Screens' Assets tab, Asset Export panel | `ui.dialog.set` `tab: "assets"`, `assets: [asset id…]`; `window.panel {panel: "assetExport"}` | on the Assets tab of `exportForScreens` the `assets` field lists the checked asset ids (all of them when it opens); `ui.dialog.confirm` runs `document.exportForScreens {assets}` (nothing checked keeps it open) and OK reads "Export Asset". The Asset Export panel acts through `assets.*` and shares the format rows with the dialog (`assets.settings.set`). The dialog has the format presets menu (☰). In the dialog, `exportPreset` names the preset applied last (`ui.dialog.set` of it applies the preset it names, as picking it does; a name that is not a preset's is an error and leaves the dialog as it was), `__exportPresets` lists the presets, and `__savePreset` holds the name being typed after Save Preset…. The panel menu applies presets through `assets.settings.set {exportPreset}` and holds Save As Preset…, Save Changes, Delete Preset, Import Preset… and Export Preset…. Import and Export use picked files. | | `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as one asset (`assets.add`; one per object with `multiple: true`) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` still exports the selection in one go, without the dialog | -| CSS Properties panel | `window.panel {panel: "cssProperties"}`; `engine.execute` `css.copy` / `css.exportFile` | the panel shows `css.selection` of the selection (after Generate CSS, while nothing is selected, `css.generate`); its menu holds the options the commands take (`units`, `position`, `dimensions`, `unnamed`, `rasterize`). `css.copy {scope?, …options}` copies the CSS to the clipboard → `{css, rules}`; `css.exportFile {path?, scope?, …options}` writes `css.export` to `path` (else a picked file; the web downloads it) with the pictures of rasterized art next to it → `{path, rules, images, warnings}`, and the status bar shows the first of `warnings` as Export As shows an export's notes | +| CSS Properties panel | `window.panel {panel: "cssProperties"}`; `engine.execute` `css.copy` / `css.exportFile` | the panel shows `css.selection` of the selection (after Generate CSS, while nothing is selected, `css.generate`); its menu holds the options the commands take (`units`, `position`, `dimensions`, `unnamed`, `rasterize`). `css.copy {scope?, …options}` copies the CSS to the clipboard → `{css, rules}`; `css.exportFile {path?, scope?, …options}` writes `css.export` to `path` (else a picked file; the web downloads it) with the pictures of rasterized art next to it → `{path, rules, images, warnings}`, and the status bar shows `warnings` as Export As shows an export's notes | | `ui.dialog.*` on `importPdf` | `{field: "page" \| "allPages" \| "range" \| "cropTo" \| "password", value}` | opening (`app.open`, `file.open`) a PDF, `.ai` or `.ait` with a password, or one with several pages unless it is a `.ai` or `.ait` with its editing data or carries its VectorCraft document (those open whole), or placing (`file.place` without `page`) any of them with several pages or a password, opens the Import PDF dialog (`mode`: `open` or `place`; `pageCount`). While `__locked` is true, set `password` and `ui.dialog.confirm` to unlock it (a one-page file then opens or is placed). Then set `allPages: false` and `range` ("2-3, 5") to open some pages, or `page` to place one, and `cropTo` (`bounding`, `art`, `crop`, `trim`, `bleed`, `media`); `ui.dialog.confirm` opens or places them (placing keeps the other `file.place` params, such as `link`, `template` and `at`, in `__place`). `document.open {pages, cropTo, password}` and `file.place {page, crop, password}` do the same without the dialog | @@ -217,7 +217,9 @@ export's own parameters); `ui.dialog.confirm` writes the file. An importer plug- `pluginImport` dialog when `file.openWith` is given no `params`: one field per parameter, `__plugin`, and `__open` (`path` and `importer`); `ui.dialog.confirm` opens the file. `ui.installPlugin {path?}` installs a `.wasm` (without a path it asks for one); one that needs approval opens the `pluginInstall` dialog, which only a person can confirm -(`ui.dialog.confirm` and injected input are refused); see [plugins.md](plugins.md). +(`ui.dialog.confirm` and injected input are refused). When a control request opened it, directly or through a file +dialog, the reply adds `approval: "personMustStartInstall"` and nobody can confirm it: the person chooses Object › +Plug-ins › Install Plug-in… to install the plug-in; see [plugins.md](plugins.md). Overprint Black: the Edit → Edit Colors → Overprint Black… menu item opens a `command` parameter dialog for `edit.colors.overprintBlack` (fields `remove`, `percentage`, `fill`, `stroke`, `includeCmyBlacks`, @@ -236,12 +238,15 @@ Edit or Apply Colors runs `ui.recolorDialog {colors, library?}` with the harmony recolours as usual; with nothing selected the colours themselves are the rows and `ui.dialog.confirm` saves them as a new colour group (`swatch.newGroup`, named by the `groupName` field). -Color panel options: `ui.colorPanel {mode?, options?}` picks the panel's mode as its panel menu does (`grayscale`, -`rgb`, `hsb`, `cmyk` or `websafe`; the active color converts to the mode's model as one undo step) and shows -(`options: true`) or hides (`false`) the options. It answers `{mode, options, shown}`: `mode` is null until a mode is -picked, and `shown` is the mode the panel shows the color in, or `tint` for a tint of a global or spot swatch. -Another mode, `lab` included, answers an error. The desktop app keeps both settings with its preferences, and -`ui.inspect` reports them as `ui.color_mode` and `ui.color_hide_options`. +Color panel options: `ui.colorPanel {mode?, options?, recentColors?}` picks the panel's mode as its panel menu does +(`grayscale`, `rgb`, `hsb`, `cmyk` or `websafe`; the active color converts to the mode's model as one undo step), +shows (`options: true`) or hides (`false`) the options, and checks (`recentColors: true`) or unchecks (`false`) Show +Recent Colors, which shows or hides the panel's Recent Colors row. Applied colors still join the list while the row +is hidden, and the Swatches panel keeps its own row. It answers `{mode, options, recentColors, shown}`: `mode` is null +until a mode is picked, and `shown` is the mode the panel shows the color in, or `tint` for a tint of a global or spot +swatch. Another mode, `lab` included, answers an error, as does an `options` or `recentColors` value that is not true +or false. The desktop app keeps the three settings with its preferences, and `ui.inspect` reports them as +`ui.color_mode`, `ui.color_hide_options` and `ui.color_show_recent_colors`. Color Themes panel (`window.panel {panel: "colorThemes"}`): its Create tab makes a theme on a harmony wheel and its My Themes tab lists the saved themes; every action runs a command (`colorTheme.save`, `colorTheme.delete`, @@ -396,7 +401,10 @@ the Tools panel alone, and Tab hides these toolbars with the other panels. Windo panel without them. A toolbar shown with its item or made with New Toolbar after Tab shows alone, and the other toolbars Tab hid are turned off. A toolbar's ••• button (`window.editToolbar {toolbar}`) opens the All Tools drawer beside it, and the drawer's drags and -`toolbar.addTool`, `toolbar.removeTool` and `toolbar.reset` with `toolbar` edit it; the drawer has no Show section +`toolbar.addTool`, `toolbar.removeTool` and `toolbar.reset` with `toolbar` edit it. The + button above the ••• +button (Add Tool…) opens a menu of every tool under the drawer's headings: a click on a tool runs `toolbar.addTool +{tool, toolbar}`, which puts it at the end, and the tools under its Remove Tool heading run `toolbar.removeTool +{tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, two-column flag, top-left corner, the groups torn off it). They are kept with the workspace they were made in: @@ -568,8 +576,12 @@ Document Setup: File → Document Setup… (`file.documentSetup`, Cmd+Alt+P) ope are what `document.setup` reports (`units`, `bleed` [top, bottom, left, right] in pt, `outlineImages`, `highlightSubstitutedGlyphs`, `gridSize`, `gridColors`, `simulatePaper`, `flattenerPreset`, `discardWhiteOverprint`, `language`, `quotes`, `typographersQuotes`, `superscript`, `subscript`, `smallCapsSize`, -`exportText`, `backgroundContents`) plus `tab` (`General`, `Transparency` or `Type`) and `bleedLinked`. -`ui.dialog.confirm` runs `document.setup` with them as one undo step; a bad value answers with an error and the dialog +`exportText`, `backgroundContents`) plus `tab` (`General`, `Transparency`, `Type` or `Color`) and `bleedLinked`, and +the Color tab's `colorMode` (`rgb` or `cmyk`), `convertColors` (a mode change converts the colors; `false` keeps their +numbers), `rgbProfile` and `cmykProfile` (a profile name, or null for the working space). +`ui.dialog.confirm` runs `document.setup` with them as one undo step. When the Color tab's fields differ from the +document, it runs `document.setup`, then `edit.assignProfile` with the changed profiles, then `file.documentColorMode` +in one `command.batch`, and the document's changes are one undo step. A bad value answers with an error and the dialog stays open. New Document: File → New… (`file.newDialog`, Cmd+N) opens the `newDocument` dialog. Its fields are `file.new`'s params @@ -701,8 +713,9 @@ with. DXF Options: Export As… with the DXF format (`file.exportAs {format: "dxf"}`, then the save dialog), or `ui.dxfOptionsDialog {path?, …document.exportDxf options}` for agents, opens the `dxfOptions` dialog. Its fields are `document.export` params: `dxfPreset` (`custom`, `cnc`), `version`, `unit` (a unit name such as `Millimeters`), `scale`, -`scaleLineweights`, `colors` (`8`, `16`, `256`, `true`), `rasterFormat` (`png`, `jpeg`), `preserve` (`appearance`, -`editability`), `selectedOnly`, `alterPaths`, `outlineText`, plus `path` and the artboard choice. Setting `dxfPreset` to +`scaleLineweights`, `colors` (`8`, `16`, `256`, `true`), `rasterFormat` (`png`, `jpeg`), `includeImages` (Include +Placed Images), `preserve` (`appearance`, `editability`), `selectedOnly`, `alterPaths`, `outlineText`, `includeHatches` +(Include Fill Hatches), plus `path` and the artboard choice. Setting `dxfPreset` to `cnc` sets the fields it sets (see `document.exportDxf`), and `dxfPreset` reads `custom` again once one of them is changed; setting it to `custom` puts back the defaults. `ui.dialog.confirm` checks them (a bad value, or Export Selected Art Only with nothing selected, keeps the dialog open), remembers them for the next DXF Options and @@ -784,12 +797,19 @@ artboards' files. A `.ai` file's `aiVersion` comes first: `"pdf"` (the default) Options"), which takes only `transparentImages` (`"flatten"` or `"omit"`), `hiddenObjects` (`"layer"`, `"omit"` or `"visible"`, the Hidden Objects menu), `outlineText` (the Text menu: false Editable, true Outlines) and, with several artboards, the artboard picker: `boards`, one bool per artboard (default: those last saved, else all), saved as `range`, one file per checked -artboard. OK is disabled with none checked. +artboard. OK is disabled with none checked. Save As to an EPS file opens the same dialog after the save panel (heading +"EPS Options") with `useArtboards`, `all` and `range`, then the options Export's EPS Options shows. Preview +(`previewFormat`), Overprints (`overprints`), Flattener preset (`flattenerPreset`) and PostScript (`level`) are menus: +a pick writes the option's value (`"tiffColor"`, `"preserve"`, a built-in preset's id such as `"medium"` or a saved +preset's name, the level as a number), and a value none of them names shows as it is. EMF and WMF: Export As… lists both formats (`file.exportAs {format: "emf"}` or `"wmf"`); they have no options dialog, so `ui.dialog.confirm` asks for the path and writes the file (one per artboard with Use Artboards). Open and Place read `.emf` and `.wmf`; a paste of `image/emf` from a system clipboard service runs `clipboard.importEmf`. +HP-GL: Export As… lists it (`file.exportAs {format: "hpgl"}`); it has no options dialog, so `ui.dialog.confirm` asks +for the path and writes the `.plt` file with the default options (one per artboard with Use Artboards). + TIFF, BMP and Targa Options: Export As… with the TIFF, BMP or Targa format (`file.exportAs {format: "tiff"}`, then the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster rows of PNG Options (`ppi`, `background`, `antiAlias`), then TIFF's `colorModel` (`rgb`, `cmyk`, `gray`; a CMYK document starts on `cmyk`), @@ -807,7 +827,7 @@ a preset) plus `__view` (`original`, `optimized`, `2up`, `4up`), `__zoom` (`fit` the image, or the page with HTML output; the web downloads the files); with `discard: true` it is Done: it remembers the settings and closes. `file.saveForWeb` with settings saves without the dialog, and `file.saveForWeb.browser` writes the HTML page to a temporary folder and opens it in the default browser (desktop). Both return the export's -`warnings`, and the status bar shows the first one as Save As shows a save's notes. +`warnings`, and the status bar shows them as Save As shows a save's notes. PSD Options: Export As… with the PSD format (`file.exportAs {format: "psd"}`, then the save dialog) opens `psdOptions`: the raster rows of PNG Options (`ppi`, `background`, `antiAlias`), then `colorModel` (`rgb`, `cmyk`, `gray`; a CMYK @@ -1049,7 +1069,7 @@ app: | `vectorcraft.docInspect(params)` / `vectorcraft.uiInspect(params)` | `document.inspect` / `ui.inspect` | | `vectorcraft.inspect()` | `ui.inspect` (the name before `uiInspect`) | | `vectorcraft.screenshot(params)` | `ui.screenshot` (no `path`: the PNG comes back inline, as `data` and as `pngBase64`) | -| `vectorcraft.openFile(name, bytes)` | opens the bytes the way a dropped file opens (returns `true` once queued) | +| `vectorcraft.openFile(name, bytes)` | opens the bytes the way a dropped file opens, as automation: a plug-in install it asks for has to be started by the person (returns `true` once queued) | | `vectorcraft.captureDownloads(on)` | while on, a save or export is kept in the page instead of downloaded | | `vectorcraft.files()` / `vectorcraft.readFile(name)` | the kept files (`{path, size}`) / one of them as a `Uint8Array` | diff --git a/docs/development.md b/docs/development.md index c6523bd035..e7831adf1b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Development -> **Last updated:** 2026-11-06 · **Change:** Hindi catalog and zero/one plural rule; desktop Devanagari fallback and optional craft-fonts UI face; native review pending. +> **Last updated:** 2026-11-12 · **Change:** minor (clipboard failure helper follows its Linux/BSD and test callers; previously: Hindi catalog and zero/one plural rule; desktop Devanagari fallback and optional craft-fonts UI face; native review pending). > **Last updated:** 2026-11-01 · **Change:** Linux: Automatic Linux Display Server opens the window through XWayland when a pen is attached on a Wayland session, so the pen draws (#4967); `VECTORCRAFT_NATIVE_WAYLAND=1` keeps Wayland. > **Last updated:** 2026-10-31 · **Change:** files opened while the app runs open in its window on Windows and Linux (#4892); `--new-instance`. > **Last updated:** 2026-10-29 · **Change:** Linux clipboard: the Flatpak on GNOME copies and pastes text through the core Wayland protocol. @@ -89,6 +89,8 @@ The desktop app writes its `log` records to standard error and to `logs/vectorcr By default VectorCraft's own crates log at `info` and everything else at `warn`. `RUST_LOG` replaces that with env_logger-style directives, for example `RUST_LOG=debug`, `RUST_LOG=warn,vectorcraft_render=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`vectorcraft*=debug`). The logger is `apps/vectorcraft/src/logging.rs`. `vectorcraft-cli mcp` has its own logger, which sends records to the MCP client (`docs/mcp.md`). +When the interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, which the process keeps locked. The report gives the part of the frame (the input hook, the app's logic, the interface, or the renderer after a frame in which any window had input), a system clipboard read or write in progress, the last 8 different command ids (a command run again moves to the end of the list), the times of the last 16 frames, the platform, the window system (Wayland, X11, AppKit, Win32, other or unknown), `XDG_CURRENT_DESKTOP`, `XDG_SESSION_TYPE`, whether the app runs in a Flatpak, the graphics adapter, the present mode and frame latency the app asks the window surface for, the session's running time and how many documents are open. It holds no document contents, file paths or command parameters, and no native stack. The time after a frame that minimizes or hides the main window, or starts moving or resizing it, is not timed, and neither is an in-line file dialog (Windows and Linux) or an open menu of the macOS menu bar. When the interface answers again, the log records after how long and the file is removed. A file that no process holds locked at a later launch was left by a session that was closed while it did not answer (a locked one belongs to another instance and is left alone): that launch writes the report to the log, moves the file to `logs/hang-report.1.txt` (older abandoned reports beyond the newest 16 are removed) and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the hang reports of this session and the last one, for a bug report. The watch is `apps/vectorcraft/src/hang_watch.rs`; the marks it reads are `crates/ui-egui/src/hang_beacon.rs`. + ## Environment variables (desktop app) | Variable | Effect | @@ -122,8 +124,8 @@ On GNOME/Wayland, enable **Preferences › User Interface › System Title Bar** The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On machines with two GPUs it renders on the one the desktop runs on unless Preferences say otherwise; see [Desktop graphics processor](#desktop-graphics-processor) (#502). The system clipboard (`apps/vectorcraft/src/clipboard.rs`) is arboard with its `wayland-data-control` feature: -- **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. Where there is no X11 either (the Flatpak on a Wayland session: `--socket=fallback-x11` gives it none), Copy and Paste use the compositor's core data-device protocol on the window's own connection through smithay-clipboard: text only (a copy's text or its SVG markup), and only while the window has focus. smithay-clipboard waits for the owner's data with no limit, so its reads run on a worker thread and a Paste waits 2 s at most: an owner that never sends its data costs one Paste 2 s, and later reads return at once until it answers. A clipboard neither backend opens is tried again after 1 s, doubling to a minute (a Copy or Paste of the user's at most once a second), and logged once when it goes and once when it comes back: before, the background Paste check reconnected and logged a warning every 250 ms. egui's own text paste into fields goes through smithay-clipboard and works either way. -- **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. A paste itself still reads on the UI thread, so pasting from such an owner waits for it once. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. +- **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. Where there is no X11 either (the Flatpak on a Wayland session: `--socket=fallback-x11` gives it none), Copy and Paste use the compositor's core data-device protocol on the window's own connection through smithay-clipboard: text only (a copy's text or its SVG markup), and only while the window has focus. smithay-clipboard waits for the owner's data with no limit, so its reads run on a worker thread and the UI thread waits 2 s at most: an owner that never sends its data costs one read 2 s, and later reads return at once until it answers. When a read gets no answer in its 2 s, such as a paste's check whether the clipboard still holds what VectorCraft copied, the paste waits on its background thread for that read's answer, up to 10 s after the read was sent, and pastes the text unless it is empty or what VectorCraft copied. A clipboard neither backend opens is tried again after 1 s, doubling to a minute (a Copy or Paste of the user's at most once a second), and logged once when it goes and once when it comes back: before, the background Paste check reconnected and logged a warning every 250 ms. egui's own text paste into fields goes through smithay-clipboard and works either way. +- **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. - **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. @@ -349,6 +351,10 @@ parameters. Shipped code therefore never panics. Anything that can fail returns ### Enforced by lints +The clipboard timeout failure helper is compiled for Linux/BSD workers and unit tests; production +macOS reads synchronously. Keep helper target gates aligned with their callers instead of disabling +dead-code warnings across the workspace. + `Cargo.toml` denies these clippy lints for the whole workspace, and `cargo xtask ci` runs clippy with `-D warnings`. The gate targets the current stable Rust (`rust-version` in `Cargo.toml` is only the minimum that builds the app, and no toolchain is pinned): when a new stable adds lints, they are fixed @@ -506,6 +512,7 @@ Scores and hour estimates are unchanged. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | Compile the clipboard failure helper only for Linux/BSD worker callers and unit tests; keep production macOS free of the unused helper without suppressing workspace dead-code warnings. | | 2026-11-06 | minor | Localisation: Hindi catalog, zero/one plurals, desktop and web font requirements; AI/MT draft, native review pending. | | 2026-10-31 | minor | Files opened while the app runs open in its window on Windows and Linux (#4892); `--new-instance` opts out. | | 2026-10-29 | minor | Linux clipboard: core Wayland protocol text fallback where arboard has neither data-control nor X11 (the Flatpak on GNOME).; its reads wait 2 s at most. | diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b1bc1fa38a..6b14fa0907 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -28,7 +28,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Rasterize | Rasterize… (as a live effect) | 1/1 | — | | Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | | SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists the document's own filters: VectorCraft ships no default filters. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | -| Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; Arc is a circular arc in the object's own proportions (#1578) | +| Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers its resolution, PDF export warns once per object with the requested and the lowest achieved ppi @@ -180,14 +180,14 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; no materials, shadows or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic), Rotate (Classic) and Map Art: none | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); no materials, soft shadows or ray tracing | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, -angular cut caps, exact visibility, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable) is 25–45 h. +angular cut caps, exact visibility, the rest of 3D Classic (Map Art), Turntable) is 25–45 h. ## Revision history diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index df33fa8b63..b99adf420e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -155,7 +155,8 @@ private editing data. VectorCraft: under them, clipped to where they show, along a smooth outline traced at the image's own resolution; that art stays) or omitted (Transparent Images, `transparentImages: "flatten"|"omit"`). Type is written as editable text objects (point type, area type and type on a path, with their fonts' PostScript names, sizes, colours, alignment, indents, leading, tracking and - scaling), which the reading app sets in those fonts; characters outside Windows-1252, vertical type, ruby, inline + scaling, and the Standard Vertical Roman Alignment and Tate-chu-yoko marks as `Tv` and `TY`), which the reading + app sets in those fonts; characters outside Windows-1252, vertical type, ruby, inline graphics and gradient or pattern fills make that type outlines, and so do rotated characters (Character Rotation, which a version 7 text object can't hold: the outlines keep the rotation, and the type is no longer editable text in the file), and Text: Outlines (`outlineText: true`) writes @@ -290,11 +291,12 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined Unicode CMap (`UniJIS-UCS2-H`), set as type in the font of the CIDFont's name; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). CNC preset and VCarve QA remain open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | +| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | -| PSD | open, place, export | yes (merged image, every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers (Photoshop Import Options) missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | -| PSB | open | yes (merged image) | no | | +| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers and a PSD import options dialog missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | +| PSB | open | yes (layers as layers, or the merged image) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | | JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` | @@ -339,6 +341,11 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Newly imported SVG/SVGZ titles use the imported-text rules: generated Untitled names and control-only titles give the filename fallback, other control characters are removed, and titles are limited to 65,536 characters. Native and Preserve Editing titles remain unchanged (#3626). | +| 2026-11-11 | minor | Native and Preserve Editing restores keep an existing File Info title exactly, including repeated spaces; imported-text fallback titles alone are normalized (#3626). | +| 2026-11-03 | minor | An imported document's own title goes into File Info only (#3626): an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title` is File Info's title (`metadata.title` in the native format, left out when unset so other documents save unchanged and older versions ignore it; written by exports); the document's name, which the tab, Save As and the default export names use, stays the file's name. | +| 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | +| 2026-11-11 | minor | `.ai` and EPS import, and what SVG export, PDF export and `.ai` save draw: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as a `.ai`'s own page aligns them (see type-parity.md, same date). In 224 users' files (used locally, never committed), 63 render differently: 54 closer to the page, 7 further, 1 alike and 1 that couldn't be compared; among them the median share of pixels that differ from the page went from 4.4% to 1.0%. Of the 7: one now opens from its layers instead of its PDF part (they differ from the page by less than the import's 5% limit now; type note 3.8%); one has a centred line whose spacing inside it differs from the page's, which now centres on the page's line while half of it no longer lies on the page's glyphs (type note 1.4% to 2.4%); five moved by less than 0.05 of a percentage point, in type the page draws in other glyphs. The type note shows a smaller share in 6 files; 2 more envelopes of type open live (129 to 131, none fewer in any file). SVG import: `text-anchor` aligns a line's advance, which ends after its last character's letter spacing, so a centred or right-aligned letter-spaced line moves back by half or all of it and stays where a reader draws it; SVG export, which anchors lines so, reads back unchanged (test `import_text::anchored_letter_spaced_lines_stay_where_a_reader_draws_them`). Affinity import: centred or right-aligned tracked artistic text moves by half or all of its last character's tracking, as layout now aligns it (unverified against Affinity, whose files we don't have), and differently aligned paragraphs line up by the widths layout aligns them by (`affinity_features::artistic_text_aligns_its_lines_within_the_longest`). Scores and estimates unchanged. (#6610) | | 2026-11-11 | minor | `.ai` and EPS import: while an envelope's contents are edited, the editing data keeps its mesh (a mesh's, a top object's or a warp's grid) in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art, as if the mesh hadn't followed the envelope when it moved: the envelope drew its contents elsewhere and kept its drawn art. A mesh or top object saved in Edit Contents (or a warp of type tried on its saved grid) whose mesh draws the contents as large as the drawn art, within half a point over width and height together, but further from it than that, is now tried again, after every other way and with one more of the import's checks, with its mesh moved by as far as the drawn art's box lies from the box of what it draws; it opens live there where it then draws as the drawn art. In users' files, used locally and never committed, only envelopes saved in Edit Contents draw elsewhere than their drawn art, and nothing in their dictionaries says by how much they moved. Tests `ai::tests::an_envelope_in_edit_contents_whose_mesh_stayed_behind_opens_live_on_its_drawn_art`, `tests_native::a_warp_of_type_in_edit_contents_whose_grid_stayed_behind_opens_on_its_drawn_art` (#6570) | | 2026-11-11 | minor | `.ai` save (PDF-compatible editing copy and legacy) and `.ai`/EPS open: a layer's `Lb` colour index follows the file's numbering, where Magenta, Cyan and Yellow are 4, 5 and 6 and `LAYER_COLORS` has Yellow, Magenta and Cyan; Yellow, Magenta and Cyan layers no longer come out as Magenta, Cyan and Yellow, and the other 24 presets are unchanged (#6502, from the index and RGB pairs in users' files). `LAYER_COLORS` keeps its order, so `.vectorcraft` files and the Layers panel don't change. Scores and estimates unchanged. | | 2026-11-11 | minor | `.ai` save: stroked type writes its stroke's cap, join and miter limit into the text document (keys 61, 62 and 64, as `.ai` import reads them since #6500), so they come back when the file opens again and no longer count among the attributes of type left out; a run without a stroke doesn't count them either, as they draw nothing. Tests `ai_editing::tests::type_comes_back_as_type`, `an_unstroked_run_with_a_stroke_style_loses_nothing` (follow-up to #6472) | @@ -485,25 +492,39 @@ Stop opacity on translated artboards remains outside this regression coverage. Feature evidence updated 2026-10-26; scores and estimates unchanged. -EPS is offered by Save As, and an opened EPS keeps its own path for ordinary Save. Save writes -one artboard (the first by default, or the named artboard), retaining its page bounds and transparent -margins rather than cropping to the drawn artwork. The whole editable VectorCraft document remains -embedded in EPS comments, including other artboards. Save bounds the optional TIFF preview to +EPS is offered by Save As, and an opened EPS keeps its own path for ordinary Save. The EPS +Options of Save As show Use Artboards with All or Range under it, for a separate file per artboard +([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), +unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with +a default of false, +[scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). +Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, +without the artboards' background colors; an opened EPS saved back this way loses the margins its +page had. With no visible art the page is the first artboard, in its color. Naming artboards with +`artboard`, `artboards` or `range` turns Use Artboards on. Checked with two or more chosen, the +file at the path is the central file of the visible art and each artboard is also written to +`<name>_<artboard>.eps` beside it, holding that artboard. Checked with one chosen, VectorCraft +writes that artboard as the page of the file at the path alone, retaining its bounds and +transparent margins. The file the document becomes carries the whole editable VectorCraft document +in EPS comments, including other artboards. Save bounds the optional TIFF preview to 1024 pixels on its longest side (about 4 MiB of RGBA pixels), avoiding the roughly 16 MiB preview a large artboard otherwise produces. Export keeps its existing 2048-pixel preview cap. Preview format choices are unchanged; no public preview-resolution option exists. The EPS PostScript appearance still flattens transparency; its existing warnings remain. This does not promise native Illustrator editing-data fidelity. -Cropped and selected-only EPS output remains available through Export. Save refuses those options. +Selected-only EPS output remains available through Export. Save refuses `selectedOnly`. An EPS opened from a preview, a partially interpreted program or damaged native editing data keeps its source-loss warning: writing over that original requires explicit confirmation. File › Save uses the same engine path and write-failure handling as other document formats. -Synthetic regressions: `tests::save::opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins`, -`eps_save_keeps_all_editing_artboards_while_printing_one_page`, +Synthetic regressions: `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, +`eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, +`eps_save_keeps_all_editing_artboards_in_the_file_of_one_page`, +`eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, +`cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `eps_save_supports_an_empty_artboard_without_cropping_its_page`, `partially_read_eps_requires_confirmation_before_save_back`, `eps_with_damaged_editing_data_requires_confirmation_before_save_back`, `eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data`, and the UI regressions `file_save_writes_opened_eps_back_without_another_save_as_dialog` and -`eps_save_as_keeps_page_options_and_writes_eps_without_export_only_switches`. +`eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. diff --git a/docs/gaps.md b/docs/gaps.md index e4b81f6b48..d7ce0f3f18 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (#6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -90,7 +90,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 13–23 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 4–10 | Wayland pressure | [hardware-parity.md](hardware-parity.md) | -| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 7–17 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 5–15 | no | [target-app-parity.md](target-app-parity.md) | | 12 | [G3 3D and Materials](#g3-3d-and-materials) | 25–45 | no | [effects-parity.md](effects-parity.md) | | 13 | [G7 Views and windows](#g7-views-and-windows) | 15–25 | no | [ui-parity.md](ui-parity.md) | | 14 | [G6 Automation and scripting](#g6-automation-and-scripting) | 4–8 | no | [target-app-parity.md](target-app-parity.md) | @@ -166,6 +166,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Improved:** Eyedropper has an original pipette cursor at its sampling tip; Use Precise Cursors keeps the crosshair. Bitmap/DPI and preference checks cover the distinction (#1269). OS cursor display and Caps Lock remain unverified. +- **Done (#6404):** Eyedropper character copying compensates for source and target text transforms, including highlighted ranges and reverse sampling; invalid dimensions reject the pick before document, default-paint or sample changes. G1 scores and estimates unchanged. - **Done (#1251):** Eyedropper source reads are independent of locks and isolation, including Shift/Shift+Alt and gradient stops. Source and selection preservation, unchanged Alt reverse/selection restrictions, hidden art and Undo/Redo have regression coverage. This addresses the reported behavior, with no new full-parity measurement. - **Done (#1253):** adding paint to an unpainted zero-width stroke restores the existing 1 pt default, including new-art defaults and Swap Fill/Stroke. The real Eyedropper inheritance sequence, targeted appearance items, preserved widths and Undo/Redo have regression coverage. - **Done:** a busy cursor while a file opens off the UI thread or a labelled background save or export runs (`Cursor::Busy` in `crates/tools/src/cursors.toml`). Heavy synchronous effect previews remain open. @@ -198,7 +199,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done (2026-11-06):** an EPS page that paints its gradients as rows of abutting one-colour strips imports them as linear gradients, so the seams between strips no longer show and an Illustrator EPS drawn that way keeps its layers instead of opening as its page. This narrows G9; scores and estimates unchanged. - **Done (2026-10-30):** from an audit of a user's `.ai`/EPS files: All Caps and Small Caps; placed files at their box's corner; pages cropped to the art; gradient mesh corners with handle weights of 0 and the transparency written after a mesh, a masked mesh and a blend; a layer's state block with the stroke style; type on a path spaced as the file lays it out (the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box, and the fit under Gravity does not reproduce the file's layout); EPS10 legacy-format type; a PDF of some artboards compared on the artboard its page shows. Comparison limits remain unchanged. This narrows G9; scores and estimates unchanged. -- **Save-back update (2026-10-26):** ordinary EPS Save retains page margins and the whole editable document; source-loss confirmation remains. Import fidelity gaps and estimates below are unchanged. +- **Save-back update (2026-10-26):** ordinary EPS Save retains page margins and the whole editable document; source-loss confirmation remains. Import fidelity gaps and estimates below are unchanged. Since 2026-11-12 Save keeps the page margins only with Use Artboards checked; unchecked, the default, the bounding box fits the visible art. - **Done (2026-10-16):** EPS legacy mesh corners and vector opacity masks retained; winding-declared compound member groups keep shared paint. Raster print-page minification no longer causes a false editing-data fallback; comparison limits remain unchanged. Synthetic regressions cover damage and missing artwork. This narrows G9; scores and estimates unchanged. @@ -322,8 +323,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** Numeric fields keep a text drag's start when the pointer gains focus, including short movements that egui still classifies as clicks (#1326). A release more than 1 pt from the press keeps the caret; a tap, including one with a pixel of pen or trackpad jitter, selects the whole value. Keyboard focus, double-click and numeric stepping remain regression-tested (`tests/numfields.rs`, `a_short_drag_released_as_a_click_keeps_its_caret` and `a_sub_threshold_movement_released_as_a_click_keeps_its_caret`). -- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback. Alter Paths for Appearance outlines only the strokes a CAD line can't draw (aligned, profiled, offset dashes, wider than 2.11 mm, or in R13 and R14), so a 1 pt circle or arc stays a CIRCLE or ARC. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. -- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE. A closed four-cubic ellipse, or a circle scaled out of proportion, is written as a native ELLIPSE in R13 and later; R12 keeps the existing fallback. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. +- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE. A closed four-cubic ellipse, or a circle scaled out of proportion, is written as a native ELLIPSE in R13 and later; R12 keeps the existing fallback. Alter Paths for Appearance outlines only the strokes a CAD line can't draw (aligned, profiled, offset dashes, wider than 2.11 mm, or in R13 and R14), so a 1 pt circle or arc stays a CIRCLE or ARC. DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Done:** Simplify and Add Anchor Points clear stale component selections on rewritten paths; Simplify previews and reports original/new point counts (#1272). - **Done:** Object › Path › Simplify opens its slider at the Auto-Simplify level for the selection and previews that result, as the [manual-simplify page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) describes; simplifying only a Direct Selection part of a path is done too (G1). @@ -618,9 +618,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi symbol static drops them; stored in the native format. Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol - Libraries Menu open each library in a library panel of its own (four original libraries generated in code, + Libraries Menu open each library in a library panel of its own (five original libraries generated in code, Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, Map Markers with Pin, - Flag, Crosshair and Checkpoint, and Inventory Icons with Sword, Shield, Potion, Key and Gem; User Defined; Other + Flag, Crosshair and Checkpoint, Inventory Icons with Sword, Shield, Potion, Key and Gem, and Skill Icons with + Attack, Defend, Heal, Buff and Ult; User Defined; Other Library… reads the symbols of any document VectorCraft opens); a click adds a symbol to the document's Symbols with its Symbol Options and the resources it uses, as one undo step, and dragging one onto the canvas also places it; Save Symbols / Save Symbol Library writes the @@ -629,8 +630,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (five original libraries generated in code: Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter - Shapes and Game Trails; User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (seven original libraries generated in code: Art Ribbons, Calligraphic Nibs, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails and Energy Beams; User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -644,15 +645,18 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Direct Selection of a path, compound path or type inside a dynamic instance also takes opacity and blend (`transparency.set`) and a gradient or pattern fill or stroke (`paint.setFill` / `paint.setStroke`, Eyedropper), for that instance only; - graphic style libraries (Window › Graphic Style Libraries; eight original libraries generated in code, including - Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert, and Status Effects - with Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade and Shield Buff; User Defined; Other - Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the eight shipped, and further symbol libraries beyond Basic - Shapes, UI Frames, Map Markers and Inventory Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; + graphic style libraries (Window › Graphic Style Libraries; ten original libraries generated in code, including + Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert, Status Effects + with Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade and Shield Buff, Painted and Sketched with + Washed Blue, Bristle Ochre, Pastel Heather, Charcoal Shade, Ink Contour, Wet Ink and Fine Pen, and Textures with + Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, + painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, + `graphicStyle.addFromLibrary`). +- **Missing:** more built-in brush libraries beyond the seven shipped (and further graphic-style libraries beyond the ten shipped, and further symbol libraries beyond Basic + Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches and highlighting matches before the start; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 6–16 h. +- **Estimate:** 5–15 h. ## G3 3D and Materials @@ -660,7 +664,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its existing appearance. All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, the rest of 3D - Classic (Revolve, Rotate, Map Art), Turntable, textures, map art and shading in 3D export. + Classic (Map Art), Turntable, textures, map art and shading in 3D export. - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. @@ -687,8 +691,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts and the `#targetengine` and `#engine` script directives (#1183 is - open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, +- **Missing:** the document object model for scripts and the `#engine` script directive (#1183 is + open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and export, and full agent control over MCP are done. @@ -854,6 +859,10 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| | 2026-11-12 | minor | G11: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); short-drag and jitter-tap regressions in `tests/numfields.rs`; estimates unchanged. | +| 2026-11-03 | minor | An imported document's own title (an SVG's root `<title>`, a PDF's XMP `dc:title` else its Info `Title`) goes into File Info only; the document's name stays the file's name (#3626); no scored gap or estimate reassessed. | +| 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | +| 2026-11-11 | minor | G5: built-in Energy Beams brush library (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Missing trimmed; estimate 5–15 → 4–14 h; MCP Brush libraries list Energy Beams. | +| 2026-11-11 | minor | G5: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); Missing trimmed; estimate 6–16 → 5–15 h; MCP Symbol libraries list Skill Icons. | | 2026-11-10 | minor | G6: MCP catalogue (#6460): headless lists `UI_COMMANDS` (`ui: true`), eight prompts, effect vs command ids, 33 tools, commands/reference; estimate unchanged. | | 2026-11-11 | minor | G5: built-in Status Effects graphic style library (Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade, Shield Buff); Missing trimmed; estimate 7–17 → 6–16 h; MCP docs list UI Frames and Map Markers under Symbol libraries. | | 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | @@ -1091,4 +1100,4 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv 2026-10-28 behavior correction: Flare ray rotation follows vertical travel at one degree per document point, independent of pointer event count. Shift freezes the current orientation; Space also freezes rotation on the first update. This is the chosen application interaction rate. Scores and estimates unchanged. ## EPS Save evidence (2026-10-26) -Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. +Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. diff --git a/docs/mcp.md b/docs/mcp.md index c766d812a1..fa22c66414 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -123,6 +123,18 @@ the suite) keep the agent to the folders you give it: - Every file a command writes must lie inside a **write root**: `save_file`, `export`, the save and export commands, Export for Screens, Package, Export for Web, print to file, `screenshot {path}`, library and preset saves to a path, the copies `links.relink {copy}` makes. +- A path the agent gives stays in a save or export reply, with the files written beside it. Paths it did not + give are left out when they are outside the read roots. `save_file`, `document.save` and `file.save` without + a `path` write the document's own file: the reply then has no `path`, and `files` and `linked` name the files + written beside it by their file names. A save without a path known (`file.saveAs` and `file.saveCopy` without + one, a document never saved) leaves out the suggested `folder`. `document.exportForScreens` into the `folder` + of its `exportPreset` leaves out the ZIP's `path` and lists `files` relative to that folder, and an error + for that export names the folder by its name alone. + `document.exportSettings`, `document.exportPresets.list` and `document.exportPresets.export` (as data and as + a file) leave out a kept `folder` outside the read roots. `file.package` + names the document's file and the linked files outside the read roots by their file names in `warnings`, in + `missingLinks` and in its report. `document.info` gives `link: null` for an image linked to a file outside them, + and its Linked Images rows and text report name that file alone. `action.batch` returns the replies of its steps as these commands give them. - `file.list {path}` (through `run_command`) lists a folder's files and folders, held to the read roots like any read, so an agent can see what it was given (#1163). - `file.recentFiles` and the control channel's `ui.menu.list` leave out the recent files outside the read roots. The other File › Open Recent Files rows keep their ids (`file.openRecent3` still opens the third file), and @@ -135,8 +147,37 @@ the suite) keep the agent to the folders you give it: roots shows as `loaded/<file name>` wherever `ui_inspect` and `ui.docking` name it: its id, its panel's id, the Color Guide's `ui.color_guide_limit` and a closed panel's key in `ui.docking_hidden`, also when its panel is closed. When another hidden library has the same file name, the libraries take `loaded/<file name>`, - `loaded/<file name> (2)`, `(3)` and so on in the order of their full ids, and each one keeps its id in both - replies. The other entries keep their order, and the app's own state is not changed. + `loaded/<file name> (2)`, `(3)` and so on in the order of their full ids (the libraries loaded in this session + first, then those only the UI state names), and each one keeps its id in both replies and in the library + commands below. The other entries keep their order, and the app's own state is not changed. +- `swatch.library.list`, `brush.libraries`, `symbol.libraries` and `graphicStyle.libraries` list every library + but leave out the paths outside the read roots: a library's `path` and the user library folder in `userFolder` + are `null` there. A library loaded from a file outside the roots is listed as `loaded/<file name>`, numbered + `(2)`, `(3)` and so on as in `ui_inspect` when two have the same file name. That id finds the library in the + other library commands (`swatch.library.get`, `swatch.library.add`, `brush.library`, `brush.addFromLibrary`, + `symbol.library`, `symbol.addFromLibrary`, `graphicStyle.library`, `graphicStyle.addFromLibrary` and the + others that take `library`), whose replies show it too. `swatch.library.copyToUser` refuses a library whose file + is outside the read roots without naming the file, and it and the library saves with `user: true` leave out + `path` when the user library folder is outside the read roots. +- `links.list`, `links.check`, `links.info` and the `missingLinks`, `modifiedLinks` and `updatedLinks` rows of + `document.open` leave out a linked file's path when the file is outside the read roots (a relative path is taken + from the document's folder): `path`, `found`, and in `links.info` also `link` and `location`, with the `fileSize` + and `modified` the document keeps of that file. Each row keeps its id, `name` (`fileName`), status and other + fields. This applies to every document, also one the person or a client with wider roots opened. The paths a + client gives `links.relink` and `links.unembed` stay in their replies, and the document's links are not changed. +- `image.info` gives `link: null` for a linked file outside the read roots, as `links.info` leaves it out; its id, + name, `linked` and the other fields stay. `links.findFiles` and `text.findFontFiles` replies, including later + `{}` and `{stop: true}` calls on a search another client started, leave out the files found outside the read + roots (with their `size` and `match`), a sought link's `path` outside them, and `folder` when the folder searched + is outside them; `error` then gives the reason without the path (for example `the folder can't be read`). The + rows keep their `name`, `ids`, family, style and status, and the counts stay. `text.addFontFiles` gives + `folder: null` when VectorCraft's Fonts folder is outside the read roots, and only the file name in `copied` and + `kept` `to` and in `skipped` `file` for a path outside them; the fonts are still copied. +- `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show a folder preference outside the read roots + (`fontsFolder`, `pluginsFolder`, `scratchPrimary`, `scratchSecondary`, `recoveryFolder`, `templatesFolder`) as + `null`; an empty folder and the scratch disk choices `Startup` and `None` stay. In `prefs.get {}` and + `prefs.reset`, an export preset in `screenExportPresets` leaves out its `folder` when the folder is outside the + read roots, and the preset stays. The preferences themselves are not changed. - Each flag may be given more than once (#3546): a path inside any of the read roots may be read, one inside any of the write roots written, so one session can read a project folder and a shared assets folder, or write to an output folder and a scratch folder, without widening a root to their common parent. A folder given twice @@ -430,7 +471,14 @@ or a new object (`css.export`, `object.isolate`, `layer.locate`, `layer.releaseT counterparts, `image.info`, `links.info`, `links.goTo`, `links.unembed`, `shaper.release`, `shaper.expand`, `transparency.editOpacityMask`, `transparency.viewOpacityMask`, `symbol.edit`, the `object.blend.spine.*` commands and `path.curvature`) refuse an `id` that is not a non-negative integer (`"abc"`, `"5"`, `true`) with an error and -change nothing; an omitted or null `id` keeps the default. A command that leaves out an object selected inside a +change nothing; an omitted or null `id` keeps the default. Commands that need an object id (`document.node`, the +`path.*` anchor and handle commands, `text.reshapePath`, `text.editRange`, the `object.mesh.*` point commands, +`layer.target`, `node.move`, `select.magicWand` and the others like them, and the `source`, `target`, `group` and +`path` keys of `appearance.transfer`, `appearance.copyFrom`, `layer.move`, the `livePaint.*` commands and +`text.createInPath`) refuse a value that is not a non-negative integer with "`id` must be a whole number", naming the +key, and report a key left out or null as missing. The optional `group` of `livePaint.fill` and `parent` of +`node.move` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when +`group` is left out or null, and reports a missing group only when both are left out. A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes `ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value that is not a list, and changes nothing; it does not act on the other entries. The error for an entry names the key, @@ -452,7 +500,7 @@ so a bad one draws nothing. The object and its styling are one `command.batch`, it can't read, a swatch the document lacks) fails the call and leaves the document as it was. The reply adds `name`, `opacity` and `effects` (each `effect.apply` result) when given; `paint` lists the stroke options applied. A gradient given to several objects fits each one's own bounds; `paint.setFill` / `paint.setStroke` with -`span: "selection"` place a linear or radial gradient once on the union of the targets' bounds instead, so one +`span: "selection"` place a linear, radial, conic or diamond gradient once on the union of the targets' bounds instead, so one ramp runs across them. `paint.setFill` without `item` on a grayscale or 1-bit image sets the color the image is drawn in: each pixel takes the color as far as the pixel is dark, and white pixels are transparent. `none` removes the color. An image with an @@ -470,7 +518,9 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr In the app's Color panel and Color Picker, RGB, HSB, hex and Web Safe RGB values describe the active working RGB space. RGB edits preserve the other native channels; HSB uses those same working RGB components. Colors outside display sRGB retain their native numeric values. `ui.colorPanel` selects the panel mode and `ui.colorPicker` -opens the picker through `run_command` with the remote backend. +opens the picker through `run_command` with the remote backend. `ui.colorPanel {"recentColors": false}` unchecks +the panel menu's Show Recent Colors, which hides the Color panel's Recent Colors row, and `true` shows it again; +applied colors still join the list while it is hidden. | Tool | Arguments | Notes | |---|---|---| @@ -482,7 +532,7 @@ opens the picker through `run_command` with the remote backend. | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | -| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. `line`: `x1,y1,x2,y2`. | +| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | @@ -490,13 +540,13 @@ opens the picker through `run_command` with the remote backend. | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | -| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for a top-level `compress`, `version`, `preview` or `precision` and for each key in `options` that the format doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | -| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF and WMF write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for a top-level `compress`, `version`, `preview` or `precision` and for each key in `options` that the format doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | +| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. With `copy`, the first step duplicates. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted `index` uses the current state. An `index` that names no state is an error and changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | @@ -874,8 +924,19 @@ export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. A page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2). A PDF 1.5 file with such a page is written as PDF 1.6, with a warning, and -keeps PDF 1.5's encryption (128-bit RC4). PDF/X files and PDF 1.3 and 1.4 files write such a page in points, and apps -that keep to the limit cut it to 200 in. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can +keeps PDF 1.5's encryption (128-bit RC4). A PDF/A-2b file at PDF 1.4 with such a page is written as PDF 1.6 too, with a +warning, whether or not `longPagesInPoints` is on, so that its page boundaries stay within PDF/A-2's limit of 14,400 units +unless the page is too narrow for that (below) +([veraPDF rule 6.1.13-11](https://github.com/veraPDF/veraPDF-validation-profiles/wiki/PDFA-Parts-2-and-3-rules#rule-6113-11); +PDF/A-2 files may declare PDF 1.0 to 1.7, [rule 6.1.2-1](https://github.com/veraPDF/veraPDF-validation-profiles/wiki/PDFA-Parts-2-and-3-rules#rule-612-1)). +PDF/X files and other PDF 1.3 and 1.4 files write such a page in points, and apps +that keep to the limit cut it to 200 in. `longPagesInPoints: true` (off by default; "Write pages longer than 200 in at +full size in points" in the Save PDF dialog's General section) writes such a page in points at every PDF version, without +a `UserUnit`, and a PDF 1.5 file stays PDF 1.5; the warning then says the page is written in points. The option applies +only to files without a standard: PDF/X files write such a page in points anyway, and PDF/A files keep the `UserUnit`, which +keeps their page boundaries within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13), a PDF/A file at PDF 1.4 +included (written as PDF 1.6). The dialog disables the +checkbox when a standard is chosen. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can be at most 32,767, and whole numbers are written as integers: a page longer than 32,767 pt whose sides aren't whole numbers of points fails the export with an error naming the page before the thumbnails are drawn and the transparency is flattened, and one whose art needs a real number past 32,767 fails with the same error when the file is written. A page whose short side is 3 pt or longer but would be under 3 units at that @@ -1046,20 +1107,64 @@ radial shadings: {"name":"run_command","arguments":{"command":"paint.setGradientGeom","params":{"aspect":60,"focal":[130,140]}}} ``` -Dither (the Gradient panel's box) draws a linear or radial gradient fill with fine noise that hides banding; -SVG and PDF exports write such a fill as an image at the Document Raster Effects resolution. It applies to fills -(`stroke: true` is refused): +A conic gradient (`kind: "conic"`, also accepted as `angle` or `conical`) sweeps its stops once around the center +(the start), clockwise on the page from the vector, with a seam where the last stop meets the first. Its annotator +draws the extent ellipse, aspect dot and center ring of a radial gradient, without a focal point; a `focal` given +for a conic gradient is an error. A negative `aspect` mirrors the sweep (counterclockwise), as reflecting the object +does; for the other kinds a negative `aspect` is an error. The Gradient panel's Aspect Ratio field and the aspect dot +keep a mirrored sweep mirrored. Dither and Method apply as they do to a linear gradient. PDF export writes it as a +function-based shading (type 1) whose calculator function turns the angle into the ramp, and PDF import reads a +function-based shading whose color turns around the origin of its space back as a conic gradient, with its stops' +opacity, also when the origin lies outside the painted area; in a PDF/A file, or with more than 97 stops on its +curve, it is written as an image. SVG has no conic gradient: one of opaque stops is written as 360 solid wedges +clipped to the shape, others as an image, and on type characters as a linear gradient. CSS (CSS Properties, a swatch +library saved as CSS) writes `conic-gradient(from …)`, an elliptical sweep as a circular one. EPS and legacy `.ai` +files get 360 solid wedges, and the `.ai` editing data a linear gradient along the vector with the same stops. +Object › Expand turns it into wedges (`steps`) or a mesh of columns around the center. An export that writes it in +another form gives a warning: + +```json +{"name":"run_command","arguments":{"command":"paint.setFill","params":{"gradient":{"kind":"conic","start":[150,150],"end":[200,150],"aspect":-100}}}} +``` + +A diamond gradient (`kind: "diamond"`) runs its stops from the center (the start) out to a square with a corner at +the end of the vector, a diamond on the page while the vector is level; `aspect` stretches the square across the +vector into a rhombus. Fitted to an object, it is centered on the object's box, and the edge of its square runs +through the box's farthest corner; at an angle of 0 or 90 degrees the edges run through all four corners. Its +annotator draws the square with the aspect dot and center ring of a radial gradient; a `focal` or a negative +`aspect` given for a diamond gradient is an error. Dither and Method apply as they do to a linear gradient, and the +canvas draws it as pixels, out to the miters, caps and arrowheads of a stroke. PDF, SVG, EPS and legacy `.ai` files +have no diamond gradient: one of opaque stops is written as four linear gradients, one for each quarter of the +square, clipped to the shape (PDF as axial shadings). In PDF and SVG, one with translucent stops, a dithered fill or +a square with no area is an image, and so is a Perceptual one, except in PDF when its stops are spot colors that the +Method paragraph below describes. SVG writes one on type characters as a radial gradient through the square's +corners. PDF import reads a function-based shading (type 1) whose color is the same along each square about the +origin of its space, with corners on its axes, as a diamond gradient. CSS writes a radial gradient through the +square's corners. A swatch library saved as CSS gets four `linear-gradient` layers, one for each quarter of the box, +which make a value for the `background` property but not for `background-image`; a swatch whose angle is not a +multiple of 90 degrees gets a circular `radial-gradient` instead, and, as for a radial swatch, the aspect is not +written. The `.ai` editing data holds a radial gradient through the corners with the same stops. Object › Expand +turns it into nested squares (`steps`) or a mesh of rings around the center. A document export that writes it in +another form gives a warning: + +```json +{"name":"run_command","arguments":{"command":"paint.setFill","params":{"gradient":{"kind":"diamond","start":[150,150],"end":[200,150],"aspect":60}}}} +``` + +Dither (the Gradient panel's box) draws a linear, radial, conic or diamond gradient fill with fine noise that hides +banding; SVG and PDF exports write such a fill as an image at the Document Raster Effects resolution. It applies to +fills (`stroke: true` is refused): ```json {"name":"run_command","arguments":{"command":"paint.editGradient","params":{"dither":true}}} ``` Method (the Gradient panel's menu): `classic` (the default) mixes the colours between stops in display RGB, -`perceptual` mixes a linear or radial gradient's colours in OKLab so the steps look even. SVG exports write a -Perceptual gradient as an image at the Document Raster Effects resolution (a dithered Perceptual fill with its noise). -PDF exports write it the same way, except for a linear or radial gradient with spot color stops whose other stops -are all paper white or written in CMYK or gray, that is not a dithered fill and whose curve does not have too many -stops. An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a +`perceptual` mixes a linear, radial, conic or diamond gradient's colors in OKLab so the steps look even. SVG exports +write a Perceptual gradient as an image at the Document Raster Effects resolution (a dithered Perceptual fill with +its noise). PDF exports write it the same way, except for a linear, radial, conic or diamond gradient with spot color +stops whose other stops are all paper white or written in CMYK or gray, that is not a dithered fill and whose curve +does not have too many stops (a diamond as four such shadings). An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading. `paint.setFill`/`paint.setStroke` take it in `gradient` too: @@ -1263,6 +1368,22 @@ fails with no change. A description with a `…` entry takes more keys than it l object can carry several formats' options). A command that takes its own reply back (`document.setup`, `text.areaOptions`) says so the same way. +The app's own commands are not checked against their descriptions, but those listed here refuse a value of the wrong +type and change nothing: `view.setZoom` (`zoom`, `center`), `view.screenMode` (`mode`), `window.panel` (`toggle`, +`toggleGroup`), `file.revert` (`confirmed`), `file.close` (`index`), `ui.newSwatch` (`spot`, `global`), +`ui.symbolOptions` (`edit`), `ui.batchDialog` (`set`, `action`) and `file.exportSelection` (`multiple`). So do the +control channel's `ui.key`, `ui.move`, `ui.wheel`, `ui.click`, `ui.drag`, `ui.pointer`, `ui.resize`, `ui.screenshot`, +`ui.render` and `ui.set` for their numbers, switches and `mods`, and the headless session's key, pointer and screenshot +calls. Omitting a param or giving null keeps its default, with two exceptions: `ui.click`'s `count` and `ui.drag`'s +`count` and `steps` refuse null, and a headless pointer event needs its `x` and `y`. A pointer event's `pressure`, +`holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers and its `space` must be `doc` or `screen`. A pointer packet +with one malformed event sends none of its events: + +```json +{"id": "view.setZoom", "params": {"zoom": "200"}} +→ `zoom` must be a number +``` + Saved actions aren't checked this way. When the Actions panel plays an action (Play at any speed, an action's function key, the Batch dialog or `ui.action.play`), a key a command no longer reads, recorded by an older version, is ignored and the action still plays. `Session::replay` plays a journal the same way. The command still refuses an effect @@ -1280,6 +1401,11 @@ doesn't take. Each of them refuses an unknown key inside an option object it tak → invalid parameters for `document.export`: unknown parameter `marks.useDocumentBleed`; `marks` takes: … ``` +Of the keys each one takes, `document.export`, `document.exportSelection`, `document.serialize` and +`document.exportForOffice` refuse a `path` or `format` that is not a string, a `selectedOnly`, `selectionOnly` or +`transparent` that is not true or false, and a `ppi` that is not a number, naming the key, and write nothing. Null is +the same as leaving the key out. + The save commands limit them the same way. `document.save`, `file.saveAs`, `file.saveCopy`, `file.saveAsTemplate`, `app.save` and `file.save` refuse a key that no save format takes, given beside the path or in `options`, and an unknown key inside a PDF option object or the `svg` object, also when the file is not SVG. A save still leaves out a key @@ -1351,6 +1477,20 @@ message, as in `` `steps` must be a number, not "8" ``, and change nothing: `ste `highlight` in `object.mesh.create`; and `opacity` in `object.mesh.setPointColor`. A null is read as a key left out. `object.mesh.create` refuses an `at` that is not two numbers with `` `at` must be [x, y] ``. +The graph commands refuse a value of the wrong type, naming the key, and leave the graph and the undo history as they +were. `graph.setType` refuses `` `columnWidth` must be a number, not "50" `` for `columnWidth` and `clusterWidth`; +`` `legend` must be true or false `` for `legend`, `markPoints`, `connectPoints`, `edgeToEdge`, `separateScales`, +`ticksBetweenLabels`, `firstRowInFront`, `firstColumnInFront`, `filledLines`, `dropShadow` and `legendAcrossTop`; +`` `type` must be a string `` for `type`, `valueAxis`, the three tick lengths, `prefix`, `suffix`, `rightPrefix`, +`rightSuffix`, `pieLegend`, `piePosition` and `pieSort`; and `` `ticks` must be a number, not "5" `` (or +`` `ticks` must be 0 or more `` for a negative number) for `ticks`, `rightTicks` and the three tick mark counts. +`axisMin`, `axisMax`, `rightAxisMin` and `rightAxisMax` take a number, or null to go back to the value calculated from +the data; any other value is refused with `` `axisMin` must be a number or null, not "10" ``. `graph.setData` and +`graph.create` refuse a `csv` that is not a string, `series` or `categories` that are not lists, and `rows` that are not +lists of numbers and nulls; `graph.setData` also refuses a `transpose` or `switchXY` that is not true or false, and +`graph.create` a `type` that is not a string or a `width` or `height` that is not a number. A null is read as a key +left out. + The transform, Align, Object Properties and Live Shape Properties commands refuse a string, a number or another value that is not true or false with `` `strokes` must be true or false ``, naming the key, and leave the document and its undo history as they were: the options `copy`, `strokes`, `corners`, `patterns`, `objects` and `typeAreas` in @@ -1387,8 +1527,8 @@ These commands refuse a string, a number or another value that is not true or fa `clockwise` in `shape.spiral`; `closed` in `shape.arc` and `path.create`; `vertical` and `placeholder` in `text.create` and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalMetrics`, `tateChuYoko`, `standardVerticalRoman` and `noBreak` in `text.setRangeStyle` and `text.setFormat`, which also checks `hyphenate`, `hyphenateCapitalized` and -`romanHangingPunctuation`; `effective` and `story` in `text.getRange`; `story` in `text.setRangeStyle`; `on` in `type.opticalMarginAlignment`, `type.systemLayout` -and `type.fractionalWidths`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in +`romanHangingPunctuation`; `effective` and `story` in `text.getRange`; `story` in `text.setRangeStyle`; `on` in `type.opticalMarginAlignment`, `type.dynamicText`, `type.systemLayout` +and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in `symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in `swatch.delete`; `fromArtwork`, `toGlobal` and `includeTints` in `swatch.newGroup`; `global` and `selection` in `swatch.addUsedColors`; `visible` in `appearance.setItem`; `copy` in `appearance.transfer`; `reverse` and `append` in @@ -1416,6 +1556,14 @@ and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gra `width` and `tolerance` in `livePaint.strokeEdge`. A null is read as a key left out. A gradient stop that names a swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. +The Edit, document, guide and slice commands also check the type of each param and change nothing when one is +wrong. A value that is not a number gets `` `dx` must be a number, not "10" ``: `dx` and `dy` in `edit.duplicate`, +`edit.paste`, `guide.move` and `object.slice.duplicate`. A value that is not true or false gets +`` `toggle` must be true or false ``: `summary` in `document.node`, `cancel` in `edit.undoGroup.end`, `vertical` in +`guide.add`, `toggle` in `guide.select` and `object.slice.select`, `copy` in `guide.move` and `delete` in +`select.editSaved`. `name` in `select.save` and `newName` in `select.editSaved` must be strings, and `index` in +`file.close` must be a non-negative integer. A null is read as a key left out. + `text.setStyle` refuses a `size` that is neither a number nor a length with a unit (`"12 pt"`, `"5 mm"`) with `` `size` must be a number, not true ``, and a `tracking` that is neither a number nor a number written as a string (`"20"`) with `` `tracking` must be a number, not false ``. It and `text.setRangeStyle` refuse a `font` or `style` that is not a string @@ -1486,9 +1634,9 @@ path to a value inside a list or an object, and the document and its undo histor An omitted value with a `default` takes it (`rotation` 0 in `view.saved.new`); the journal keeps the params as they were given. Saved steps played from a journal or an action keep a key the schema does not name, unless its value nests -more than 16 levels deep, and the values of the parameters it names are checked as in a new call. The schemas of built-in commands belong to API level 2 +more than 16 levels deep, and the values of the parameters it names are checked as in a new call. The schemas of built-in commands belong to API level 3 (`vectorcraft_engine::schemas::API_VERSION`); a change to any of them raises the level. Level 2 added -`engine.apiReference`. Commands that plug-ins add have no schema here. +`engine.apiReference`; level 3 says that `rotation` in `view.saved.new` and `view.saved.list` turns clockwise. Commands that plug-ins add have no schema here. `engine.apiReference {}` → `{markdown}` returns the command API reference, written from these schemas each time it runs; no file of it is kept. It needs no open document and changes nothing. The reference has a `##` section for each @@ -1516,10 +1664,10 @@ top-level `import` or `export`, such as a React `.jsx` file), `notText` (a NUL b control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, the reply holds these lists: - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects - and directives, such as `$`, `alert`, `UnitValue` and `#target`), `dom` (the reference app's document model), - `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: palettes, - `#targetengine`, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, - reflection, actions and `selectTool`). + and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's + document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: + palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions + and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and `locale`. A directive is read where it starts a line, written `#name` or `//@name`. @@ -1527,9 +1675,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, `menuCommand` or `e4x`), each with a count and its lines. - `dom.members` lists the document-model member chains as the script writes them (`app.activeDocument.layers[].name`, with `[]` for an index and `()` for a call); a variable assigned from a chain - is replaced by that chain, and a name written with `\u` escapes is read as the name it spells. `dom.types` lists - the type names the script compares with `.typename` or creates with `new`, apart from the language's, the platform's - and the script's own functions. + is replaced by that chain, and a name written with `\uXXXX` or `\u{…}` escapes is read as the name it spells. + `dom.types` lists the type names the script compares with `.typename` or creates with `new`, apart from the + language's, the platform's and the script's own functions. - `menuCommands.strings` lists the string literals the script passes to `executeMenuCommand` (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. @@ -1541,7 +1689,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper than the check follows: more than 4,096 open brackets, or XML literals and the code in their braces nested more - than 4,096 levels deep). + than 4,096 levels deep). Newer syntax includes a private name (`#name`, given with its escapes read, unless the + name they spell would make the line a directive) and a `\u{…}` escape in a name (given as written). A `#` and a + name at the start of a line is a private name, not a directive, when the name starts with an escape, or when the + line is inside braces and the name is not a directive's. Each entry of `targets`, `directives`, `includes` and `problems` has the `line` it is on (a problem with the whole text has none) and, when it is in an included file, that file's path as `file`. `features`, `menuCommands.strings` @@ -1601,10 +1752,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a missing file and a refused path throw errors the script can catch. - `$.fileName` is the file being run, which is the file `$.evalFile` is running while it runs, and is empty for a - script given as `source`. `$.includePath` is the current `#includepath` list, separated by `;`. + script given as `source`. `$.includePath` is the current `#includepath` list, separated by `;`. `$.engineName` is + the name `#targetengine` gave the engine the script runs in (`VectorCraft` without the line) and is read-only. - `alert(message[, title, errorIcon])`, `confirm(message[, noAsDflt, title])` and `prompt(message, preset[, title])` open a dialog, described below. `vc.api.has("dialogs")` is true. -- `vc.args` is the `args` object. +- `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. Before any of the script runs, its preprocessor lines are read. The help page @@ -1634,8 +1786,12 @@ VectorCraft reads them by these rules of its own: and `Function` compile takes the checks of the code that compiles it. A file `$.evalFile` runs takes the checks of its own last `#strict` line, for its code and the functions it defines, or the caller's when it has none; the caller's code keeps its own. Any value other than `on` or `off` ends the run with `#strict takes on or off`. -- `#targetengine` and `#engine` end the run with an unsupported-directive error, and any other `#name` with an - unknown-directive error. A `//@` line with another name is a comment. +- `#targetengine name` and `//@targetengine name` run the script in the named engine. The help page above describes + the line: the engine it names lasts for the application session, and a later script that names it sees the globals + and functions earlier ones left. A script without the line, and `#targetengine main`, get a new engine for each + run, as before. The rest are VectorCraft's own rules, described under Script engines below. +- `#engine` ends the run with an unsupported-directive error, and any other `#name` with an unknown-directive error. + A `//@` line with another name is a comment. - A script run from a file reads its included files and the files `$.evalFile` runs only in that file's folder and the folders below it. A path with a `..` name, a path that leads out of the folder through a link or a junction, a Windows device name or stream, and a computer on the network are refused, and so is every path for a script given as @@ -1671,7 +1827,7 @@ VectorCraft's own, and `vc.api.has("dollar")` is true where they are available: | `localize` | `false`; while `true`, `String(object)` of a localization object gives its text for `$.locale` | | `os` | `Windows`, `macOS`, `Linux`, `FreeBSD`, `Unix` or `Web`, without a version | | `screens` | an empty array | -| `sleep(ms)` | waits from 0 to 1,000 milliseconds between two frames of the app, without stopping it from drawing; `script.stop` ends the wait; it does not wait on the web; called with more than 0 inside a getter, a conversion, a callback of a built-in function or a file `$.evalFile` runs, it throws an `Error` instead of waiting | +| `sleep(ms)` | waits from 0 to 1,000 milliseconds between two frames of the app, without stopping it from drawing; `script.stop` ends the wait, and so does `notifications/cancelled` for a run its `tools/call` waits for, without waiting for the time to pass; it does not wait on the web; called with more than 0 inside a getter, a conversion, a callback of a built-in function or a file `$.evalFile` runs, it throws an `Error` instead of waiting | | `strict` | `false` | Members that are values (`build`, `level`, `os` and the like) cannot be changed. A wrong value for a member that can @@ -1688,7 +1844,9 @@ as it is. A string as the first argument is used as the text. objects as the text of an expression that makes the same value, such as `({"a":[1, "x"]})`. A function, a getter, a date, a regular expression, an error, a host object such as `vc`, an array with properties besides its elements, an object whose prototype is not `Object.prototype`, a property that is not enumerable, or an object that contains -itself throws a `TypeError`. A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 +itself throws a `TypeError`. So does a property that is not writable or not configurable, an object or array after +`Object.preventExtensions`, `Object.seal` or `Object.freeze`, and an array whose `length` is read-only, since the text +would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A @@ -1713,6 +1871,45 @@ change anything outside the documents: `script.*` except `script.check`, `plugin an error. With Data Recovery off for complex documents, a run in the web build does not start while a complex document has unsaved changes. +### Script engines + +A named engine (`#targetengine`) keeps its globals and functions between the runs that name it, until it is dropped +or the session ends. Engines stay on the thread that made them: a session used on another thread starts there with +no engines, and the engines it left are dropped when their own thread next uses engines. These are VectorCraft's own rules: + +- The name is either a name of ASCII letters, digits and `_` that does not start with a digit, or a name in single or + double quotes of 1 to 64 bytes of UTF-8 without control characters. Names are matched as written: `Session` and + `session` are two engines. `main` is the engine of a script without the line, which is new for each run. +- Only the script itself has the line, once, before its code and its `#include` lines; blanks, comments and the other + preprocessor lines may come before it. A second line, a late line, a bad name, or the line in an included file ends + the run at that line before any of it runs, and makes no engine. In a file `$.evalFile` runs, the line makes that + call throw a `SyntaxError` when the call runs. +- A session keeps at most 8 named engines. A run that names a ninth ends with a limit error before any of it runs, + and the other eight are kept. Each named engine has a heap of 64 MiB, which holds what it keeps between runs; a run + that goes past it ends with the heap limit, and the engine stays usable. +- The documents go back after an uncaught error, a limit or `script.stop` as they do for any run, and the engine keeps + the globals the run set before it ended. An internal error drops the engine. +- An error in code an earlier run compiled, such as a function it defined, is reported at that code's line and column + in the earlier run's script, a file it included or a file its `$.evalFile` ran, and the report's `file` names that + file. For an earlier script given as `source`, `file` is that run's name. The report's `name` and the console line's + name stay the calling run's, as in `caller.js: /path/lib.jsx:12:5: Error: kept`. Each engine keeps these places + for 8 MiB of source maps, the oldest going first; an error in code whose place is gone, or in code that `eval` or + `Function` compiled, is reported without a line and column, and the code still runs. +- `vc`, `$`, `alert`, `confirm` and `prompt` act for the run that calls them, including a copy an earlier run kept in a + global. `vc.args` is the calling run's `args`, through a `vc` object an earlier run kept too. An engine + holds no document: `vc.document` is a copy, read when it is called. What a run sets on `$` (`$.locale`, + `$.localize`, `$.flags`, `$.setenv` values and `$.hiresTimer`) lasts for that run only, as in a run without the line. +- `File` and `Folder` objects read in the folders of the run that calls them, including objects an earlier run kept in + a global. `Folder.current` starts at the script's folder in each run, and a file an earlier run left open is not open + in a later one. +- `script.engines {}` lists the named engines in the order they were made: `{engines: [{name, heapBytes, running}], + limit: 8, heapLimit: 67108864}`, where `heapBytes` is the engine's heap after its last run. +- `script.engine.drop {name}` drops a named engine and its globals, and returns `{dropped: true, name}`. The next run + that names it gets a new engine. `main`, a name with no engine, and the engine of the running script are refused; + the last one ends with the busy error. +- A script cannot run `script.engines` or `script.engine.drop`. +- The web build has no named engines: a run that names one other than `main` ends with an error before any of it runs. + VectorCraft sets these limits itself: | Limit | Value | @@ -1721,7 +1918,7 @@ VectorCraft sets these limits itself: | Included and evaluated files | 64 in all, 16 levels deep, 1,024 paths looked up | | Heap | 256 MiB (128 MiB on the web) | | Host calls | 2,000,000 | -| `maxFuel`, instructions in all | 1 to 100,000,000,000; 1,000,000,000 by default | +| `maxFuel`, instructions in all, plus one for each UTF-16 code unit of source that `eval`, `Function` or an evaluated file compiles during the run | 1 to 100,000,000,000; 1,000,000,000 by default | | Instructions without a pause | 200,000,000 | | Nesting depth | 64 levels | | A value crossing to or from a command | 16 MiB and 1,048,576 entries | @@ -1731,6 +1928,8 @@ VectorCraft sets these limits itself: | A dialog's message, title and prompt preset | 16 KiB, 256 bytes and 16 KiB | | `answers` | 10,000 answers and 1 MiB as JSON | | `dialogs` in the report | 10,000 dialogs and 1 MiB as JSON | +| Files `File.open` reads | 8 MiB a file, 32 MiB in a run, 256 open at once | +| `Folder.getFiles` | 2,048 entries, 65,536 names looked at | | Growth before a person is asked | 100,000 objects and 512 MiB of new document data | In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and @@ -1743,7 +1942,9 @@ another file than the script) and `fuelLeft`. - `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are left out. `timingAvailable` is false on the web, where `runTimeMs` is 0. -- `hostCallCounts` is `{vcRun, documentReads, commandListReads, vcLog, consoleWrites}`. +- `hostCallCounts` is `{vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}`. + `fileCalls` counts the calls `File` and `Folder` make to the app, and `fileExecutes` the `execute` calls, which open + nothing. - `slowestCommands` lists at most 5 commands as `{id, calls, totalMs, maxMs}`, the longest in all first, then by id. - `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as text. @@ -1802,10 +2003,63 @@ empty object are the same. vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` +The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and +https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A +script reads files with them: + +- `new File(path)` and `new Folder(path)` name a path without looking it up. A path is a platform path or a URI + path: a relative path is taken from `Folder.current`, which starts at the script's folder, `~` is the home folder, + `%xx` escapes are read as UTF-8, and on Windows `/` and `\` both separate names and `/c/` names drive C. `File(path)` + without `new` gives a `Folder` for an existing folder, and `Folder(path)` gives a `File` for an existing file. Two + objects for the same path are different objects. +- `name`, `displayName`, `fsName`, `absoluteURI`, `fullName`, `relativeURI`, `path`, `parent` and `toString()` come + from the path. `exists`, `length`, `created`, `modified`, `hidden`, `readonly` and `alias` read the file system. + `exists` is true for a `File` only when the path names something other than a folder, and for a `Folder` only + when it names a folder. + `File.encode`, `File.decode` and `File.isEncodingAvailable` (and the same on `Folder`), `File.fs`, and the folders + `Folder.temp`, `Folder.desktop`, `Folder.myDocuments`, `Folder.userData` and the others are there too. +- `open('r')` opens a file to read, and `read([chars])`, `readln()`, `readch()`, `seek(pos[, mode])`, `tell()`, `eof` + and `close()` read it. `read`, `readln` and `readch` count characters, and `seek` and `tell` count bytes. `readln` + and `readch` take CR, LF, CRLF and LF CR as one line end. `folder.getFiles([mask])` lists a folder, sorted by name; + the mask matches `*` and `?` without regard to case, and a function as the mask keeps the entries it returns true + for. +- A method that fails returns `false`, `null` or an empty string and sets `error`, such as `Script file access + denied`, `Script file does not exist` or `Script file is not open`. A count or a position that is not a finite + number, or a negative count, throws a `RangeError`. + +VectorCraft reads files by these rules of its own: + +- A script run from a file reads only in that file's folder and the folders below it, as its includes are read, and + a script given as `source` reads no files. When automation read roots are set, as for a run over MCP or the command + line, the files must also be inside them. A path outside, a Windows network path (`\\host\share`) and a device path + (`\\?\`, `\\.\`) are refused before anything is looked up: `exists` is `false`, the dates and `getFiles` give `null`, + and `error` is `Script file access denied`. A path that leads out through a link or a junction is refused too, and + `getFiles` leaves such an entry out. A missing file is refused the same way unless the nearest folder above it that + exists is inside the script's folder. It is also refused when a link above it leads to a folder that does not exist. +- `open` reads the whole file. A file larger than 8 MiB is refused from its size before any of it is read, with + `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A run has at most 256 + files open at once; another `open` returns `false` with `Script has 256 files open` until one is closed. +- The encoding is the one the file's byte order mark gives (UTF-8, UTF-16LE or UTF-16BE), otherwise the `encoding` + the script set before `open`, otherwise UTF-8 when the bytes are valid UTF-8, otherwise CP1252. `BINARY` reads each + byte as one character. A byte the encoding cannot read, such as one above 127 in `ASCII`, fails the read with + `Script file cannot be decoded` and leaves the position where it was. +- `getFiles` gives at most 2,048 entries and looks at most 65,536 names; past that it gives `null` with `Script folder + has more than 2,048 entries`. A mask that takes more than 16,777,216 steps to match against the names of one + folder gives `null` with `Script folder mask takes too many steps to match`. +- A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a + `File` or `Folder` is made from it. +- Writing is not available yet: `open('w')`, `open('e')`, `open('a')`, `write`, `writeln`, `copy`, `remove`, + `rename`, `create` and `createAlias` return `false` with `Script file writing is not available`, and setting + `length`, `hidden` or `readonly` sets `error` to that message and changes nothing. The file + and folder dialogs return `null`, and `execute` opens nothing and returns `false`. In the web build every lookup + fails with `Script file access is unavailable on the web`. + Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and `$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another file), its end, and a report of -its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds, +its time, host calls and slowest commands. An uncaught error that a `finally` block passes on unchanged has the line +and column where it was thrown; an error the `finally` block throws has the line and column of that throw. Each line +shows the run's number and the script's name. Line feeds, carriage returns and the two together break lines, and other control characters show as their Unicode Control Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. When the console has dropped or cut any lines, a note at the top counts them. The panel lays out only the @@ -1842,9 +2096,10 @@ way. The listed scripts come first in the menu, above Check Script… and Other The rest of this section is VectorCraft's own rules: -- The folder is read when the app starts, each time its window becomes the active one, and, where the menus are in - the window (Windows, Linux and BSD), each time the File menu opens. A script added while VectorCraft runs is listed - after the next of these. A read takes names only, never a script's text, and runs off the UI thread, one read at a +- The folder is read when the app starts, each time its window becomes the active one, each time the File menu opens + where the menus are in the window (Windows, Linux and BSD), and each time a menu of the macOS menu bar opens. A + script added while VectorCraft runs is listed after the next of these; in the macOS menu bar it shows the next time + the menu opens. A read takes names only, never a script's text, and runs off the UI thread, one read at a time. - Each level is sorted by label without regard to case, with scripts and subfolders mixed. A script whose label another row of its folder has (`Tidy.js` beside `Tidy.jsx`, or beside a subfolder `Tidy`) shows its whole file name. @@ -2057,6 +2312,11 @@ the isolated group or layer, or a group or layer it is in, is hidden, locked or everything in it, and `select.all`, `select.allOnArtboard` and `select.inverse` select nothing. `select.object.bristleBrushStrokes` selects the objects whose topmost stroke has a bristle brush (type `bristle` in `brush.list`), whatever the brush is named; a brush of another type with "Bristle" in its name does not count. +`select.object.notAlignedToPixelGrid` (Select › Object › Not Aligned to Pixel Grid) selects the paths and compound +paths whose pixel-aligned property (`object.setPixelAligned`) is off and returns `{count}`. It goes by the property, +not by where the anchors are: a path on whole points with the property off is selected. Guide paths, type, images, +groups and other objects are not, nor are the paths inside a compound path, which takes the property as one object. +It looks into groups, replaces the selection, and with no such object clears it; it records no undo step. `select.nextAbove` and `select.nextBelow` select the nearest such object above or below the first selected object among the objects beside it in its group or layer, passing over hidden and locked objects and sublayers. When there is no such object, the selection stays as it is. @@ -2171,7 +2431,7 @@ repeated names, and ids the document doesn't have are dropped. View → New View… keeps a view under a name, in the document: `view.saved.new {name?, center: [x, y], zoom, rotation?}` (the desktop app fills in its current view; default the first free "View N"; at most 25 per document, -names up to 255 characters, each name once) → `{name, index}`, one undo step. `view.saved.list` → +names up to 255 characters, each name once; `rotation` is in degrees clockwise on screen, as `view.rotate` turns the view) → `{name, index}`, one undo step. `view.saved.list` → `{views: [{name, center, zoom, rotation}…]}` in menu order. Edit Views… renames and deletes: `view.saved.edit {name, newName?, delete?}`, or several at once as `{edits: [{name, newName?, delete?}…]}` in one undo step (→ `{views}`), where every `name` is the name before the edit and the names must stay unique; it is @@ -2210,9 +2470,33 @@ kept with the workspace, and built-in workspaces and workspaces saved without it {"name":"invoke_menu","arguments":{"command":"window.toolsBesideCanvas","params":{"on":true}}} ``` +## Learn panel + +Window › Learn and the Explore tutorials button beside the search icon at the right end of the app bar show and hide +the Learn panel. Its For you tab holds a Get started section with a Quick skill guide card; choosing the card opens +the Skills tab. The Skills tab lists VectorCraft's own skills, each with its number of tutorials and an empty progress +ring. Choosing a skill lists its tutorials, choosing a tutorial shows its numbered steps, and Back goes up one level. +The tutorial text is English. `window.learn {show?}` shows the panel (`show: true`), hides it (`show: false`) or +toggles it (`show` omitted or null), and answers whether it shows; Window › Learn and Explore tutorials run it. +The panel counts as hidden while the dock is hidden or a full screen mode hides the panels. Showing it shows a hidden +dock; in a full screen mode it makes Learn the front panel, which shows when the mode ends, and answers false. Any +other value of `show` is an error and changes nothing. `learn.list {}` → `{skills: [{id, title, tutorials: [{id, title, steps}]}]}`, in the order the Skills tab +lists them, where `steps` is the number of steps. `learn.show {tutorial}` shows the panel on its Skills tab with that +tutorial's steps → `{skill, tutorial, title, steps: [text]}`. A missing, non-string or unknown `tutorial` is an error +and changes nothing. Behavior reference: +[Quick skill guide](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html). + +```json +{"name":"invoke_menu","arguments":{"command":"learn.show","params":{"tutorial":"pen-paths"}}} +``` + ## Ruler guides -Ruler guides are numbered in the order they were made. `guide.add {vertical, pos, artboard?}` makes one (the x of a +Each ruler guide is an object of a layer or sublayer, directly in it and above its art, and takes an id from the +document's object ids. Ruler guides are numbered by id, which is the order they were made (a guide read from an `.ai` +file takes its place in the file). An object command given a ruler guide's id (in `ids` or `id`) fails with an error, +and `node.move` cannot put a ruler guide into a group or out of its layers; the guide commands below take guides by +number. `guide.add {vertical, pos, artboard?}` makes one (the x of a vertical guide, the y of a horizontal one, in points) → `{index}`. With `artboard` (an artboard's index) it is an artboard guide: it runs across that artboard only, moves with it (`artboard.move`, a pure move in `artboard.setProps`, `artboard.rearrange`), scales with it (`artboard.setProps {scaleArt}`), is copied with it (`artboard.duplicate`, `artboard.move {copy}`) and is @@ -2236,8 +2520,8 @@ with guides unlocked, as the preference is off until `prefs.set` turns it on. `view.guides.release {index?, ids?}` (View › Guides › Release Guides) turns guides into paths → `{count}`. With `index` it releases that ruler guide, and with `ids` it releases those guide paths (and the guide paths inside them). Otherwise it releases the selected guide paths and ruler guides, and with no guide selected it releases every guide -path. A released ruler guide becomes a straight path with no fill or stroke, at the top of the guide's layer (or where -new art goes, for a guide on no layer). An artboard guide becomes a line across its artboard, and a canvas guide +path. A released ruler guide becomes a straight path with no fill or stroke, at the top of the art of the guide's +layer. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the bounds of all the artboards. `index` and `ids` are refused while guides are locked. The release is one undo step, and the released paths are selected. With the Selection, Direct Selection or Group Selection tool, a double-click with Cmd/Ctrl and Shift held releases the ruler guide or guide path under the pointer @@ -2346,8 +2630,9 @@ already walks Image Trace. Short agent entry points: locked or sits in a hidden or locked group or layer. Choosing another selection tool selects the instance whole again. `symbol.instance.reset {ids?}` drops the selected instances' changes (the Properties panel's Reset). Redefining the symbol (`symbol.update`) reshapes every instance and keeps each change whose path the - new art still has; `symbol.breakLink` bakes the changes into the expanded art; `symbol.edit` edits the symbol's own - art, and each edit there keeps the changes whose path the art still has; making the symbol static drops them, and + new art still has, less a fill or stroke the object now at that path does not draw (a change left empty is dropped); + `symbol.breakLink` bakes the changes into the expanded art; `symbol.edit` edits the symbol's own art, and each edit + there keeps the changes the same way; making the symbol static drops them, and so does `symbol.replace` with a different symbol (a replace with the instance's own symbol keeps them). ```json @@ -2358,6 +2643,12 @@ already walks Image Trace. Short agent entry points: Instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and the art of the document's brushes count, and so do the instances in the art of a symbol that is used; a symbol placed only inside an unused symbol is unused too. +- The Symbols panel menu's Sort by Name: `symbol.sortByName` (`{}`) puts the document's symbols in name order, + ignoring case, as one undo step; symbols whose names differ only in case keep their order. `symbol.list` and the + panel list the symbols in the new order, the current symbol stays current, and instances are + unchanged. No undo step is added when the symbols are already in order. The panel menu's Thumbnail View, Small List + View and Large List View change only how the panel shows the symbols: thumbnails, or rows with a thumbnail and the + name (smaller rows in Small List View). - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the @@ -2565,8 +2856,26 @@ already walks Image Trace. Short agent entry points: false) offers Continue in the message box. An action with an empty message still waits at the stop, which is VectorCraft's own rule. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an - object, or no action and no recording is an error, and then nothing changes. The panel menu's Insert Stop… opens the `actionStopRecord` dialog + object, no action and no recording, or a stop that would give the action more than 10,000 steps or its set's file + more than 8 MiB is an error, and then nothing changes. The limits count the steps that the recording in progress + adds to the set. The panel menu's Insert Stop… opens the `actionStopRecord` dialog (`message`, `allowContinue`, `set`, `action`, `step`), whose OK runs this. +- Actions: `ui.action.insertMenuItem {set?, action?, step?, command, params?}` inserts a menu item's command as a step + without running it. `command` and `params` (default: `{}`) must be those of an item in the menus that can be a step: + an item that runs a document command without opening a dialog first, outside the File, Window and Help menus, and + not Undo, Redo, a Paste command, Object › Align (its items add the Align To choice when clicked), Object › Image + Trace › Make or Make and Expand (the menu traces off the UI thread, with progress and Cancel), Object › Pattern › + Make or Edit Pattern (the menu also opens the Pattern Options panel), a preference + toggle, an Actions command or a recent-font, saved-selection or saved-view slot. Disabled items are listed, and playback checks the step when it runs. With `set` and `action`, the + step goes into that action, after step `step`, else after its last step, becomes the panel's selected step, and the + command returns `{set, action, step}`. Without them it goes into the recording in progress and returns + `{recording: true}`. A command no such item runs, params that are not an object, an index past the last set, action + or step, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file + more than 8 MiB is an error, and then nothing changes. The limits count the steps that the recording in progress + adds to the set. The panel menu's Insert Menu Item… opens the + `actionInsertMenuItem` dialog (`find`, `command`, `params`, `set`, `action`, `step`): typing in Find and pressing + Find picks the one item whose menu path, shown name or command id holds every word typed, or lists the matches, and + OK runs this. - Actions: `ui.action.continue {}` plays on from the stop the playing action waits at, on the document active now, and closes the stop's message box (`actionStopMessage`). The next step runs at once, or at Accelerated the steps up to the next stop as one undo step. It returns `{results, pending, atStop?}`. With no action waiting at a stop it is an @@ -2687,6 +2996,30 @@ Brushes panel's New Brush button, its menu's New Brush… and art dropped on the Brush Options for the new brush; for a scatter, art or pattern brush they preview the art from `brush.selectionArt`. Their OK runs `brush.new {type, name, params, ids?}`, and Cancel adds no brush. +`brush.placeArt {name, x?, y?}` places a copy of the art a scatter, art or pattern brush is made of, centered on +(`x`, `y`) (default: the center of the first artboard), and selects it, in one undo step. The app runs it when a +brush is dragged from the Brushes panel onto an empty part of the canvas; dropped on a path, a brush is applied to it +(`brush.apply`). A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner +corner, start, end (only the tiles it has art for), each in a group named Side Tile, Outer Corner Tile, Inner Corner +Tile, Start Tile or End Tile. A tile with a repeat frame has an unpainted rectangle at the back of its group that marks +the frame. A symbol instance in the art is measured by its symbol's art. A calligraphic or bristle brush is refused +with "`<name>` has no art (only scatter, art and pattern brushes do)". + +`brush.replaceArt {name, ids?|id?, applyToStrokes?}` makes the selected art the brush's art and keeps its other +options; several objects become one group, as in `brush.new`. A pattern brush takes a group named for a tile, or a +group of such groups, tile by tile: an unpainted rectangle at the back of a tile group becomes that tile's repeat frame, +a tile group's art goes back without that group, and the tiles that are not given stay as they are. Of two groups named +for the same tile, the frontmost one counts. Other art becomes the side tile. When strokes use the brush and +`applyToStrokes` is `false`, the brush and its strokes stay as they were, and a copy of the brush with the new art, +named "`<name>` copy", goes after it and becomes the current brush. Otherwise, and for a brush no stroke uses, the brush +changes and its strokes redraw. It replies `{name}`, the brush that has the new art, and refuses a calligraphic or +bristle brush, an empty selection and art (or a tile it is given, such as a tile group left with only its frame's +rectangle) with no width. `brush.replaceArt` and `brush.new` measure a symbol instance in the art by its symbol's art. +In the app, art Alt-dragged (Option-dragged on macOS) from the canvas onto a scatter, art or pattern brush in the +Brushes panel runs it. When strokes use the brush, the app checks the art first and shows why in the status bar when +the brush cannot take it; otherwise a dialog (`brushReplaceArt`) asks: Apply to Strokes, Leave Strokes +(`applyToStrokes: false`) or Cancel. + `variable.bind`, `variable.unbind`, `variable.delete`, `dataset.set`, `dataset.update`, `dataset.delete`, `dataset.select`, `dataset.next` and `dataset.prev` add no undo step when they leave the document as it was, such as binding art to a variable it already has or applying the active data set again: the steps to redo stay, and a saved @@ -2846,8 +3179,8 @@ See [Revolve](revolve.md) for the scope and limitations. replaces the lighting rig and ambient of an existing Revolve, Extrude & Bevel, Inflate or Rotate effect. `item: null` addresses object-level effects; an item index addresses a fill/stroke's effects. All targets must have a 3D effect at `index`, otherwise nothing changes. Extrude & Bevel -(Classic) has no lighting presets: a target with it at `index` is an error, nothing changes, and -`effect.setParams` sets its lights. The operation is one undo step and preserves Shading, geometry, source paint and the view. +(Classic), Revolve (Classic) and Rotate (Classic) have no lighting presets: a target with any of them at `index` is an +error, nothing changes, and `effect.setParams` sets its lights. The operation is one undo step and preserves Shading, geometry, source paint and the view. The four original rigs use one white front light at 80% intensity. Standard keeps the existing default; Diffuse uses 100% Softness and 35% Ambient Light, Top Left uses Rotation 135 and Height @@ -2859,6 +3192,32 @@ The document stores their numeric settings; manual edits remain possible through {"name":"run_command","arguments":{"command":"effect.lightingPreset","params":{"index":0,"item":null,"preset":"topLeft"}}} ``` +## 3D shadows + +Revolve, Extrude & Bevel, Inflate and Rotate take `shadow` (boolean, default false), `shadowPosition` (`"behind"` +or `"below"`, default `"behind"`), `shadowDistance` (0..100%, default 0) and `shadowBounds` (10..400%, default 100), +set with `effect.apply` or `effect.setParams` in one undo step. With `shadow` on, the first light casts a +hard-edged shadow of the solid, drawn behind the solid as one path filled black at 50% opacity times the opacity +of the art that casts it, in that art's blending mode. `"behind"` puts it +on a plane square to the view behind the object; `"below"` puts it on the floor under the object, square to the +object's own vertical axis and turned with it, so with no X rotation the floor is seen edge-on and draws nothing. +`shadowDistance` moves the plane away from the object by that share of the object's largest size. `shadowBounds` +limits the plane to a square about the foot of the object's center, four times the object's largest size across +at 100%. No shadow is drawn when `shade` is false, when the first light's intensity is 0, or when it does not +reach the plane (a light behind the object for a shadow behind it); a fill, stroke or group member at 0% opacity +casts none. Values out of range, another `shadowPosition` and a `shadow` that is not a boolean are refused before +the document changes. A shadow is cast from at most 327,680 faces, the solids of one object together (VectorCraft's +own limit); past that, a command is refused with "The 3D shadow is too complex; turn Shadows off or simplify the +art", and a loaded file draws the source path, as it does for a solid past its limits. The color, the opacity and how Distance and Bounds scale are VectorCraft's own; the public +documentation names the controls and their ranges +([3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html)). +The settings are saved in the native file; SVG and PDF exports draw the shadow, and `effect.expandAppearance` keeps +it as a path. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows). + +```json +{"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"shadow":true,"shadowPosition":"below","shadowDistance":10,"shadowBounds":150}}}} +``` + ## 3D object type `effect.setParams {index: int, threeDType: "plane" | "extrude" | "revolve" | "inflate", params?, item?, ids?, aligned?}` @@ -2929,6 +3288,51 @@ an unknown surface or shading color is refused with an error and the document is {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.classicExtrude","item":null,"params":{"depth":40,"bevel":"rounded","bevelHeight":6,"surface":"diffuse","blendSteps":64}}}} ``` +## Revolve (Classic) + +`effect.apply {effect: "threeD.classicRevolve", params: {...}, ids?, item?}` is Effect › 3D and Materials › +3D (Classic) › Revolve (Classic)…. It sweeps the profile round a vertical axis as `threeD.revolve` does, at 64 segments +for a full turn, and draws every face, back to front, with the classic surfaces. Parameters: `angle` (degrees, +0..360, default 360), `cap` (true closes the profile's open ends, false leaves the surface hollow), `offset` (points, +0..1000, default 0; the axis's distance from the profile, so a value above 0 makes a ring), `edge` (`left`, the +default, or `right`: the edge of the profile's bounds the axis is at), `rotationX/Y/Z` and `perspectiveAngle` as +above, and `surface`, the lights, `ambient`, `highlightIntensity`, `highlightSize`, `blendSteps`, `shadingColor` and +`shadingCustom` as Extrude & Bevel (Classic) takes them. It has no `drawHiddenFaces`. The effect also goes on a group +or layer, whose members turn about one shared axis, or on a fill or stroke. The public documentation describes the +dialog ([Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)) +and its Angle (0 to 360), Cap, Offset (0 to 1000) and Left Edge or Right Edge settings +([Revolve options](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=283)); +the defaults are VectorCraft's own. An unknown parameter (`segments` included), a number out of range, a flag that +is not true or false, another `edge`, surface or shading color is refused with an error and the document is not +changed. + +```json +{"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.classicRevolve","item":null,"params":{"angle":270,"offset":10,"surface":"diffuse","blendSteps":64}}}} +``` + +## Rotate (Classic) + +`effect.apply {effect: "threeD.classicRotate", params: {...}, ids?, item?}` is Effect › 3D and Materials › +3D (Classic) › Rotate (Classic)…. It turns every fill and stroke as one flat plane about the center of the object's +bounds, as `threeD.rotate` does, each in its own paint, and draws the plane from either side. Parameters: +`rotationX/Y/Z` and `perspectiveAngle` as above; `surface` (`diffuse`, the default, lights the art softly, and +`none` keeps the paint unlit); and the lights, `ambient`, `blendSteps`, `shadingColor` and `shadingCustom` as Extrude & +Bevel (Classic) takes them. It has no highlight, no `drawHiddenFaces` and no shadow. The effect also goes on a group +or layer, whose members turn about one shared center, or on a fill or stroke. The public documentation describes the +dialog's Position and Surface settings +([Rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)), +the Position presets, rotations from -180 to 180 and Perspective from 0 to 160 +([Set 3D rotation position options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=270)), +and No Shading and Diffuse Shading as the only surfaces for an object that uses only this effect +([Surface shading options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=271)). +The defaults and the shading are VectorCraft's own. An unknown parameter (`highlightSize` and `drawHiddenFaces` +included), a number out of range, a flag that is not true or false, a surface other than `none` or `diffuse`, or +another shading color is refused with an error and the document is not changed. + +```json +{"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.classicRotate","item":null,"params":{"rotationX":0,"rotationY":40,"rotationZ":0,"surface":"diffuse","blendSteps":64}}}} +``` + ## Edit Colors and Recolor Artwork @@ -2944,6 +3348,11 @@ with one gray channel, so a PDF writes it in gray. `includePatterns: false` leaves patterns out. The Blend commands also grade gradient meshes, which keep their shading. `edit.colors.saturate` needs `intensity`, a number from -100 to 100 (a number outside the range counts as its nearest end). Without one, or with a value that is not a number, it answers `` missing number `intensity` `` and changes nothing. +The `edit.colors.*` commands, `edit.colors.overprintBlack` and `addon.color.filter` answer a `fill`, `stroke`, +`includeImages`, `includePatterns`, `convert`, `remove`, `includeCmyBlacks` or `includeSpotBlacks` that is not true or +false with `` `fill` must be true or false ``, naming the key, a `percentage` that is not a number with +`` `percentage` must be a number ``, and a `mode` that is not a string with `` `mode` must be a string ``. They change +nothing and record no undo step. A null counts as a key left out. The reply of `recolor.apply` and of every command above except the Blend commands has `notChanged: {locked, hidden}`. When the selection is exactly what `select.all` takes (in isolation mode, what it takes inside the isolated group), it @@ -3048,6 +3457,16 @@ that shape, and the effects before it are left out. Its Contents row stands for vector exports write those items as paths, and `effect.expandAppearance` turns them into objects in a group with the image. Use Preview Bounds measures an image by its frame. +A Warp effect (`warp.arc` … `warp.twist`) on an image, or on a group that holds one, bends the image's pixels with its +frame: after the last effect in the list, the image is cut into 10 × 10 cells of two triangles, each a clipped piece of +the image under its own affine map. The cell count is VectorCraft's own. Effects after the Warp reshape only the frame, +a second Warp bends the same pieces, and a Transform effect moves them. A placed gradient on a group that holds the +image follows the group's bounds as the pieces draw them. The pieces keep the +image's fill color when it colorizes a grayscale image, and so do the pieces an envelope cuts. Under any geometry +effect, an image keeps that color and is drawn with or without smoothing as the image is. SVG writes the image once and +draws the pieces with `<use>`; PDF, EPS, `.ai` and PNG write the bent pieces. Removing the warp shows the image as it +was. The images stay unbent when their pieces would make the art pass 2 million objects, and an image stays unbent when +its clipping frame keeps its shape because the warp would pass the effects' anchor budget. ```json {"name":"run_command","arguments":{"command":"appearance.addFill","params":{"ids":[7]}}} @@ -3065,8 +3484,9 @@ in the `swatch.list` shape (`library` is an id or a name). `swatch.library.add { into the document as one undo step: a colour group's name brings the whole group, a swatch's name the swatch alone, no names the whole library; swatches the document already has (same name and paint) are reported under `existing` and not added again. `apply: "fill"|"stroke"` also applies the first one, in the same undo step (what clicking a -swatch in the library panel does). The pattern library Geometric Patterns (`geometric-patterns`, category -`patterns`) holds pattern swatches drawn in code; adding one also adds its pattern, as pasting art painted with it does +swatch in the library panel does). The pattern libraries Geometric Patterns (`geometric-patterns`) and Grit Textures +(`grit-textures`: seamless black grain, grit, sand, speckle, stipple, scratch and fleck tiles), category `patterns`, +hold pattern swatches drawn in code; adding one also adds its pattern, as pasting art painted with it does (the same pattern the document has is reused, and a name another pattern or swatch has gets a number). `swatch.resetDefaults {replace?}` brings back the missing default swatches. @@ -3114,7 +3534,10 @@ as a value left out. ## Graphic style libraries Graphic style libraries are read-only sets of graphic styles generated in code (Shadows and Glows, Outlines and -Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD, Status Effects). `graphicStyle.libraries` lists them +Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD, Status Effects). Textures +(`textures`) paints its fills and strokes with the texture effects: Fine Grain (`texture.grain`), Canvas Weave and Burlap +Sack (`texture.texturizer`), Cracked Glaze (`texture.craquelure`), Mosaic Floor (`texture.mosaicTiles`), Quilted Squares +(`texture.patchwork`), Leaded Glass (`texture.stainedGlass`) and Damp Paper (`sketch.waterPaper`). `graphicStyle.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `graphicStyle.library {library}` returns one's styles in the `graphicStyle.list` shape (`library` is an id or a name). `graphicStyle.addFromLibrary {library, name? | names?}` copies styles into the document's Graphic Styles as one undo step (no names: the whole library); styles the @@ -3124,6 +3547,13 @@ the patterns the styles paint with come along. `apply: true` also applies the fi does. Library styles keep placed gradients in unit-box space, so each object gets them at the same place relative to its bounds. +Painted and Sketched (`painted-sketched`) holds Washed Blue, Bristle Ochre, Pastel Heather, Charcoal Shade, Ink +Contour, Wet Ink and Fine Pen. Each is a solid fill (Bristle Ochre and Ink Contour add a 1 pt stroke) under one object +effect that repaints fill and stroke together: `artistic.watercolor`, `artistic.dryBrush`, `artistic.roughPastels`, +`sketch.charcoal`, `brushStrokes.inkOutlines`, `brushStrokes.sumiE` and `sketch.graphicPen`, in that order. The +colors and effect settings are VectorCraft's own. These are raster effects, so the document's raster effects +resolution sets how fine they draw. + ```json {"name":"run_command","arguments":{"command":"graphicStyle.library","params":{"library":"hand-drawn"}}} {"name":"run_command","arguments":{"command":"graphicStyle.addFromLibrary","params":{"library":"hand-drawn","name":"Crosshatch","apply":true}}} @@ -3138,8 +3568,8 @@ with the same extension and bytes as one there, loads as that User Defined libra ## Symbol libraries -Symbol libraries are read-only sets of symbols: four generated in code (Basic Shapes, UI Frames, Map Markers, -Inventory Icons), the `.vectorcraft` files in +Symbol libraries are read-only sets of symbols: five generated in code (Basic Shapes, UI Frames, Map Markers, +Inventory Icons, Skill Icons), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the symbols of any document loaded with `symbol.loadLibrary`. `symbol.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `symbol.library {library}` returns one's symbols (`name`, `size`, `registration`, `exportType`; `library` is an @@ -3163,8 +3593,8 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: five generated in code (Art Ribbons, Calligraphic Nibs, Pattern -Borders, Scatter Shapes, Game Trails), the `.vectorcraft` files in the user library folder of the desktop app (User +Brush libraries are read-only sets of brushes: seven generated in code (Art Ribbons, Calligraphic Nibs, Bristle +Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). @@ -3341,8 +3771,13 @@ where the layout puts it. ## Flatten Transparency `object.flattenTransparency {ids?, preset?, …options}` turns transparent art into opaque art that looks the same, in -one undo step. The targets split into groups of overlapping objects; groups without transparency stay as they are. -Each other group becomes one group of atomic regions: paths filled with the flat colour the art showed there (over +one undo step. The targets split into groups. A group holds each object with transparency and every object it +overlaps, counting 1 pt around each object for antialiasing. It also holds each object without transparency that +overlaps a member in the same way and lies above that member but below the group's topmost object, whose place the +group takes. +Objects without transparency that overlap only others without transparency stay as they are. Overlapping objects of +which one is inside a clip group or clipping layer form one group, with transparency or without; groups without +transparency stay as they are. Each other group becomes one group of atomic regions: paths filled with the flat colour the art showed there (over white, which blend modes do not read; over nothing, keeping alpha, with `preserveAlpha: true`), plus one image where gradients, patterns, images, opacity masks or raster effects reach (clipped to those regions with `clipComplexRegions`, a rectangle without). The image leaves out the part of such art that the clipping path of a clip group or clipping layer hides, so art under @@ -3927,6 +4362,13 @@ an `anchor` or `segment` in the same way. The document does not change and no un after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves, with the new anchor as an end of both that moves with them. Undo restores the path and the selection in one step. +`path.close {id, subpath?, in?, out?, independent?}` closes an open subpath (by default the last open one). `in` places +the first anchor's incoming handle as `path.setHandle` places a handle: a smooth anchor turns its outgoing handle to +stay in line and keeps that handle's length, and a corner keeps its outgoing handle where it is. With +`independent: true` the anchor becomes a corner first, so its outgoing handle does not move. `out`, placed after `in`, +is the first anchor's outgoing handle, and makes the anchor a corner. A Pen press on the first anchor sends `in` at +the anchor with `independent: true`. The Pen's and the Smart Pen's closing drags send the mirror of the pointer as +`in`, and once Alt is held they also send `out` at the outgoing handle's position when Alt went down. `path.reshape {id, x, y, dx, dy, tol?, focal?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an anchor there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. @@ -3975,8 +4417,8 @@ an `x` without a `y`, or a `y` without an `x`, with "x and y must be given toget `path.blob` refuse a point in `points` whose x or y is not a number, such as `["10", 10]` or a point written as a string, with "x and y must both be numbers". All of them except `path.curvature` refuse a pen pressure, tilt or rotation that is neither a number nor null with `` `pressure` must be a number, not "0.5" ``, naming the key -(`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `in` that is not `[x, y]` -with `` `in` must be [x, y] ``. +(`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `in` or `out` that is not `[x, y]` +with `` `in` must be [x, y] ``, naming the key. These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: @@ -4222,6 +4664,27 @@ files saved without it read back with it off. {"name":"run_command","arguments":{"command":"object.setPixelAligned","params":{"ids":[12],"on":false}}} ``` +### Align New Objects to Pixel Grid + +`document.setup {alignNewObjectsToPixelGrid: true|false}` turns the document's Align New Objects to Pixel Grid on or +off in one undo step, as the New Document dialog's Advanced Options checkbox and the Transform panel menu's checked item +do (described on the help page, +<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>); +`document.setup` with no params reports it. While it is on, every path and compound path drawn in the document (the +shape, line, arc, spiral, Pen, Curvature, Pencil, Paintbrush, Blob Brush and `addon.shapes.*` commands, and the paths +in a new rectangular grid, polar grid or flare) takes the pixel-aligned property and is snapped in the undo step that +makes it. These rules are VectorCraft's own: type, images, groups and guides do not take it; art already in the document stays as it is when the setting changes; objects that Paste, Duplicate, Place and +import bring in keep their own property; and `object.setPixelAligned` turns one object's property off without changing +the document's setting. `file.new {alignNewObjectsToPixelGrid}` sets it for the new document. The Mobile and Web presets +start with it on and the other built-in presets with it off; saved presets and Recent entries keep the value they were +made with, and a saved preset from before the setting reads off. The setting is saved in the native file only when on, +and files saved without it open with it off. + +```json +{"name":"run_command","arguments":{"command":"document.setup","params":{"alignNewObjectsToPixelGrid":true}}} +{"name":"run_command","arguments":{"command":"file.new","params":{"preset":"Letter","alignNewObjectsToPixelGrid":true}}} +``` + ## Live Corners `object.setLiveShape {id?, ids?, radius?, kind?, corners?, items?}` sets the corners of any path (one undo step): a live @@ -4362,9 +4825,12 @@ page describes saving the list from the Keyboard Shortcuts dialog as a text file The desktop app adds its active artboard, the one the Artboards panel highlights, to the `object.align`, `object.distribute`, `object.distributeSpacing` and `select.allOnArtboard` calls it runs without `artboard`, as it does -for `edit.pasteInPlace`, `edit.pasteInFront` and `edit.pasteInBack`, and to each `command.batch`. A batch passes its +for `edit.pasteInPlace`, `edit.pasteInFront` and `edit.pasteInBack` (while the Artboard tool has several artboards +selected, it adds those to these three as `artboards` instead; in a document without artboards it adds neither), and to +each `command.batch`. A batch passes its `artboard` on to each of these steps that names -none, when the step runs. When the document a step runs in has no artboard at that index (for example, after an +none, when the step runs; a paste step that names `artboards` keeps them, and one that names neither, while the +Artboard tool is chosen with several artboards selected, pastes a copy on each of those. When the document a step runs in has no artboard at that index (for example, after an earlier step deleted the active artboard when it was the last one), the step gets that document's last artboard. In remote mode, MCP's `run_command` calls and each step of the `command_batch` tool get the active artboard too. The Actions panel plays an action as a `command.batch`, omitting steps whose playback checkmarks are @@ -4383,7 +4849,8 @@ Save for Office Documents included) that writes a file and that the batch does n warning. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name -for existing callers; the dialog starts with File + Number. A folder source ignores this parameter. The folder +for existing callers; the dialog starts with File + Number, and shows and sends the choice only when Destination is +Folder. A folder source ignores this parameter. The folder destination and overridden Save/Export paths use the chosen stem with the output format's extension. An empty data set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, @@ -4393,7 +4860,12 @@ template, AI or AIT format counts artboard file names when the document has any counts them when the document has several artboards. Under Data Set Name, VectorCraft makes Windows device names safe (`CON` becomes `CON-`). This is VectorCraft's naming behavior. Caps: 500 -files or data sets, 8 folder levels, 256 steps. An action recorded in the Actions panel leaves the artboard out, +files or data sets, 8 folder levels, 256 steps. `action.batch` refuses `includeSubdirs`, `overrideOpen`, +`overrideSave`, `overrideExport` or `stopOnError` given as anything but true or false, such as `"false"`, with +`` `stopOnError` must be true or false ``, and `source`, `folder`, `destination`, `destinationFolder`, +`datasetFileNaming` or `label` given as anything but a string with `` `label` must be a string ``, naming the key. +It checks them, and that `source` is `folder` or `datasets`, before it makes the destination folder or opens a file. +A null is read as a key left out. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard @@ -4713,7 +5185,8 @@ Pen's second anchor at (150, 431), in line with the square's centre. `type.resetTracking` (Cmd+Alt+Q, `press_key {key: "Q", mods: {cmd: true, alt: true}}`) sets tracking to 0 and clears manual kerning in the type objects in `ids`, the Type tool's selected text or the selected type objects, keeping Optical; at a caret - it resets only the kerning of the character before it. `type.resetHorizontalScale` (Cmd+Shift+X, + it resets only the kerning there: of the character before it, or at the start of a line (of the text, a paragraph, + or after a forced line break) the space before the character after it (`kerningBefore`). `type.resetHorizontalScale` (Cmd+Shift+X, `press_key {key: "X", mods: {cmd: true, shift: true}}`) sets the horizontal scale to 100%, as the Character panel shows it, in the same text; at a caret it leaves the text as it is. In the app, `type.highlightKerning` (Cmd+Alt+K), `type.highlightTracking` (no default key) and `type.highlightFontName` (Cmd+Alt+Shift+F) show the Character panel and @@ -4906,10 +5379,14 @@ Exporting and importing preferences is an optional VectorCraft feature. as a red outline around each artboard), the transparency grid (size and two colours; the first is also the simulated paper colour), the flattener preset and Discard White Overprint (Overprint Preview keeps white overprints visible while it is on), the type options (language and its quotes, Use Typographer's Quotes for typed straight quotes and a typed `”` where a quote opens, superscript, subscript -and small caps proportions, SVG text export) and the background contents (white: raster exports are white behind the -art). Pass any of these keys to change them in one undo step; `document.setUnits` stays as an alias for `units`. +and small caps proportions, SVG text export), the background contents (white: raster exports are white behind the +art) and Align New Objects to Pixel Grid (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). +Pass any of these keys to change them in one undo step; `document.setUnits` stays as an alias for `units`. A file whose bleed (0 to 72 pt a side), superscript and subscript sizes (1 to 500%) and positions (-500 to 500%) or small caps size (1 to 200%) lies outside those ranges opens with the nearer end of each range. +`document.setup` does not take the color mode or the assigned profiles. The Document Setup dialog's Color tab sets +them with `edit.assignProfile` and `file.documentColorMode`: its OK runs `document.setup`, then `edit.assignProfile`, +then `file.documentColorMode` in one `command.batch`, and the document's changes are one undo step. ```json {"name":"run_command","arguments":{"command":"document.setup","params":{"gridColors":"Blue","gridSize":"large","language":"German","bleed":9}}} @@ -4920,7 +5397,8 @@ small caps size (1 to 200%) lies outside those ranges opens with the nearer end `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, spacing, rightToLeft}`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's -value outside that range is read as the nearer end) and `previewMode`. +value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see +[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets @@ -4981,6 +5459,23 @@ Dock to Top and Dock to Bottom, the edge in use checked, and so does a drag of t the edge the pointer is released nearer and shows a band along that edge while it moves. The edge is kept with the workspace, and a workspace saved without it docks the bar at the top. Another `edge`, or none, fails with "`edge` must be one of top, bottom" and leaves the bar where it is. +`window.control.options {group, visible?}` (desktop app) turns a group of the Control bar's options on (`visible: +true`), off (`false`) or toggles it (omitted), and returns `{group, visible}`. The groups are `snapping` (the Snapping +menu), `anchors` (Convert and Anchors), `toolOptions` (the active tool's options), `objectOptions` (Isolate Selected +Object or Exit Isolation Mode, the envelope controls and the symbol instance controls), `imageOptions` (a selected +image's or Image Trace object's controls), `fillStroke` (the fill and stroke chips, Stroke and its weight and width +profile), `opacity`, `graphicStyle` (Style, Recolor Artwork and Global Edit Options), `character`, `paragraph`, +`verticalAlignment` (area type's vertical alignment), `alignDistribute`, `transform` (the Transform link and the X/Y/W/H +fields, with the Artboard tool too), `artboardOptions` (the Artboard tool's other controls) and `documentOptions` +(Document Setup and Preferences, with nothing selected). The bar's panel menu lists the groups above Dock to Top and Dock +to Bottom, each checked while it is on, and runs the command for the group clicked. A group that is off stays out of +the bar even while its tool or object is selected, takes no room, and leaves the room to the groups after it; a group +that is on shows only while the selection or the tool calls for it. With an image or an Image Trace object selected and +`imageOptions` off, the bar shows neither its controls nor Fill and Stroke. Every group starts on. Which groups are off +is kept with the preferences and with the workspace; a workspace or preferences saved without them show every group, +and a group id the bar does not have is dropped when they are read. Another `group`, or none, fails with "`group` must +be one of …", and a `visible` that is not true or false fails with "`visible` must be true or false"; either leaves +every group as it is. The groups and their contents are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} @@ -5010,7 +5505,9 @@ that draws the image does not decode the file again. `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and -`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). +`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). `file.place`, `file.place.queue` and +`file.place.info` refuse, of the keys each one takes, a `link`, `replace` or `template` that is not true or false and a `thumbnail` that is not a +number, naming the key, and place nothing; null is the same as leaving the key out. ```json {"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/photo.jpg","at":[300,200]}}} @@ -5039,7 +5536,14 @@ its resources as they are now and raises no conflict. Placement: `edit.paste {center}` centres the objects on a point (the app passes the view centre), else offsets them by `dx`/`dy` (the Paste Offset preference). With nothing selected, `edit.pasteInFront` / `edit.pasteInBack` put them on top / at the bottom of the current layer. `edit.pasteOnAllArtboards` keeps their offset to the artboard they were -copied from. `layer.pasteRemembersLayers {on?}` (a document option, `document.inspect` → `pasteRemembersLayers`) +copied from. `edit.pasteInPlace`, `edit.pasteInFront` and `edit.pasteInBack` take `artboard` (one artboard) or +`artboards: [index…]` (a copy on each, placed where the objects were on the artboard they were copied from, the +copies in artboard order); `artboard` wins when both are given. Without either, while the Artboard tool is chosen with +several artboards selected, they paste a copy on each of those, and the journal records them as `artboards`; a +recorded action leaves both out. Art copied from no artboard keeps its place on the first artboard named and its +offset to that one on the others. An index the document does not have, a repeated index, a value that is not an index +or an empty list fails, and nothing is pasted. Copied artboards come back once, where they were, whichever artboards +are named. `layer.pasteRemembersLayers {on?}` (a document option, `document.inspect` → `pasteRemembersLayers`) pastes objects back into the layers they came from, by name, making missing ones. Drawing modes (`view.drawMode`) apply too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind, @@ -5287,13 +5791,23 @@ They also write the `copyrightNotice` as `dc:rights`, the `copyrightUrl` as `xmp `copyrightStatus` as `xmpRights:Marked` (`True` for copyrighted, `False` for public domain, none for unknown) to the XMP packet. A PDF, `.ai` or `.ait` opened from its pages or its editing copy (`document.open`, -`file.newFromTemplate`, `file.revert`; not one restored from the document it carries) opens with the `author`, -`description`, `keywords`, `copyrightStatus`, `copyrightNotice`, `copyrightUrl`, `created` and `modified` that its XMP -packet (`dc:creator`, `dc:description`, `dc:subject` or `pdf:Keywords`, `xmpRights:Marked`, `dc:rights`, -`xmpRights:WebStatement`, `xmp:CreateDate`, `xmp:ModifyDate`) and its document information dictionary (`Author`, -`Subject`, `Keywords`, `CreationDate`, `ModDate`) give, the XMP packet's value where both give one. A value that -`file.info` would refuse is left out, and the title is set as for any other open (the file name, or a new untitled -name for a template). +`file.newFromTemplate`, `file.revert`; not one restored from the document it carries) opens with the `title`, +`author`, `description`, `keywords`, `copyrightStatus`, `copyrightNotice`, `copyrightUrl`, `created` and `modified` +that its XMP packet (`dc:title`, `dc:creator`, `dc:description`, `dc:subject` or `pdf:Keywords`, `xmpRights:Marked`, +`dc:rights`, `xmpRights:WebStatement`, `xmp:CreateDate`, `xmp:ModifyDate`) and its document information dictionary +(`Title`, `Author`, `Subject`, `Keywords`, `CreationDate`, `ModDate`) give, the XMP packet's value where both give +one (for `dc:title` and `dc:description`, the `x-default` language item first). An SVG opens with the `title` of its +root `<title>` element (not a shape's or group's). A title is read with its white space made single spaces and +without control characters, at most 65,536 characters, as `file.info` takes one. A value that `file.info` would +refuse is left out. A file that gives no title, a blank one or the `Untitled-N` name New gives leaves File Info with +the document's name as its title, and a template opens with a new untitled name. +The title a file gave is File Info's alone: the document's name, which is what its tab shows until it has a file and +what Save As and the default export names start from, stays the file's name with its extension (`box.svg`), or the +title a native file holds. File Info's `title` is the one the file gave, else the document's name. It is saved with the +document (a native file, and the editing data of an SVG, PDF, `.ai` or EPS that carries it), and the files an export +writes carry it (PDF `Title` and XMP `dc:title`, SVG `<title>` and Dublin Core, PNG text, EPS and `.ai` `%%Title`), +where the document has one. Changing the `title` with `file.info` sets the document's name, as it always did, and drops +the title the file gave. `document.inspect` (`inspect_document`) and the `document.open` (`open_file`) reply report the File Info title as `fileInfoTitle`. Their `title` is the document's tab name, which comes from the file name once the document is saved to or opened from a file (with ` [Converted]` or ` [Recovered]` where that applies). @@ -5586,8 +6100,11 @@ DXF layer (hidden layers switched off, locked ones locked, non-printing ones not straight paths become polylines (an open path of one straight segment becomes a line, except for a stroke weight before 2000), curved ones cubic splines through every anchor, fills their outlines followed by solid hatches (laser and cutter software reads the outlines and skips hatches; R12 has no hatches: the outlines -alone), strokes lines with their lineweight and a linetype per dash pattern, and placed images image entities linked -to PNG or JPEG files (`rasterFormat`) written next to the drawing (`linked` in the result). Coordinates are y up +alone; an open path's fill outline is closed, as the fill is), strokes lines with their lineweight and a linetype per dash pattern, and placed images image entities linked +to PNG or JPEG files (`rasterFormat`) written next to the drawing (`linked` in the result). `includeImages: false` +leaves placed images out, with no image entity, no linked file and no decoding of their pixels, and `includeHatches: +false` writes each filled area as its outlines alone, without its solid hatch (both default to `true`; these two +options are VectorCraft's own). Either one, when it leaves something out, adds one note to `warnings`. Coordinates are y up from the bottom-left corner of the first artboard (or `artboard`), in drawing units: `scale` units per `unit` (default 1 mm = 1 unit, which sets `$INSUNITS`); `scaleLineweights` scales the lineweights with them. `colors` is `8`, `16` or `256` indexed colours, or `true` (default; true colour with the nearest index, DXF 2004 and later). `preserve: @@ -5600,7 +6117,8 @@ selected objects in their layers (every export takes it), and `useArtboards: tru artboard holding the art over it. `dxfPreset: "cnc"` (CNC / CAM; default `"custom"`) sets the options for cutting software that the call does not give: version `2000` (the oldest version that has both lightweight polylines and lineweights), `unit: "mm"` and `scale: 1`, `colors: 256` (all version 2000 holds), `preserve: "editability"` with `alterPaths: false` (every -stroke a center line), `outlineText: true` (type as paths), and `rasterFormat: "png"`. DXF Options has the same choice as its Preset menu, +stroke a center line), `outlineText: true` (type as paths), `includeImages: false` and `includeHatches: false` (the +cutting paths alone: fills as their outlines, no image files), and `rasterFormat: "png"`. DXF Options has the same choice as its Preset menu, which shows Custom again once a field it sets is changed. What DXF can't hold (gradients and patterns as one colour, blending, opacity masks, raster effects, clipping) comes back in `warnings`. In R13 and later, an image that can't be decoded is left out with no linked file, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such @@ -5650,10 +6168,12 @@ reduced size"; the document keeps the whole file) or, when it can't be read that allowance has bytes, drawn as a crossed gray box on the canvas and left out of exports ("too large to draw"); `document.open` and `file.place` say the same in their `warnings`). `links.info {id?}` is the Link Info: `image.info`'s fields plus `status`, `format`, the file's `ppi` and the `effectivePpi`, `scale` (% of 100%), `rotation` (degrees, counter-clockwise), `placement` and, for a linked file, `fileName`, `location`, `fileSize`, `created`, `modified`. +With automation read roots, a file outside them has no `path` or `found` in `links.list` and `links.check`, and no +`link`, `path`, `location`, `fileSize` or `modified` in `links.info`; its row keeps the file's name. `links.goTo {id}` selects an image; `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. -`links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, +`links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and `links.reveal` open the linked file in its app or show it in its folder (desktop). Edit Original runs only from the app's window, @@ -5677,7 +6197,8 @@ type uses in `Fonts/` (fonts whose licence doesn't allow embedding are listed in the copies (each file copied once); one that can't be read is copied as it is, and a cycle of placed documents or one past the nesting limit stops there, each with a line in `warnings` and the report. A `folder/name` where a packaged file would replace the document or one of its linked files (the document's own folder, say) is an error, and nothing is -written. Every option defaults to true. Without `folder` (the web, or an agent that wants the bytes) the +written. Every option defaults to true. An option that is not true or false, or a `folder` or `name` that is not a +string, is an error naming the key, and nothing is written; null is the same as leaving the key out. Without `folder` (the web, or an agent that wants the bytes) the result carries the same files as a zip (`{name: "<name>.zip", dataBase64}`, entries under `<name>/`). `document.info {selectionOnly?, category?, format?: "text"}` adds `sections` (`[{id, title, rows: [[label, value]]}]`: @@ -5691,7 +6212,11 @@ whose drawn characters use a pattern included, hidden fills and strokes, strokes member's own fills and strokes, an image's fills and strokes that no Convert to Shape or Outline Object effect gives a shape, and characters that draw nothing (spaces and line breaks without an underline or strikethrough) left out, with the patterns it uses, which the patterns category lists as Pattern Objects and `objects.patterns` counts; with `selectionOnly`, those in the selection), -`patternNames` (the patterns those objects use) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left +`patternNames` (the patterns those objects use), `gradientObjects` (`[{id, name, gradients}]`: every object filled or +stroked with a gradient, by the same rules as `patternObjects`, with the gradients it uses: the name of the gradient +swatch a gradient is linked to, else `Linear gradient`, `Radial gradient` or `Freeform gradient`; the gradients category +lists them as Gradient Objects and `objects.gradients` counts them; gradient swatches no art uses are not listed; with +`selectionOnly`, those in the selection), `gradientNames` (the gradients those objects use) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left out, which objects lists as Path Length in the document's units, say for a cut line or an LED strip along the letters); `format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?, selectionOnly?, category?}`: only `category` when given, else every category) and the package report write. @@ -5989,6 +6514,88 @@ clipboard service offers it (the Windows desktop service doesn't read metafiles {"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/chart.emf","at":[300,200]}}} ``` +## HP-GL import + +`document.open` and `file.place` read HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`) into one layer, with the +artboard round the art. A file whose extension no other format reads opens as HP-GL when it starts with plotter +instructions. Older HP-GL files are read by the HP-GL/2 rules for the instructions the two share. The reader follows +the [HP-GL/2 and HP RTL Reference Guide](https://support.hp.com/sg-en/document/c01121263). + +Plotter units (1016 to the inch, y up) become points through the scaling the file sets (`IP`, `IR`, `SC`) and its +rotation (`RO`). Each line drawn with the pen down is one stroked path in the pen's color (`SP`, `PC`, `NP`, `CR`) +and width (`PW`, `WU`; 0.35 mm by default), with the line type (`LT`, `UL`) as a dash pattern and the line attributes +(`LA`) as caps and joins. Circles, arcs, wedges and Bézier curves (`CI`, `AA`, `AR`, `AT`, `RT`, `EW`, `WG`, `BZ`, +`BR`) are drawn as curves. Filled rectangles, wedges and polygons (`RA`, `RR`, `WG`, `PM` with `FP`) become filled +paths, and edged ones (`EA`, `ER`, `EW`, `EP`) become stroked paths. Encoded polylines (`PE`) are read, and printer +escape sequences and PJL lines around the instructions are skipped. + +Two rules are VectorCraft's own: before the first `SP` the pen is pen 1, and the hard-clip limits are 11 × 8.5 in +from the origin, so P2 lies there when the file sets no scaling points. +`SP0` draws nothing. Labels, the symbols of symbol mode (`SM`) and raster images are not drawn, the input window +(`IW`) does not clip the art, the art of later pages is drawn over the first page, and hatched and patterned fills are +filled solid; `warnings` lists each of these. A file named as a plot file that doesn't start with plotter +instructions is refused with "not an HP-GL file". + +```json +{"name":"open_file","arguments":{"path":"/tmp/part.plt"}} +{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/part.plt","at":[300,200]}}} +``` + +## HP-GL export + +`document.export` (and `export`, and Export As) with format `hpgl` writes a plot file (`.plt`) of the first artboard +(or `artboard`) for pen plotters and cutters; `useArtboards: true` writes one file per chosen artboard +(`{stem}-{artboard}.plt`), `false` the bounds of the visible art. Each visible path is drawn once along its own line: +a filled shape is its closed outline, also when a stroke gives its color, and a stroked path is its center line, so +fills, stroke widths, dashes, brushes and arrowheads are not painted. Type is drawn as its glyph outlines, and a +gradient mesh as its outline, also inside a blend (a mesh whose every point is at 0% opacity draws nothing). A +symbol instance is drawn as its symbol's art with the art's effects, in the colors of the instance's stain. +Clipping masks cut the art they clip, and the art is cut at the artboard's edges. Hidden and non-printing layers, +hidden objects, objects at 0% opacity, template layers and guides are left out, and so are placed images, with a +warning. Coordinates are plotter units (1016 to the inch, y up) from the artboard's bottom-left corner, or its +center with `origin: "center"`, rounded to whole units, as the HP-GL/2 and HP RTL Reference Guide defines them +([book listing](https://informit.com/store/hp-gl-2-and-hp-rtl-reference-guide-a-handbook-for-program-9780201310146); +the [vendor's support page](https://support.hp.com/sg-en/document/c01121263) names it as the language reference). +The guide also gives the instruction syntax and the encoding of `PE` numbers that the writer follows. Art more than +8,388,607 units (about 210 m) from the origin is cut off, with a warning. + +Each color is a pen. Pen 1 is the first color the plot draws in, pen 2 the next new one, and so on, up to 255 pens; +colors past those draw with the pen of the nearest color. The files of one export share the numbering, so a color is +the same pen in each file. `pens: ["#000000", "#ff0000"]` gives the pen table instead (pen 1 first): each path draws +with the pen of the nearest color, the lower pen when two are as near. A path's color is its topmost visible stroke's, +else its topmost visible fill's, where a fill or stroke at 0% opacity does not count. A gradient's color is the average +of its stops, a gradient mesh's the average of its points' colors (points at 0% opacity left out), and a pattern's its first visible solid fill (gray +when it has none). The pens draw in turn, each pen's paths in paint order, or with `sortPaths: true` each next path +the one that starts nearest where the pen stopped (an open path may be drawn from its other end, and a closed one +starts at its point nearest the pen). With `insideFirst: true`, a path is drawn only after every path of the same +pen that lies inside it, for example a letter's counter before the letter and a part's holes before the part. A +path lies inside a closed path when it does not cross that path's line, every part of it lies inside that path (by +the even-odd rule) or on its line, and some part lies inside: a path touching the line around it is inside, a path +crossing it or leaving it through a corner is not, and copies of one outline are not inside each other. Without +`sortPaths` the paths otherwise keep paint order; with it, the next path is the nearest of those free to draw. +Curves become straight moves no further than `curveTolerance` points from the curve (default 0.1, from 0.01 to 10). +These defaults, the 255-pen limit and the rules for pen numbers, colors and the order of paths above are +VectorCraft's own. + +`hpglVersion: "hpgl"` (the default) writes `IN;`, then for each pen `PU;SP<n>;` and each path `PUx,y;PDx,y,…;`, and +ends with `PU;SP0;`. `"hpgl2"` also writes the palette (`NP` and a `PC` color for each pen) and draws each pen's +paths as one encoded polyline (`PE`, base 64), which takes fewer bytes than the same moves as text. An `"hpgl"` plot +with a coordinate outside −32,768 to 32,767 units (about 82 cm from the origin, the range of 16-bit numbers) is written +as it is, with a warning that older devices may not read it; this check is VectorCraft's own. `warnings` names +type drawn as outlines, inline graphics in type (left out), placed images, opacity masks, raster effects, stroke +looks that are not drawn, art past the plotter's range, HP-GL coordinates past 16-bit numbers, colors past 255 pens, +and the limits on points, clipping work, symbols, live art, nesting depth and sorting. Sorting and finding which paths lie inside which share one +work budget for the plot, 500 million box and point comparisons. When sorting runs out of it, the paths not yet +drawn keep paint order, each after the paths inside it with `insideFirst`. When it runs out while the writer is +finding which paths lie inside which, the paths of that pen and of the later pens keep paint order. Both cases add +a warning. + +```json +{"name":"export","arguments":{"path":"/tmp/decal.plt","format":"hpgl"}} +{"name":"run_command","arguments":{"command":"document.export","params":{"format":"hpgl","path":"/tmp/sheet.plt","useArtboards":true,"hpglVersion":"hpgl2","pens":["#000000","#ff0000"],"sortPaths":true}}} +{"name":"run_command","arguments":{"command":"document.export","params":{"format":"hpgl","path":"/tmp/stencil.plt","sortPaths":true,"insideFirst":true}}} +``` + ## TIFF, BMP and Targa export `document.export` (and `export`) writes them like the other raster formats: one artboard (or `useArtboards`, one @@ -6118,7 +6725,8 @@ point, as in SVG export), `pt`, `mm`, `cm` or `in`; `unnamed: false` leaves out writes the `.css` file with the PNGs of rasterized art next to it (no path: `data` and `images` as base64). Its `warnings` add the PNGs' notes to the CSS's, each once (an image that couldn't be decoded, type written in the fallback font…). In the app, `css.copy` copies the CSS and `css.exportFile` writes it through a save panel (the web -downloads it) and shows the first note in the status bar. +downloads it) and shows the first note in the status bar, with how many there are; resting the pointer on the +message lists up to 30 of them, fewer when the list would not fit in the window, with how many were left out. ```json {"name":"run_command","arguments":{"command":"css.selection","params":{"units":"px","position":true}}} @@ -6138,12 +6746,67 @@ appearance of their own or knockout stay one pixel layer. Hidden layers and obje `hiddenLayers: true` writes them as hidden layers. `layers: false` writes one flat image, on white where nothing is drawn. Files are at most 30000 pixels a side. -Photoshop documents (`.psd`, and `.psb`, the large document format) open and place as their merged image, the -flattened picture every Photoshop file carries (layers aren't read): Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK +PSD files (`.psd`, and `.psb`, the large document format) place as their merged image, the +flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution. A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it again when it changes); Multichannel files are refused. +`document.open` converts a PSD or PSB file's layers to objects. In +[PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html), +the option that converts layers to objects keeps as much of the layer structure as it can, merges the layers of a +clipping mask into one layer and discards hidden layers that require merging; the option that flattens the layers +imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with +`layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges +adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with +the layers below them. `document.open` applies neither adjustments nor knockouts, and it merges a layer by its blend +mode alone, as the rules below say. + +The rest are VectorCraft's own rules: + +- Each layer becomes a layer of the document holding its pixels as an image, with the layer's name, visibility, + opacity and blend mode. +- A layer group becomes a layer of sublayers. A Pass Through group is not isolated; a group in any other mode is. +- Layers clipped to the layer below are merged into it as one image, shown where that layer has pixels. Layers + clipped to an adjustment layer, or to a fill layer that stores no pixels and isn't drawn, show over the whole + canvas, through that layer's mask. +- Hidden layers are left out unless `hiddenLayers: true`, which brings them in hidden. A hidden layer that would + need a merge is always left out, with the layers clipped to it. The `warnings` count the layers left out. +- `layers: false` opens the merged image. +- A layer or group in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, + Divide, Darker Color or Lighter Color is merged with the visible layers below it in its group, whether or not it + holds transparent pixels. Layers in Color Dodge, Color Burn and Difference keep their mode. In such a merge, the + layers of a Pass Through group blend with the layers below the group, at the group's opacity and through its layer + mask. +- A Dissolve layer's partly transparent pixels are merged as opaque or transparent, opaque at the share of its + pixels their transparency gives, in a fixed pattern that differs from layer to layer. +- A merged layer is named after the layers it holds, joined with ` + `. +- A layer name the file stores only as a one-byte Pascal string, without its Unicode name, is read as Mac Roman. +- A layer's opacity is multiplied by its fill opacity, in every blend mode. A layer that others are clipped to keeps + its own opacity, and its fill opacity fades only its own pixels. +- A layer mask becomes the layer's opacity mask: a gray image that hides the layer outside it when the mask's + default color is black and shows it when white. A disabled mask is kept, switched off. +- Type and shape layers, and gradient and pattern fill layers that store pixels, come in as the pixels the file + stores. A solid color fill layer that stores no pixels and has no vector mask comes in as an image of its color + (RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers + clipped to it are left out. +- Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, + knockouts and vector masks are not applied; the `warnings` count them. +- Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits. +- A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image + with a warning, and when the merged image can't be read either, the file is refused with an error. + +Each layer's pixels must fit the memory allowed for one image, and the pixels of all the layers and masks, with the +canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image, +with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when +they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its +own instead of clipped. File › Open in the app has no PSD import options dialog: it converts the layers and leaves +hidden layers out. + +```json +{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}} +``` + JPEG XL images (`.jxl`, a bare codestream or the ISOBMFF container) open and place as their first frame, with the orientation their header gives, decoded with jxl-oxide and stored as PNG. 16-bit and floating-point samples become 8 bits, and alpha is kept. Colors are converted to sRGB in XYB-encoded images and when the header names the color space @@ -6417,12 +7080,17 @@ Native files save it only when it is `rows`, so files from before it open by col sizes don't change: the scaling happens at layout time, so rendering and every export see it. The factor is found by bisection over the first run's size in steps of 0.1 pt (its scaled size is a whole number of tenths of a point, so the result is deterministic); at `fitMinPercent` the text may still overflow. +- `block`: Dynamic Text's Block, as `type.dynamicText` turns it on (see below), in place of Auto Size and Shrink Text + to Fit; another fit turns it off. `wordGap` (0–1,000 % of a word space, default 100) and `lineGap` (-1,296 to 1,296 + pt, default 0) set its gaps, and are kept while Block is off. The file stores `"fit": "autoHeight"` or `"fit": {"shrinkText": {"minPercent": 40}}` in the object's `area`; the -command also accepts that object form. The query (and every reply) of `text.areaOptions` reports `fit` as its id, -`fitMinPercent`, `overflow` (the text doesn't fit its frame) and `fitScale` (Shrink Text's factor, 1 unshrunk). +command also accepts that object form. Block is stored as the object's `"dynamicText": true`, with `wordGap` and +`lineGap` in its `area` when they differ from their defaults. The query (and every reply) of `text.areaOptions` +reports `fit` as its id (`block` while Block is on), `fitMinPercent`, `wordGap`, `lineGap`, `overflow` (the text +doesn't fit its frame) and `fitScale` (Shrink Text's factor, 1 unshrunk). `document.inspect` (and `document.node {summary: true}`) reports `overflow` for area type and type on a path (text past -the end of the path), and `fit` and `fitScale` for area type. +the end of the path), and `fit`, `fitScale` and `dynamicText` (Block is on) for area type. Given for several area types (`ids`, or a selection of several), `text.areaOptions` changes only the options given on each one: each frame keeps its other options (it used to take the first frame's), and `fitMinPercent` alone changes only @@ -6447,6 +7115,48 @@ chosen artboards draw all of them. A PDF leaves out the layers that don't print {"name":"run_command","arguments":{"command":"text.areaOptions","params":{"fit":"shrinkText","fitMinPercent":60}}} ``` +### Dynamic Text: Block + +`type.dynamicText {ids?|id?, on?: bool, wordGap?, lineGap?}` (Type › Dynamic Text, and the Contextual Task Bar for +area type outside a thread) turns Block on or off for the +selected area type, as it turns Dynamic Text on or off for type on a path ([Dynamic Text](#dynamic-text)). Area Type +Options › Block is the same setting, and the Properties panel's Paragraph section has a Dynamic Text checkbox, which +shows Word Gap and Line Gap while it is on. The [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) +describes Block as text that scales to fill a rectangular box, with settings for the spacing between words and between +lines. The rest are VectorCraft's own rules: + +- Each line as typed (each paragraph, and each forced line break, Shift+Enter, in one) is one line; lines are not + broken again. Each line is set to the frame's width, less the inset, the gutters between columns and the paragraph's + left, right and first-line indents, by its font size only (tracking and scaling stay): the first character's size in + steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it and their + baseline shifts following. Vertical type sets each line to the frame's height (less the gutters between rows). +- The layout sets every paragraph with `wordGap` as its Desired word spacing (Justification…), and its Minimum or + Maximum word spacing moves out to `wordGap` when `wordGap` lies outside it. The paragraphs keep their own + Justification… values, which apply again when Block is off. Each character's leading is its size plus `lineGap`. A + gap given with no area type in the selection is an error. +- The sizes are written into the characters, so every export and the Character panel see them. After every edit to + the text or the frame (typing, `text.editRange`, character and paragraph changes, `text.areaOptions {width}`, a + frame resize) the lines are fitted again, in the edit's own undo step. The lines are then measured again, in at + most four passes: a line whose width does not follow its size (a tab to a fixed stop) is sized again from what it + measures, and a line that still wraps (a frame that is not a rectangle) is made smaller. +- An empty line, or a line of spaces, keeps its size. At 1,296 pt a line can be narrower than the frame; at 0.1 pt it + can still wrap. A frame with no room along its lines changes nothing. Right-to-left lines are fitted as left-to-right + ones are. +- Off keeps the sizes the text was drawn at. On replaces Auto Size and Shrink Text to Fit. Point type in the selection + is left as it is. Area type in a thread is refused with an error that names it (`text.areaOptions {fit: "block"}` + refuses it too); threading a frame turns Block off, keeping its sizes. Without `on`, it toggles from the first + object's setting, or turns on when a gap is given. A value that is not a boolean, or a gap outside its range, is an + error. When nothing changes, no undo step is recorded. +- Saved and opened, the native file keeps Block on with its gaps and the sizes in the characters; with Block off it + keeps the sizes. + +The reply is `{on, ids, fitScale, wordGap, lineGap}` (`fitScale` as for type on a path, 1 when the first object is area +type; the gaps are the first area type's). + +```json +{"name":"run_command","arguments":{"command":"type.dynamicText","params":{"on":true,"wordGap":120,"lineGap":2}}} +``` + ## Threading text from the in and out ports As in the reference app, selected area type and type on a path show an in port and an out port: area type's on the @@ -6517,7 +7227,9 @@ the middle of its bounding box's right side, hollow on point type and filled on Type and Convert To Point Type. Either keeps the text and its styles and is one undo step; `ids` picks the objects (default: the selection). A frame of threaded text that `type.convertToPointType` converts leaves its thread with the text it holds, and the story flows through the other frames without that text; a thread left with one frame is no -longer a thread. +longer a thread. Area type with Dynamic Text (Block) on becomes point type with Dynamic Text off, at the sizes Block +set its lines to, as `type.dynamicText {on: false}` leaves them; converting it back to area type does not turn Block +on again. ```json {"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}} @@ -6682,6 +7394,25 @@ Panel sets it back to Push Out Only. One undo step. {"name":"run_command","arguments":{"command":"text.setFormat","params":{"kinsokuType":"pushInFirst"}}} ``` +## Korean Line Break Anywhere + +`text.setFormat {koreanLineBreakAnywhere: bool}` (Paragraph panel menu › Korean Line Break Anywhere, shown with the +East Asian options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / +`end` range touches). Off, a Korean word (the characters between two spaces, when any of them is Hangul, Han and kana +included) breaks only at its spaces, after East Asian punctuation in it, and at forced line breaks, so a word that does +not fit moves to the next line whole; a word wider than the line still breaks where it overflows. On, a line may break +between any two Hangul syllables. Both composers and vertical type follow it, No Break and the Kinsoku Set still apply, +and hyphenation never adds a hyphen to Hangul. Text without Hangul keeps its own breaks. New type and imported text have +it off; paragraphs saved before the option open with it on, the breaks they were laid out with. It is saved with the +paragraph (`korean_line_break_anywhere` in `para`) only when off, paragraph styles carry it (Paragraph Style Options › +East Asian Composition Settings), and Reset Panel turns it off. A value that is not true or false is refused. One undo +step. `.ai` editing data does not hold it, and a save reports a Korean paragraph with it on as left out. The +help page: https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/set-line-breaks-korean-text.html + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"koreanLineBreakAnywhere":true}}} +``` + ## Hanging punctuation (burasagari) `text.setFormat {burasagari: "none"|"standard"|"forced"}` sets the Paragraph panel menu's Burasagari (None / Regular / @@ -7241,6 +7972,79 @@ begins or ends, dragging the centre bracket slides the type along its path and, {"name":"run_command","arguments":{"command":"type.pathOptions","params":{"start":0.25,"end":0.75,"flip":true}}} ``` +`type.pathCenter.top {ids?|id?}` and `type.pathCenter.bottom {ids?|id?}` (Type › Type on a Path › Center on Top and +Center on Bottom, and the Contextual Task Bar for type on a closed path) slide the selected type on a closed path along +it so that the middle of the span between its brackets lands on the path's topmost or bottommost point. This is +VectorCraft's own behavior. The path is measured as the object is drawn, after its transform, so a rotated, scaled or +skewed circle centers on its drawn top. On a level stretch, such as a rectangle's top edge, the middle of the stretch +is used; with several separate topmost points, the middle of the shortest part of the path that holds them all is +used. The span keeps its length, and type that runs once round stays once round. The first paragraph's alignment +becomes Center unless it is Center or Justify Center, so the type is centered there. The type is not flipped: on the +bottom of a circle, whose path runs clockwise, it reads upside down outside the circle until `type.pathOptions {flip: +true}` turns it inside. Point type and area type in the selection are left as they are. Type on an open or compound +path, type in a thread, and type on a path with no length or no height are refused with an error that names them, +and nothing changes. The menu items are enabled, and the task bar shows them, only while every selected type on a +path is on one closed path and none of it is in a thread. Several objects move in one undo step. When every object is +already centered there, nothing changes and no undo step is recorded. Each replies `{ids, start, end}` with the first +object's brackets. + +```json +{"name":"run_command","arguments":{"command":"type.pathCenter.top","params":{}}} +``` + +## Dynamic Text + +`type.dynamicText {on?: bool, ids?}` (Type › Dynamic Text, and the Contextual Task Bar for type on a path) turns +Dynamic Text on or off for the selected type on a path; without `on` it sets the opposite of the first object's +setting. With Dynamic Text on, the text spans the stretch between its start and end brackets and its size follows +the text, growing or shrinking to fill it, and it fits again after each edit to the text and each move of a bracket +([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), +[start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). +The rest of this entry is VectorCraft's own rules. The layout scales every character's size, leading, baseline shift +and tate-chu-yoko offsets by one factor, so runs keep their proportions; Type on a Path Options › Spacing is not +scaled. The first character's size, in document points, moves in steps of 0.1 pt within 0.1 to 1,296 pt; text that +still runs past the end bracket at 0.1 pt overflows. Reshaping or scaling the path fits the text again. The stored +sizes do not change: turning Dynamic Text off writes the sizes the text was drawn at into its characters, so it keeps +its look, in one undo step. Point type in the selection is left as it is, and area type in it takes Block +([Dynamic Text: Block](#dynamic-text-block)). Type on a path in a +thread is refused with an error that names it, and the menu item and the task bar item are not offered for it; +`text.thread.create` and `text.thread.add` turn Dynamic Text off on the frames they thread, at their drawn sizes, and +list them in `dynamicTextOff`; `addon.type.releasePath` turns it off at the drawn sizes on the point type it makes. When every object already has the setting asked for, nothing changes and no undo step +is recorded. It replies `{on, ids, fitScale}` (the first object's factor, 1 when off), and the menu item is checked +while the first selected type on a path or area type has it on. `document.inspect` reports `dynamicText` and `fitScale` for type +on a path. New type and documents from before it have it off, and it is saved only when on. SVG, PDF, EPS, legacy +`.ai` and the editing data for other apps write the type at its drawn sizes; legacy `.ai` and the editing data do not +hold the setting, and each says so in a warning. + +```json +{"name":"run_command","arguments":{"command":"type.dynamicText","params":{"on":true}}} +``` + +`type.dynamicTextPreset {preset: "circle"|"arch"|"bow", position?: "above"|"center"|"below", flip?: bool, ids?}` +(Type › Dynamic Text Presets › Circle, Arch and Bow) puts the selected point type and type on a path on a new path +of the preset's shape and turns Dynamic Text on, so the text is sized to fill it. Circle puts the text on a circular +path, Arch on an upward-curving path and Bow on a downward-curving one; `position` sets where the text sits against +the path (above, center or below) and `flip` turns its direction +([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)). +The shapes and the rest of this entry are VectorCraft's own rules. The circle is as wide as the text, and the text +runs clockwise round all of it from its bottom. Arch and Bow are a 120° arc of a circle whose chord is as wide as the +text, bulging up or down, and the text runs along it from left to right. The width is, for point type, the length on the +page of the longer side of the text's bounds, and for type on a path the longer side of its path's bounds on the +page, so the same preset again leaves it as it is; the new path is centered where they were, and +the shape is upright on the page when the object is rotated or scaled. Empty point type gets a path four ems of its +first character wide. `position` (omitted: +above) sets Type on a Path Options › Align to Path: above is Descender, center is Center and below is Ascender. +`flip: true` then turns the text to the other side of its path, running the other way, as Type on a Path Options › +Flip does. Type on a Path Options › effect and Spacing stay as they are, and Type on a Path Options, the brackets and +Type › Dynamic Text change the result afterwards. Area type in the selection is left as it is; with no point type +or type on a path selected the command refuses with `` select point type or type on a path ``, and type on a path in +a thread is refused as `type.dynamicText` refuses it. A preset that would leave every object as it is records no +undo step. It replies `{ids, fitScale}` (the first object's factor). + +```json +{"name":"run_command","arguments":{"command":"type.dynamicTextPreset","params":{"preset":"arch","position":"center"}}} +``` + ## Paragraph attributes per paragraph Each paragraph (text split at `\n`) has its own alignment, indents, space before and after, hyphenation, @@ -7252,7 +8056,10 @@ touches (a caret, `start == end`, touches its paragraph). Without a range they c targeted objects, as before. With a range, the character attributes of `text.setStyle` and `text.setFormat` style that range of characters. When every paragraph that `text.tabs.set` or `text.tabs.clear` targets already has those stops, the command changes nothing and records no undo step. `text.tabs.set` rejects a supplied `align`, `leader`, or -`alignOn` value that is not a string, and an empty `alignOn` value. +`alignOn` value that is not a string, an empty `alignOn` value or one of more than one character, a leader of more than +8 characters, a position outside 0 to 100000 pt, and more than 256 stops unless every paragraph it targets already +holds at least that many, so stops can be removed from a paragraph that holds more. It sorts the stops by position and +keeps the first of stops at one position. `text.tabs.get {start?}` and `paraStyle.new` / `paraStyle.redefine {id, start?}` read the paragraph at `start`; `paraStyle.list` counts paragraphs as uses, and `charStyle.list` counts runs; both count the type in @@ -7269,7 +8076,7 @@ is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The document's styles and the type that uses them keep their attributes, and the file's Normal styles are not loaded. The reply lists the names `added` and `existing` in the document and the names `skipped` in the file (a style whose -attributes do not read or are out of the range `charStyle.new` takes, or whose name is empty); `textStyle.loadAll` +attributes do not read or are out of the range `charStyle.new` or `paraStyle.new` takes, or whose name is empty); `textStyle.loadAll` replies `{charStyles, paraStyles}`, and `charStyle.load` and `paraStyle.load` list only the styles of their own kind. A Return the Type tool types (or `text.editRange` inserting `\n`) continues the style of the paragraph it splits; deleting a break keeps the first paragraph's style; `text.setText` gives every paragraph the first one's attributes. Threaded text keeps each paragraph's attributes as @@ -7287,13 +8094,14 @@ Character Style Options uses `charStyle.edit {name, to, attrs}` to replace the n attribute map in one undo step. `to` is trimmed and must be unique. The command updates text using the style while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, -`position`, `underline`, `strikethrough`, `charAlign`, `h_scale`, `v_scale`, `baseline_shift`, `rotation`, -`language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, +`position`, `underline`, `strikethrough`, `charAlign`, `h_scale`, `v_scale`, `baseline_shift`, `tcyUpDown`, +`tcyLeftRight`, `rotation`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, `ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, `ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. Advanced Character Formats holds `h_scale` and `v_scale` (percent, 1 to 10000), -`baseline_shift` (points, -1296 to 1296), `rotation` (degrees, stored from -180 to 180) and `language` (a name or tag from Document +`baseline_shift` (points, -1296 to 1296), the Tate-chu-yoko Settings `tcyUpDown` and `tcyLeftRight` (points, +-1296 to 1296, as `text.setRangeStyle` takes them; an explicit 0 stays distinct from unset), `rotation` (degrees, stored from -180 to 180) and `language` (a name or tag from Document Setup's languages; English: USA stores the explicit default `null`, and a tag not in the list that the style already has is kept). Language sets the language the characters are shaped in; it does not change hyphenation or spelling. @@ -7320,13 +8128,60 @@ Auto leading. An invalid value leaves the style, its text, and Undo history unch The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. -Without selected text, the New Paragraph Style dialog sends no `attrs`, and the engine gives the new style the -paragraph defaults for the interface language. Reset Panel in Basic Character -Formats removes those fields from the definition, Reset Panel in Advanced Character Formats removes its five, Reset +The New Paragraph Style dialog has the sections of Paragraph Style Options, filled in from the selected +paragraph's attributes, or without selected text from the paragraph defaults for the interface language, and OK +sends the attributes of its sections as `attrs`. Reset Panel in Basic Character +Formats removes those fields from the definition, Reset Panel in Advanced Character Formats removes its seven, Reset Panel in Character Color removes its five attributes and Reset Panel in OpenType Features removes `features`. `ui.charStyleOptions.resetPanel {}` performs that reset for the section selected in either character-style dialog; it is disabled on General. +`ui.paraStyleOptions {name}` opens Paragraph Style Options for an existing named style (double-clicking a row of +the Paragraph Styles panel, or Paragraph Style Options… in its menu, does the same). OK runs +`paraStyle.edit {name, to, attrs}`, which takes the same arguments as `charStyle.edit` and replaces the style's +name and attributes in one undo step; the paragraphs that use the style keep their local overrides. OK with no field +changed records no undo step, and Preview updates the paragraphs while the dialog is open (Cancel restores them). +The `paraStyleOptions` dialog exposes `name`, `section` (`general`, `basic`, `tabs`, `composition`, `hyphenation`, +`justification` or `eastAsian`) and `preview`, and these fields: + +- Basic Paragraph Formats: `justify` (`Auto`, `Left`, `Center`, `Right`, `JustifyLeft`, `JustifyCenter`, + `JustifyRight` or `JustifyAll`), and `left_indent`, `right_indent`, `first_line_indent`, `space_before` and + `space_after`, typed in the General unit of Preferences or with a unit of their own. +- Tabs: `tabs`, the style's stops, each `{position, align, leader, alignOn}`: `position` typed like the distances + above, `align` `left`, `center`, `right` or `decimal`, `leader` up to 8 characters, and `alignOn` one character + (used by decimal stops). The section edits the selected stop with Alignment, X: (Y: for vertical type), Leader: + and Align On:. Add puts a left stop 36 pt past the furthest stop (at 36 pt when there is none, and at most at + 100000 pt); it is disabled at 256 stops or when a stop is already at that position. Delete Tab removes the selected + stop, and Clear All Tabs leaves the style with no stops, which it then sets. OK sorts the stops by + position; of two stops at one position it keeps the one edited last. +- Composition: `composer` (`singleLine` or `everyLine`) and the `roman_hanging` checkbox. +- Hyphenation: the `hyphenate` checkbox, `words_longer_than`, `after_first`, `before_last`, `hyphen_limit`, + `hyphenation_zone` and the `hyphenate_capitalized` checkbox. The options are inactive while Hyphenation is off, and + Hyphenation Zone is inactive with the Every-line Composer. +- Justification: `word_min`, `word_desired`, `word_max`, `letter_min`, `letter_desired`, `letter_max`, `glyph_min`, + `glyph_desired` and `glyph_max` (percent), `auto_leading` (percent) and `single_word` (`fullJustify`, + `alignLeft`, `alignCenter` or `alignRight`). +- East Asian Composition Settings: the `korean_line_break_anywhere` checkbox (Korean Composition Settings › Korean + Line Break Anywhere). + +A field left as it was keeps the attribute as the style has it, and an empty field leaves its attribute unset; an +empty Hyphenation or Justification field takes its default while another field of that section is set. Attributes +the dialog does not show, such as character attributes, stay as they are. +`paraStyle.new`, `paraStyle.setAttrs` and `paraStyle.edit` reject a changed indent, space before or space after outside +-1296 to 1296 pt, Words Longer Than outside 1 to 25, After First or Before Last outside 1 to 15, Hyphen Limit outside +0 to 25, Hyphenation Zone outside 0 to 1296 pt, Word Spacing outside 0 to 1000%, Letter Spacing outside -100 to 500%, +Glyph Scaling outside 50 to 200%, Minimum, Desired and Maximum values out of that order, Auto Leading outside 0 to +500%, and changed tabs with more than 256 stops, or with a changed stop whose position is outside 0 to 100000 pt or +whose leader is longer than 8 characters. They sort changed tabs by position and keep the first of stops at one +position. A value the style already has is kept. An invalid value leaves the +style, its paragraphs and Undo history unchanged, and keeps the dialog open. +Reset Panel removes the section's attributes from the definition: Basic Paragraph Formats removes `justify` and the +five distances, Tabs removes `tabs`, Composition removes `composer` and `roman_hanging`, Hyphenation removes `hyphenate` and +`hyphenation`, +Justification removes `justification`, and East Asian Composition Settings removes `korean_line_break_anywhere`. +`ui.paraStyleOptions.resetPanel {}` performs that reset for the section +selected in Paragraph Style Options or New Paragraph Style; it is disabled on General. + In the native file a text object's `para` holds the first paragraph's attributes and `paras` (left out when every paragraph is alike) one entry per paragraph, so older readers keep the first paragraph's. SVG export anchors each centred or right-aligned line on its own (`<tspan text-anchor>`), and SVG import gives each line's paragraph its @@ -7411,13 +8266,15 @@ drawings leave a deferred stage as it is until its input or parameters change, w the active document (`reason`: `budget`, `timeout`, `missing`, `failed` or `safeMode`; `item` is the fill or stroke whose effect it is; `objectId` can be an object in the art of a symbol, pattern, brush or opacity mask; an empty list when none is deferred). A stage whose object is deleted, or whose plug-in effect is -removed, moved from its place in the list or hidden (or whose fill or stroke is hidden), is no longer listed. `effect.refreshDeferred {ids?}` (Effect › Refresh +removed, moved from its place in the list or hidden (or whose fill or stroke is hidden), is no longer listed. `effect.refreshDeferred {ids?|id?}` (Effect › Refresh Deferred Effects, enabled while a stage is deferred) runs the deferred stages of those objects (default: all of them) again with a fresh 2,000 ms budget and returns `{refreshed, stillDeferred, failed}`: `stillDeferred` counts stages left out for want of time again, the stages of an object that is hidden or in a hidden group or layer, which is not drawn, and the stages with a part of their input too small for the drawing the refresh makes, and `failed` those that timed out, failed or have no plug-in. `id` names one object in place of -`ids`, and an entry that is not an object id of the document is an error. Each document has its own budget and its own deferred stages. Exports, Expand +`ids`. An entry can name an object in the document's layers or in the art of a symbol, pattern, brush or opacity mask; +an object without a deferred stage adds nothing to the counts, and an entry that is not an object of the document is +an error. Each document has its own budget and its own deferred stages. Exports, Expand Appearance and commands run every stage under the per-call limit, so an export never leaves out a stage that was only deferred for time, and the canvas then draws the result. The web build measures the budget and the per-call limit with the page's `performance.now()`. An exporter adds a write-only file format `plugin.<id>` (listed by `document.formats`): @@ -7443,7 +8300,12 @@ runs it where it is called, so the call may take minutes; `notifications/cancell A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, -`ui.dialog.confirm` and injected input can't confirm it. A `vectorcraft-cli mcp` started with `--allow-plugin-grants` +`ui.dialog.confirm` and injected input can't confirm it. Its OK takes input only once the question has been on screen +in the focused window for half a second, counted again for every new question and after the window gets the focus +back. A question that a request asked, directly or through a file dialog it opened, can't be approved by the person +either: the reply adds `approval: "personMustStartInstall"`, OK stays disabled, and the person installs the plug-in +with Object › Plug-ins › Install Plug-in… themselves. A request's `replace: true` doesn't skip the question about +taking another module's place. A `vectorcraft-cli mcp` started with `--allow-plugin-grants` accepts `grant` and `allowHeavy` from any request, in that session only (headless; it can't be combined with `--connect`, `--automation-read-root` or `--automation-write-root`). A server confined to folders has no plug-in store, so it reads no `grants.json`, and a module that lists permissions or asks for a heavy budget does not install @@ -7456,18 +8318,22 @@ with other bytes has `needsApproval: true` and needs a new one even when it list forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When -`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed. A +`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed. +When the plug-in's settings and cache can't be moved back from their `.removed` folder then either, the error names +that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A filter without `doc.write` or `state` that returns output needing them gets an error and the document is unchanged. A plug-in of API level 2 (`api: 2` in its entry) that lists `progress` may report its progress, see Cancel and write log lines: `notifications/cancelled` makes its `vc_cancelled` return 1, and its log lines go to the server's log -under its id. One that lists `settings` or `cache` keeps settings or a cache of its own in the `Plug-ins` folder +under its id. With a desktop app connected, `plugin.dialog` runs such a filter (one without a `commandAllowlist`) in the +background when it runs at once or OK runs it with Preview off, and returns `{background: true, status}`; +`plugin.cancelRuns` stops it. One that lists `settings` or `cache` keeps settings or a cache of its own in the `Plug-ins` folder (VectorCraft's own caps: 256 settings and 1 MiB, 512 MiB of cache): `plugin.list` and `plugin.info` give the cache's size as `cacheBytes`, `plugin.clearCache {id?}` empties the cache of one plug-in or of all of them and returns `{cleared: [id], bytesFreed}`, replacing a plug-in keeps both, and `plugin.remove` deletes both (also for an id that isn't installed but still has them). Files it can't delete stay in the plug-in's folder renamed with `.removed`, where no plug-in reaches them. A later `plugin.remove` tries again to delete them when a plug-in with that id is installed or -a storage folder for the id exists, and that deletion can fail too; for an id with only a `.removed` folder it does -not ([plugins.md](plugins.md#settings-and-cache)). A module with other bytes than the plug-in installed with its id, or, with none +a storage folder for the id exists, and that deletion can fail too; for an id with only such a folder (marked by a +`.delete` file beside it) it does not ([plugins.md](plugins.md#settings-and-cache)). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has settings or a cache in the `Plug-ins` folder (`needsReplace: true` in its `plugin.inspect` entry), installs only with `replace: true`: ask the user first, since it takes that plug-in's place and gets its settings and cache. Without it, `plugin.install` returns @@ -7506,7 +8372,9 @@ pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled { off for the next launch, as Help › Safe Mode's Enable on Re-launch does; it does not load, unload or uninstall anything now, and `plugin.install` of a disabled plug-in turns it on. Turning a plug-in on by `id` or by installing it also turns on the file it is stored in, which names it when it stopped a launch while loading; when the new version can't be saved -over that file, the plug-in stays disabled. `plugin.list` reports `safeMode` and `disabled`, and +over that file, the plug-in stays disabled. When the new version is saved but its grant can't be, and the file can't be +returned to what it held before (the old module, or no file), the plug-in is turned on, and the next launch skips it +until it is approved. `plugin.list` reports `safeMode` and `disabled`, and `plugin.reload` skips disabled plug-ins. A change to the disabled list is saved on top of the list the file holds at that moment, so a change another window saved to the same preferences meanwhile is kept. When the list file can't be read (it is too large) or holds another format or version, it is left as it is; a file that isn't JSON is replaced. @@ -7800,6 +8668,20 @@ share of the content's width or height in proportion to the length of its contro its curve parameter, so content spreads evenly along a segment without handles. An envelope opened from an `.ai` file keeps the corners the file saves, and they stay on the same anchors when the envelope is moved, rotated or reflected. These are VectorCraft's own rules, and existing top-object envelopes redraw by them. +A warp bends the content's bounds as one Bézier patch. The style sets the patch's control points from the bend and +the size of the bounds (Arc's top and bottom edges, for example, are cubic curves close to arcs around one center), then +the horizontal distortion scales each column of control points about its middle, and the vertical distortion scales +each row. Content with no width or no height takes the middle of the patch along that side. New warp envelopes, and +those opened from `.ai` files, carry `version` 1 for this map, and `object.envelope.info` reports it. Envelopes in +`.vectorcraft` documents saved before the version existed read as `version` 0, the earlier map, and keep their look, +and editing an envelope keeps its version. `version` (0 or 1) on `object.envelope.makeWithWarp`, +`object.envelope.resetWithWarp` and `object.envelope.options` sets the map. The Warp effects (`warp.arc` … +`warp.twist`) take the same map through the same `version` param: `effect.apply` gives a new Warp `version` 1 unless +`params.version` is 0, the built-in graphic styles' Warps have 1, and Effect › Warp edits keep each Warp's own version. +These commands refuse any other value with `` `version` must be 0 or 1 ``; `1.0` counts as 1. An `.ai` file holds a +warp's settings and not its version, so a `version` 0 warp saved to `.ai` and opened again draws with `version` 1. +These patches are VectorCraft's own rules; the styles and the ranges of Bend and the distortions are those of the Warp +options (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). `object.envelope.info` reads the selected envelope's settings (`type`, the warp's or mesh's values, `fidelity` and the options, `editing`), or with no envelope selected the options new envelopes get. With an envelope selected, `object.envelope.resetWithWarp` and `object.envelope.resetWithMesh` (`rows`, `cols`, `maintainShape`: true keeps @@ -7835,8 +8717,14 @@ laid-out box, and so does type inside any other object, such as a blend, a repea VectorCraft's own rule, and envelopes of type in saved files redraw by it. Everything inside bends with the envelope: images as a raster mesh warp (cut into pieces by Fidelity, each a clipped image under its own affine map; SVG shares the pixels between the pieces), symbol instances as their symbol's art, -and with Distort Appearance strokes (as their filled outlines) and geometry effects; with it, Distort Linear Gradients -bends linear gradients and Distort Pattern Fills the pattern tiles. A transformed envelope keeps its warp in its own +and with Distort Appearance the strokes of paths (as their filled outlines) and geometry effects; with it, Distort +Linear Gradients bends linear gradients and Distort Pattern Fills the pattern tiles. Type's strokes (its characters' +and those on its own appearance) don't bend, with Distort Appearance or without: they paint along the bent glyph +outlines at their own weight, as `.ai` files draw type in an envelope, so a squeezed or stretched envelope keeps them +as wide as they are, also in an envelope inside an envelope (#6644). Their geometry effects and an opacity mask on +the type still bend, and Expand gives the bent outlines with the strokes on them, which Object › Expand or Outline +Stroke outlines later. Before #6644, VectorCraft bent type's strokes too, so envelopes of stroked type made earlier +now draw their strokes at their own weight. A transformed envelope keeps its warp in its own frame (`kind.frame` in `document.inspect`; rotating a warp envelope turns the warp with it), and move and scale keep it square to the page. @@ -7975,7 +8863,8 @@ keys without bounds make 1 step. `starts` gives, per object, the anchor of its f from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). With the Blend tool, `press_key` Escape drops the object clicked first and stops the next click adding to the blend just made; the document and the selection stay as they are. A blend -among the objects takes the others in as more key objects, keeping its options, name and transparency: +among the objects takes the others in as more key objects, keeping its options, name, transparency and whether it +has a spine: ```json {"name":"run_command","arguments":{"command":"object.blend.make","params":{"ids":[12,15],"starts":[0,2],"steps":8}}} @@ -7983,6 +8872,23 @@ among the objects takes the others in as more key objects, keeping its options, {"name":"run_command","arguments":{"command":"object.blend.info","params":{}}} ``` +`object.blend.createSpine {mode?: "auto" | "always" | "never"}` is the Blend panel's Create Spine menu: whether new +blends get a spine (the [help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) +describes the three choices). Without `mode` it reads the setting; both return `{mode}`. Auto, the default, and Always +give every new blend a straight spine between the key centers, as before, whatever its key objects are. Never makes blends without a spine: their steps sit where a straight spine puts them, and +`object.blend.info` reports `hasSpine: false` and no `spine`. Such a blend has no easing (`easingType` and `ramp` are +refused, and the Blend panel dims Type and Ramp), Reverse Spine and the `object.blend.spine.*` commands refuse it +("the blend has no spine"), and Release gives back its keys with no spine path. Replace Spine gives it a spine. The +setting is kept with the preferences, is not an undo step and does not change blends already made, and +`object.blend.make {createSpine}` chooses for one new blend. Any other value is refused ("`mode` must be one of auto, +always, never") and changes nothing. A blend saved without a spine keeps `noSpine` in the native file; `.ai` and +EPS files hold its drawn steps, as they do for every blend: + +```json +{"name":"run_command","arguments":{"command":"object.blend.createSpine","params":{"mode":"never"}}} +{"name":"run_command","arguments":{"command":"object.blend.make","params":{"ids":[20,31],"createSpine":"always"}}} +``` + With the Blend tool active, `tool.select {tool: "blend"}` finishes the blend, as a click on the tool's button or W does: it drops the object clicked first and stops the next click adding to the blend just made. The document and the selection stay as they are. Choosing any other tool that is already active leaves its work as it is. @@ -7993,7 +8899,7 @@ the spine passes nearest, `object.blend.spine.moveAnchor {anchor, x, y}` moves a `handle: "in" | "out"` it places that handle), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment so its point at `t` moves by (dx, dy), turning a straight spine into a curve (`perpendicular` works as in `path.reshapeSegment`), and `object.blend.spine.removeAnchor {anchor}` deletes a point no key sits on; the first edit turns the spine into a path. Moving a key moves its end of the spine. Release -(`object.blend.release`) leaves the spine as a path that paints nothing (`spines` in the result): +(`object.blend.release`) leaves the spine of a blend that has one as a path that paints nothing (`spines` in the result): ```json {"name":"run_command","arguments":{"command":"object.blend.spine.addAnchor","params":{"id":40,"x":150,"y":100}}} @@ -8073,6 +8979,18 @@ than the end. With Alt (Option on macOS) held, the objects spread from both ends open path, or of the first anchor of a closed path, up to the whole path. With measurement labels on, the distance between the objects shows next to the pointer in the document's units. Escape cancels the drag. +When the objects have room to move along the path, the same tools show the Move All widget, a diamond below the +group's first object joined by a line to its attachment point. On an open path that is when the distance from the first +object to the last is shorter than the path: one object, or a Space value that leaves part of the path free, but not +Auto from the first anchor, which spreads the objects to both ends. On a closed path the widget always shows. Dragging +it moves every object along the path as far as the pointer moves along the path, keeping the distances between them, +and previews `object.objectsOnPath.options {ids: [group], start}` and keeps it as one undo step on release. On an open +path the objects stop where the first one reaches the first anchor or the last one reaches the end, and moving the +pointer back moves them back at once; on a closed path they go on round across the first anchor. Where Auto or a Space +value the open path is too short for sets the distance, the drag also sets `spacing` to the distance as drawn, so the +objects stay that far apart. Shift and Alt do not change the drag. With measurement labels on, the first object's +distance along the path shows next to the pointer in the document's units. Escape cancels the drag. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"objectsOnPath","values":{"pivot":7,"rotate":30}}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} @@ -8600,6 +9518,60 @@ whole points and Escape cancels. A drag keeps a Contour's own corners and miter options `corners` and `miterLimit` (`tool.setOption`). A border with a gap is two Contours of one shape (the gap first, so it ends up in front), baked with `effect.expandAppearance`, then `object.pathfinder.minusFront`. +## Cutting Tools add-on + +Cutting Tools is a built-in add-on that prepares art for cutting. Its command is `addon.cutting.bridges`; in the desktop +app it is Object › Plug-ins › Cutting Tools › Stencil Bridges…. + +### Stencil Bridges + +`addon.cutting.bridges` cuts bridges out of the selected art so that a stencil cut from it holds together. An island is +an area the art encloses, such as the inside of an O, A or 8 or a hole in a shape; cut out of a sheet, it would fall +away. A bridge is a strip of the sheet left uncut across the art, which keeps the island attached +([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). The rules below are VectorCraft's own. + +- The art is measured by the area its outlines enclose, whatever their paint: paths and compound paths with their fill + rule (open paths closed as a fill closes them), groups by their members, and type by its glyph outlines. Hidden + objects, and the members of hidden groups, are left out. The type object itself is not converted. An outline that + encloses less than the square of the curve tolerance (below) counts as part of the area around it. +- Every island is joined to the area around the art, directly or through another island, by the shortest crossings + that fit (among crossings of about the same length, the one nearest the middle of the island). Then each island gets + more bridges, up to `count`: each at least two widths from the island's other bridges and no longer than twice the + shortest crossing a bridge fits plus `width`. An island too narrow for a strip `width` wide gets no bridge, and islands that a + bridge could join only to each other and not to the sheet get none either. `unbridged` counts the islands the cut + result still encloses. +- The result is one compound path (a plain path when one outline is left) with the strips cut out of its outlines, + painted as the topmost selected shape, in the place of the topmost selected object that has outlines. It is selected. + Selected objects with no outlines in the art, such as hidden objects or type holding only spaces, stay where they are. +- With `keepOriginal` the selected objects that make up the art move to a new hidden layer named "Stencil Original" + ("Stencil Original 2" and so on when that name is taken), above the other layers, in their stacking order and outside + the groups that held them; with false they are replaced. +- Art with no islands, or with islands that no bridge of the width fits, is left as it is: the result carries a + `warning` and no undo step is made. Otherwise the run is one undo step, with a `warning` when the cut result still + encloses some islands. +- Curves are followed in straight segments within a twentieth of `width` (0.002 to 0.25 pt); a curve that would need + more than 4096 segments gets a larger tolerance. Art that reaches more than 10000000 pt from the origin or has more + than 200000 anchors is refused before it is combined. Art is also refused when its combined area has more than 4000 + outlines, when its outlines need more than 200000 straight segments, and when finding which outlines lie inside + which, or measuring the crossings until every island is joined, takes more work than a fixed budget allows. When the + budget runs out while extra bridges are being added, the bridges found so far are kept. + +| Parameter | Values (default) | +|---|---| +| `width` | each bridge's width, 0.01 to 1000 pt, as a number of points or a string with a unit such as `"2 mm"` (2) | +| `count` | the bridges each island gets, a whole number from 1 to 16; fewer where it has no room, and more where other islands are joined to the sheet through it (1) | +| `direction` | `vertical`, `horizontal`, or `shortest` (the shortest crossing among 12 directions 15° apart) (`vertical`) | +| `keepOriginal` | true; false replaces the selected art | + +→ `{id (the new path, or null), islands, bridges, unbridged, original (the hidden layer's id, or null), warning?}`. +Stencil Bridges… opens the command dialog (`ui.paramDialog`) on Width, Count, Direction (Vertical, Horizontal, Shortest +Crossing) and Keep Original. + +```json +{"name":"run_command","arguments":{"command":"addon.cutting.bridges","params":{"width":"2 mm"}}} +{"name":"run_command","arguments":{"command":"addon.cutting.bridges","params":{"width":3,"count":2,"direction":"shortest","keepOriginal":false}}} +``` + ## Color Effects add-on Color Effects is a built-in add-on: its effects are colour adjustments in Effect › Color Effects, its command is @@ -8881,6 +9853,54 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` +## Image Tools add-on + +Image Tools is a built-in add-on for placed images: its command is `addon.image.removeBackground`, and in the desktop +app it lives in Object › Plug-ins › Image Tools. It is a VectorCraft addition. + +### Remove Background + +`addon.image.removeBackground` makes the background of the selected images, or of the images in `ids`, transparent by +lowering the alpha of their own pixels. The work runs in the app, and no service or model is used. + +- With `background: "edges"` (the default), the background is the most common color along the image's edges. When the + edges hold at least as many clear pixels as pixels of that color, as after an earlier run, nothing is cleared. +- With `background: "corners"`, the background is the average color of the image's four corner pixels. A clear corner + is left out of the average, and when all four are clear, nothing is cleared. +- With `background: "colors"`, the background is the colors in `colors`. `colors` lists 1 to 16 colors, as an array or + as one string split by commas or spaces. Each is written as other color params take a hex color (`#rrggbb` or `#rgb`, + with or without the `#`) or named black, white, red, green or blue. +- With `contiguous: true` (the default), the background is cleared only where it reaches in from an edge, so the same + color inside the subject stays. With `contiguous: false`, it is cleared wherever it is. +- `tolerance` (0 to 100, default 10) is how near a pixel's color must be to a background color to be cleared, as a + percentage. With `match: "distance"` (the default), it is a percentage of the RGB distance from black to white. With + `match: "channels"`, it is a percentage of 255 steps on the one of red, green and blue that differs most, so a + tolerance of `t / 255 × 100` clears the colors within `t` 8-bit steps on every channel. `softness` (0 to 100, + default 10) is the band past the tolerance over which pixels fade from cleared to kept. These ranges and defaults + are VectorCraft's own. +- A value outside 0 to 100, a `background` other than `edges`, `corners` or `colors`, a `match` other than `distance` + or `channels`, a `contiguous` that is not true or false, or a `colors` that lists no color, more than 16, or one that + is not a color or has an alpha part is refused, and the document stays as it was. + +The result stays an image, embedded as a PNG with an alpha channel and the source's color profile and resolution. An +image of 16-bit samples keeps 16 bits, a grayscale image stays gray, and a linked image is embedded. All the images +change in one undo step, and an image that `ids` names twice changes once. An image whose pixels do not change is left +as it is, and when none changes the command adds no undo step and returns `changed: 0`. `cleared` counts the pixels +made fully clear in the images that changed. The command refuses, and changes nothing, when an image is CMYK, a linked +image shows its preview (embed or relink it first), an image would need more than the decode allowance while it is +worked on (2 GiB, or 512 MiB in the web app, counted from the file's header before it is decoded), or every pixel of an +image would be cleared. Remove Background… opens the command's dialog with Preview off; with Preview on, the canvas +shows the result for the values in the dialog, and Cancel puts the image back. While a dialog previews the command, +the session keeps the decoded pixels of the images it changes (at most 128 MiB, or 32 MiB in the web app), so the next +preview step does not decode them again; it releases them when the dialog closes with OK or Cancel. A run that is not +a preview step does not keep them. +→ `{changed, ids, cleared}` + +```json +{"name":"run_command","arguments":{"command":"addon.image.removeBackground","params":{"background":"colors","colors":["#ffffff","#f0f0f0"],"tolerance":5,"softness":15}}} +{"name":"run_command","arguments":{"command":"addon.image.removeBackground","params":{"background":"corners","contiguous":false,"match":"channels","tolerance":12.55,"softness":0}}} +``` + ## Type Tools add-on Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and @@ -8922,7 +9942,9 @@ VectorCraft addition and changes no parity score. - **The text** keeps its runs with their character attributes and its paragraph attributes, and becomes point type on one straight line along the object's own axis, with the baseline starting where the first character sat on the path (type with no characters starts at its start bracket). Type on a Path Options (effect, align to path, spacing, flip, - brackets) don't apply to point type and are dropped. Without `keepOriginal` the type object itself becomes the point + brackets) don't apply to point type and are dropped. Type with Dynamic Text on (`type.dynamicText`) becomes point + type with it off, at the sizes it was drawn at: each size, leading and baseline shift is multiplied by the fit factor. + Without `keepOriginal` the type object itself becomes the point type, keeping its id, so a frame of threaded text leaves its thread with the text it holds, as `type.convertToPointType` does for area type. - It acts on the type on a path among `ids` (or `id`, else the selection), groups included; other objects are left diff --git a/docs/plugins.md b/docs/plugins.md index 06fd89f28a..f616479167 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1,9 +1,9 @@ # Plug-ins: the WebAssembly plug-in API (ABI v1) VectorCraft does not host native plug-ins built for other illustration apps: that needs unsafe FFI into -arbitrary machine code and cannot work in the browser build. Instead, plug-ins are **WebAssembly modules** -run in a sandbox. One `.wasm` file works on macOS, Windows, Linux and the web. The design follows PhotoCraft's -plug-in API (same sandbox, same manifest and parameter schema), extended for vector documents. +arbitrary machine code and cannot work in the browser build. Instead, plug-ins are **WebAssembly modules** run in a +sandbox. One `.wasm` file works on macOS, Windows, Linux and the web. The design follows PhotoCraft's plug-in API (same +sandbox, same manifest and parameter schema), extended for vector documents. There are four kinds of plug-in: @@ -20,8 +20,8 @@ There are four kinds of plug-in: paths and compound paths. File › Open lists their files, File › Open With lists the importers by name, and the host hands them the file's bytes. -This page is the contract for plug-in authors and the reference for the host (`crates/plugins`, the -`plugin.*` commands in `crates/engine/src/cmd/plugin.rs`). +This page is the contract for plug-in authors and the reference for the host (`crates/plugins`, the `plugin.*` commands +in `crates/engine/src/cmd/plugin.rs`). ## Using plug-ins @@ -44,14 +44,15 @@ An exporter adds a write-only format, `plugin.<id>`, which `document.formats` li its extensions that no built-in format has; `selectedOnly` hands it the selection, as for the built-in formats. An importer adds a read-only format, `plugin.<id>`, which `document.formats` lists with its `plugin` id. `openExtensions` -holds the extensions File › Open opens with the importer (the lists below describe which are left out). `document.open {"path"}` (or `{"name", "dataBase64"}`) opens a file with it when no built-in format -reads the file, by its content or by its extension, and the importer lists the file's extension; when several do, the -one whose id sorts first opens it. `document.open {"importer": "plugin.<id>", "params"?: {…}}` names the importer, -which must list the file's extension, also one a built-in format reads (an importer that lists `svg` opens an `.svg` -only this way). A damaged file of a built-in format reports that format's error, and the file is not handed to an -importer. The importer's objects become a new document whose artboard is their bounds (at least 1 pt wide and high, -and within ±4,000,000 pt); the document keeps no path, so Save asks for a name. File › Place reads only the built-in formats, and a file only an importer reads opens as a new document when it is dropped on the canvas. These rules are -VectorCraft's own. +holds the extensions File › Open opens with the importer (the lists below describe which are left out). `document.open +{"path"}` (or `{"name", "dataBase64"}`) opens a file with it when no built-in format reads the file, by its content or +by its extension, and the importer lists the file's extension; when several do, the one whose id sorts first opens it. +`document.open {"importer": "plugin.<id>", "params"?: {…}}` names the importer, which must list the file's extension, +also one a built-in format reads (an importer that lists `svg` opens an `.svg` only this way). A damaged file of a +built-in format reports that format's error, and the file is not handed to an importer. The importer's objects become a +new document whose artboard is their bounds (at least 1 pt wide and high, and within ±4,000,000 pt); the document keeps +no path, so Save asks for a name. File › Place reads only the built-in formats, and a file only an importer reads opens +as a new document when it is dropped on the canvas. These rules are VectorCraft's own. In the app, installed filters appear under **Object › Plug-ins**, next to **Install Plug-in…** and **Reload Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with @@ -60,25 +61,23 @@ of numbers and colors, labelled, explained and sorted into sections as its manif parameters it runs at once. Edit › Keyboard Shortcuts lists each installed filter under Object › Plug-ins, where it can be given a shortcut (`plugin:<id>`); the shortcut stays saved while the plug-in is removed and applies again when it is reinstalled. Parameters too many for the window's height scroll inside the dialog, which keeps its -heading and buttons in view. Exporters are formats of **File › Export › Export As**, where Use -Artboards is greyed out (the plug-in writes the whole document); one with parameters asks for them in a dialog of the -same kind once the file is picked, and its Export button writes the file. Importers' files are listed under File › -Open's "All readable files" and under a filter of their own, named after the importer (other open dialogs, such as New -from Template and Load Styles, list only the files the built-in formats read). These lists leave out an importer's -extensions that a built-in format reads, and those File › Open installs, imports or loads as something else (`.wasm`, -`.kys`, `.jsx`, presets, libraries and swatch or graphic style libraries such as `.ase`). File › Open does not give -those files to the importer, and Open With does. **File › Open With** lists the -installed importers by name (`file.openWith {"importer", "path"?, "params"?}`), and each opens a file picked among its -extensions with that importer (on the web, File › Open's picker opens instead) and adds it to Open Recent. On the -desktop the importer runs off the UI thread, and a run that takes a while shows a progress window with Cancel, which -stops it. An importer -with parameters, given no `params`, asks for them in a dialog of the same kind once the file is picked, and its Open -button opens the file; File › Open runs an importer with its parameters' defaults. Open Recent opens a file the way -File › Open does: it does not remember the importer or the parameters given to Open With. A built-in format reads the -file if one can, and otherwise the first importer by id that lists its extension reads it with its parameters' defaults. -**File › Open** of a `.wasm` file installs -a plug-in too (on the web this is how plug-ins get in). A heavy filter asks before it is installed, and runs in the -background ([below](#heavy-filters)). A plug-in that lists permissions asks for them before it is installed +heading and buttons in view. Exporters are formats of **File › Export › Export As**, where Use Artboards is greyed out +(the plug-in writes the whole document); one with parameters asks for them in a dialog of the same kind once the file is +picked, and its Export button writes the file. Importers' files are listed under File › Open's "All readable files" and +under a filter of their own, named after the importer (other open dialogs, such as New from Template and Load Styles, +list only the files the built-in formats read). These lists leave out an importer's extensions that a built-in format +reads, and those File › Open installs, imports or loads as something else (`.wasm`, `.kys`, `.jsx`, presets, libraries +and swatch or graphic style libraries such as `.ase`). File › Open does not give those files to the importer, and Open +With does. **File › Open With** lists the installed importers by name (`file.openWith {"importer", "path"?, +"params"?}`), and each opens a file picked among its extensions with that importer (on the web, File › Open's picker +opens instead) and adds it to Open Recent. On the desktop the importer runs off the UI thread, and a run that takes a +while shows a progress window with Cancel, which stops it. An importer with parameters, given no `params`, asks for them +in a dialog of the same kind once the file is picked, and its Open button opens the file; File › Open runs an importer +with its parameters' defaults. Open Recent opens a file the way File › Open does: it does not remember the importer or +the parameters given to Open With. A built-in format reads the file if one can, and otherwise the first importer by id +that lists its extension reads it with its parameters' defaults. **File › Open** of a `.wasm` file installs a plug-in +too (on the web this is how plug-ins get in). A heavy filter asks before it is installed, and runs in the background +([below](#heavy-filters)). A plug-in that lists permissions asks for them before it is installed ([below](#permissions)). ### Commands @@ -117,9 +116,9 @@ the object is drawn as if the effect weren't there, and the record is kept for w ## The sandbox -The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssembly interpreter -(MIT OR Apache-2.0). It builds for `wasm32-unknown-unknown` too, so plug-ins also run in the web build. Limits -(`vectorcraft_plugins::Limits`, defaults): +The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssembly interpreter (MIT OR Apache-2.0). It +builds for `wasm32-unknown-unknown` too, so plug-ins also run in the web build. Limits (`vectorcraft_plugins::Limits`, +defaults): | Limit | Default | On violation | |---|---|---| @@ -155,15 +154,15 @@ measured with the page's `performance.now()`. Some filters do heavy but legitimate work, such as routing a plotter's pen, packing shapes onto a sheet or running a simulation, which a minute and 50 M instructions don't cover. Such a filter declares `"budget": "heavy"` in its manifest (only a filter may: a live effect runs whenever the document is drawn, an exporter has an export's budget and -an importer an import's). Each of its runs gets 1 G instructions (20 times a light run's) plus the 4,000 per input byte, and 300 s -(`vectorcraft_plugins::{HEAVY_FUEL, HEAVY_WALL_TIME_MS}`). Its output can't add to the budget: the host learns how -much there is only once the run has ended. +an importer an import's). Each of its runs gets 1 G instructions (20 times a light run's) plus the 4,000 per input byte, +and 300 s (`vectorcraft_plugins::{HEAVY_FUEL, HEAVY_WALL_TIME_MS}`). Its output can't add to the budget: the host learns +how much there is only once the run has ended. - **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, and install it once the user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`, and refuses `allowHeavy` from a request except in a session started with `vectorcraft-cli --allow-plugin-grants` - (`plugin.inspect` shows the budget beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed again - at startup. The Additional Plug-ins Folder skips heavy filters with a note in its report, since loading a folder + (`plugin.inspect` shows the budget beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed + again at startup. The Additional Plug-ins Folder skips heavy filters with a note in its report, since loading a folder asks nobody. - **It runs in the background.** Its dialog has no Preview. OK (or the menu item, without parameters) runs it on a thread of its own while editing goes on, shown in the status bar and, after a moment, in a progress window with @@ -203,16 +202,28 @@ capability model proposed for PhotoCraft plug-ins `state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`. Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` - below 2, or - one of the names kept for a later plug-in API - (`ui.panel`, `ui.tool`) is refused when the module is installed, and the error names it. + below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is + installed, and the error names it. - **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of the file and each permission in plain words, and install it once the user clicks OK, if the file still has the - SHA-256 shown; Cancel installs nothing. The - names shown have control and bidirectional characters escaped (`\u{202E}`) and are cut to 64 characters. - Only a person can press its OK: `ui.dialog.confirm`, MCP's `answer_dialog` and injected input (`ui.key`, `ui.click`) - are refused and the dialog stays open. Enter confirms it only when OK has the keyboard focus. `ui.dialog.set` can't - change what it installs. + SHA-256 shown; Cancel installs nothing. The names shown have control and bidirectional characters escaped (`\u{202E}`) + and are cut to 64 characters. Only a person can press its OK: `ui.dialog.confirm`, MCP's `answer_dialog` and injected + input (`ui.key`, `ui.click`) are refused and the dialog stays open. Enter confirms it only when OK has the keyboard + focus. `ui.dialog.set` can't change what it installs. OK stays disabled until the question has been on screen in the + focused window for half a second (VectorCraft's own value, from the delay the security guidance at + https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/security/security-considerations-for-browser-ui.md + gives for dialog boxes), so a click, Enter or Space, or a press begun before then, installs nothing. The half second + starts over for every new question, even one that reads the same, and when the window gets the focus back. Cancel + and Escape work at once. A module that would take the place of the installed plug-in with its id asks in the same + dialog. +- **An install that automation asked for is not approved in its dialog.** When a control request, MCP, injected input, + or a file dialog that one of them opened (even when the person picks the file there) leads to the approval dialog, its + OK stays disabled, a confirm is refused even after the half second, and the dialog says that automation asked for the + install. `ui.installPlugin` returns `{pending: "pluginInstall", approval: "personMustStartInstall"}`. Cancel still + closes it. To install the plug-in, the person chooses Object › Plug-ins › Install Plug-in… and picks the file, or + opens it with File › Open or drops it on the window: the module is inspected again and the new question waits its + half second. A request's `replace: true` does not skip asking about taking another module's place. A module that + needs no approval still installs at once from any request. This is VectorCraft's own rule. - `plugin.install` refuses the module, naming the permissions it needs, unless this module already has a recorded grant (`plugin.inspect`'s `needsApproval` tells it beforehand). A request's `grant` is refused too: `plugin.install` takes it only with the approval the dialog gives. A `vectorcraft-cli mcp` or `run` started with `--allow-plugin-grants` @@ -226,6 +237,13 @@ capability model proposed for PhotoCraft plug-ins `VECTORCRAFT_NO_PREFS` set there is no store, and a `grant` accepted under the flag lasts for that session only. With `--allow-plugin-grants`, pass `hash` set to the `plugin.inspect` entry's `hash` so that the module installed is the one the user saw. +- The approval protects against plug-ins and automation clients (MCP, scripts and CLI requests): none of them can + approve a module's permissions. VectorCraft's own code records a grant only after that approval and when it loads + `grants.json`, and installs a module that lists permissions only under a grant recorded for this very module, + also when it loads the Additional Plug-ins Folder. The approval does not protect against native code linked into + VectorCraft or against another program running as the same user, which can change the files in the `Plug-ins` + folder. `grants.json` is not signed, so such a program can add a grant to it. `--allow-plugin-grants` is a choice + the person starting a headless session makes. - **Replacing asks first.** When the file is another module than the plug-in installed with its id, or, with none installed, its id has settings and a cache in the `Plug-ins` folder, Install Plug-in… and File › Open show its id and SHA-256 and ask whether to install it in place of that plug-in, which gives it the settings and cache kept for @@ -240,7 +258,9 @@ capability model proposed for PhotoCraft plug-ins records the new hash. When the new module or its grant can't be written to the `Plug-ins` folder, the folder keeps the old module and its grant, and the old module loads at the next start. If the write that puts the old module back fails as well, the folder holds the new module with the old grant, the grant does not cover that module, and the - plug-in is skipped at the next start until it is approved again. A grant whose hash is not 64 lower-case + plug-in is skipped at the next start until it is approved again. When the folder held no module for that id, that + write removes the new module; when the removal fails, the folder holds the new module and no grant covers it. In + both cases a disabled plug-in is turned on, as for any install the folder holds. A grant whose hash is not 64 lower-case hexadecimal digits covers nothing. `plugin.remove` forgets the grant, and so does a successful `plugin.install` of a module that lists no permissions under that id, so the earlier bytes need a new approval. When `plugin.remove` can't remove the grant from `grants.json`, it returns an error, the plug-in stays installed, and a second `plugin.remove` @@ -248,30 +268,31 @@ capability model proposed for PhotoCraft plug-ins write the module to the `Plug-ins` folder, or can't remove the grant from `grants.json`, the folder keeps the module it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be removed and the module already stored can't be read back or written back, the new module stays in the folder, and - the grant does not count for the rest of the session. The grant also does not count when the folder held no module - for that id. A + the grant stops counting. The grant also stops counting when the folder held no module for that id. A `grants.json` larger than 1 MiB, or one that is not a JSON list, grants nothing: the new module stays in the folder, and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no - permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant does not count for - the rest of the session, or until the plug-in is granted again, including for the next load, which tries the removal - again. In Safe Mode, and for - a stored module that the user disabled, + permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant stops counting, + including for the next load, which tries the removal again. A grant that stops counting in either of these cases + does not count for any session in the same process that uses the same `Plug-ins` folder, by any path to it, until + `grants.json` can be written for that plug-in, as when the plug-in is granted again. Another process on the same + folder, for example `vectorcraft-cli` beside the app, still reads `grants.json` as it is written. A grant for the + same id kept in another `Plug-ins` folder counts. In Safe Mode, and for a stored module that the user disabled, VectorCraft does not read the module, and `grants.json` keeps the grant for its id. The Additional Plug-ins Folder and `plugin.reload` do not change the `Plug-ins` folder: when they leave a module that lists no permissions under an id, the process forgets its own grant for that id, and a grant kept in `grants.json` stays with the stored module it covers. An entry of `grants.json` that this version can't use (a permission it doesn't know, an invalid id) is skipped and stays in the file until its plug-in is granted again, replaced by a module that lists no permissions, or removed. When such an entry can't be removed from the file, `plugin.install` and `plugin.remove` treat it as a grant - that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written larger than - 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept - in it count for `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, - a stored plug-in is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins - Folder and `plugin.reload` install only plug-ins that such a grant covers, and report the others. A module without a + that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written + larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for + `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, a stored plug-in + is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins Folder and + `plugin.reload` install only plug-ins that such a grant covers, and report the others. A module without a `permissions` list, or with an empty one, needs no grant. -- The host enforces the grant on a filter run and a command run: without `doc.read` the filter is given no objects; without `state` its - `documentData` is `null` and an output that sets it is refused; without `doc.write` an output that changes the - document is refused. A refused output leaves the document as it was. +- The host enforces the grant on a filter run and a command run: without `doc.read` the filter is given no objects; + without `state` its `documentData` is `null` and an output that sets it is refused; without `doc.write` an output that + changes the document is refused. A refused output leaves the document as it was. - `api` is the plug-in API level the manifest is written for: `1` (the default) or `2`, which adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects). A higher one @@ -282,12 +303,11 @@ capability model proposed for PhotoCraft plug-ins - Parameter declarations are unchanged by permissions (`params`, below). Every run gets a **fresh instance**, so no state survives between calls except what a plug-in writes to its -[settings and cache](#settings-and-cache). Traps, exhausted budgets, malformed -modules, bad manifests, out-of-range pointers, negative return codes and invalid output all become errors, and the -document is left untouched: a filter's output is checked completely before one edit applies it. A live effect that -fails draws the object's geometry unchanged; `plugin.info` reports why (`lastError`). A run that succeeds clears the -error of a failed run. A check that finds every swatch and pattern a painted result names clears only the error of a -refused swatch or pattern. +[settings and cache](#settings-and-cache). Traps, exhausted budgets, malformed modules, bad manifests, out-of-range +pointers, negative return codes and invalid output all become errors, and the document is left untouched: a filter's +output is checked completely before one edit applies it. A live effect that fails draws the object's geometry unchanged; +`plugin.info` reports why (`lastError`). A run that succeeds clears the error of a failed run. A check that finds every +swatch and pattern a painted result names clears only the error of a refused swatch or pattern. wasmi is built with its *portable* (loop) dispatcher: the default tail-call dispatcher relies on LLVM sibling-call optimisation, and when that doesn't happen a long-running module overflows the host stack, which aborts @@ -336,12 +356,16 @@ still returns `1`. `vc_progress`, `vc_cancelled` and `vc_log` need `progress`; t and one the manifest doesn't allow (an `api` below 2, or without the import's permission) refuse the module, and the error names the import and the permission. - A filter's or an exporter's progress is shown as a share: a heavy filter's progress window and the export's progress - window draw a bar with a percentage, and Cancel there makes `vc_cancelled` return `1`. A plug-in that checks it can - stop early, and the host discards what it returns after the Cancel or after its time budget ran out; one that - ignores it is still stopped by the instruction and time budgets. With a known total, a report is passed on only when - it reaches another tenth of a percent; with an unknown total, each change of `done` is passed on. After 2,000 reports - in a run, one change in 1,000 is passed on, and so is the first report after the total becomes known or unknown. A - live effect's progress is not shown, since it is drawn as part of something else. + window draw a bar with a percentage, and Cancel there makes `vc_cancelled` return `1`. In the desktop app a light + filter that lists `progress` runs in the background as a heavy one does, under its light budget, when it runs at once + from Object › Plug-ins or its shortcut, or when OK runs it with Preview off; with Preview on, its dialog keeps the + previewed run. A filter that also lists a `commandAllowlist` runs where it is called, since its command calls need + the document. A plug-in that checks `vc_cancelled` can stop early, and the host discards what it returns after the + Cancel or after its time budget ran out; one that ignores it is still stopped by the instruction and time budgets. + With a known total, a report is passed on only when it reaches another tenth of a percent; with an unknown total, each + change of `done` is passed on. After 2,000 reports in a run, one change in 1,000 is passed on, and so is the first + report after the total becomes known or unknown. A live effect's progress is not shown, since it is drawn as part of + something else. - Log lines go to the app's log (target `vectorcraft_plugins`) as `<plug-in id>: <text>`, with control and bidirectional characters escaped. The whole text must be UTF-8. A line shows its first 1,024 bytes, as at most 1,024 characters with the escapes, and ends with `…` when it is cut. A run writes at most 200 lines and 32 KiB of shown @@ -376,8 +400,7 @@ or modified time differs from the last read or write. A get answered from memory set to the value the key already has writes nothing, and neither does a delete of a key that has no value. A delete of the last setting removes the file and counts no written bytes. Every other successful set or delete writes the file before the call returns. A cache call reads or writes the whole entry in memory in one step, up to 64 MiB, and -the run waits for it. -A live effect runs while the art draws, so keep the entries it uses small. +the run waits for it. A live effect runs while the art draws, so keep the entries it uses small. - A key is 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`, and is not a Windows device name (`CON`, `PRN`, `AUX`, `NUL`, `COM0` to `COM9`, `LPT0` to `LPT9`, in any case). Keys differ in case: `tile` and `Tile` are two. @@ -387,21 +410,27 @@ A live effect runs while the art draws, so keep the entries it uses small. also fails with `-4` when the `cache` folder holds more than 8,192 items; clearing the cache removes every file in it. - The desktop app and `vectorcraft-cli` keep them in a folder named from the id under `storage/` in the `Plug-ins` - folder (ids that differ only in case get two folders): `settings.json` and a - `cache` folder with one file per entry, named by the host. A settings file that is too large or doesn't parse is - moved to `settings.unreadable.json`, replacing an earlier one there, and the settings start empty. A link in that - folder is refused (`-5`). Writes go to a temporary file that then replaces the old one; a temporary file a failed - write leaves in the `cache` folder does not count toward the caps, and clearing the cache removes it. + folder (ids that differ only in case get two folders): `settings.json` and a `cache` folder with one file per entry, + named by the host. A settings file that is too large or doesn't parse is moved to `settings.unreadable.json`, + replacing an earlier one there, and the settings start empty. A link in that folder is refused (`-5`). Writes go to a + temporary file that then replaces the old one; a temporary file a failed write leaves in the `cache` folder does not + count toward the caps, and clearing the cache removes it. - A plug-in reaches only the storage of its own id. Replacing it with another module of the same id - (`plugin.install` with `replace: true`, after the user agreed) keeps the storage; `plugin.remove` deletes it, and a run of the plug-in still going gets `-5` from every storage call after that. - `plugin.remove` first renames the folder (adding `.removed` to its name). When that fails, `plugin.remove` fails - and the plug-in stays installed with its storage as it was. Files that can't be deleted after the rename stay in the - `.removed` folder, where no plug-in reaches them. A later `plugin.remove` tries again to delete them when a plug-in - with that id is installed or a storage folder for the id exists, and that deletion can fail too. For an id that - isn't installed and has only a `.removed` folder, `plugin.remove` does not delete the folder and fails as not found. - `plugin.remove` with the id of a plug-in that isn't installed deletes the storage kept for that id, when there is - any. - `plugin.clearCache` empties the cache and leaves the settings, and `plugin.list` and + (`plugin.install` with `replace: true`, after the user agreed) keeps the storage; `plugin.remove` deletes it, and a + run of the plug-in still going gets `-5` from every storage call after that. `plugin.remove` first renames the folder, + adding `.removed` to its name (or `.removing` while a `.removed` folder holds settings an earlier removal kept). When + that fails, `plugin.remove` fails and the plug-in stays installed with its storage as it was. Before VectorCraft + deletes a renamed folder, it writes an empty file beside it with `.delete` added to the folder's name, and removes + that file once the folder is gone. When that file can't be written, the folder is not deleted and is treated like any + renamed folder without a `.delete` file (see below). Files that can't be deleted stay in the renamed folder with the + `.delete` file beside it, where no plug-in reaches them. A later `plugin.remove` tries again to delete them when a + plug-in with that id is installed or a storage folder for the id exists, and that deletion can fail too. For an id + that isn't installed and has only such a folder, `plugin.remove` does not delete it and fails as not found. When + `plugin.remove` can't remove the grant and can't rename the folder back either, its error names the renamed folder. + The next load, install or `plugin.remove` of the plug-in renames a renamed folder that has no `.delete` file back + while the plug-in has no folder of its own; when it has one, that folder is used and the renamed folder stays until + `plugin.remove` deletes both. `plugin.remove` with the id of a plug-in that isn't installed deletes the storage kept + for that id, when there is any. `plugin.clearCache` empties the cache and leaves the settings, and `plugin.list` and `plugin.info` give the cache's size as `cacheBytes`. - Without a `Plug-ins` folder (the web build, and embedders that attach none) the storage calls return `-5`. @@ -422,8 +451,9 @@ has the id, `-6` when a plug-in may not call the command, `-7` when the command `-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed). -- Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, - traps, runs out of budget or is canceled leaves every document, its selection and its history as they were. +- Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The + run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, traps, runs + out of budget or is canceled leaves every document, its selection and its history as they were. - Each call runs on the document the run is for, with its params checked as any request's are, and sees what the calls before it changed: a `select.all` followed by `object.move` moves everything. The filter's own input is the one it was given when the run started; an edit still in progress (typing, or a shape being drawn) is kept as its own undo @@ -504,18 +534,17 @@ the module's start function, in a run that isn't a filter's run on a document, o no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are - clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults - are also clamped to their range, including the implicit zero default of an `int` parameter. Besides `number`, - `int`, `bool` and `choice` there are `string` (`{"type": "string", "default": "", "maxLength": 256}`: a text field; - longer text is cut to `maxLength`, at most 4,096 characters) and `numberList` (`{"type": "numberList", "min": 0, - "max": 360, "default": [45, 135], "minItems": 1, "maxItems": 16}`: numbers typed separated by commas or spaces, - each clamped to `min..max`; a list of too few or too many is an error, and `maxItems` is at most 256) and `color` - (`{"type": "color", "default": "#3a7bd5"}`: a color button that opens a color picker; the default, black when left - out, and a value given to `plugin.run` may be a color object as paints hold one or a hex string, and the plug-in - always gets a color object, its components clamped, such as `{"model": "rgb", "r": 0.23, "g": 0.48, "b": 0.84}`; a - hex string and the picker's choice are display colors, given as the working RGB color that shows as them, so in a - working RGB space other than sRGB the numbers differ from the hex). Hosts from before `color` refuse a manifest that - uses it. A plug-in declares up to 256 + clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped + to their range, including the implicit zero default of an `int` parameter. Besides `number`, `int`, `bool` and + `choice` there are `string` (`{"type": "string", "default": "", "maxLength": 256}`: a text field; longer text is cut + to `maxLength`, at most 4,096 characters) and `numberList` (`{"type": "numberList", "min": 0, "max": 360, "default": + [45, 135], "minItems": 1, "maxItems": 16}`: numbers typed separated by commas or spaces, each clamped to `min..max`; a + list of too few or too many is an error, and `maxItems` is at most 256) and `color` (`{"type": "color", "default": + "#3a7bd5"}`: a color button that opens a color picker; the default, black when left out, and a value given to + `plugin.run` may be a color object as paints hold one or a hex string, and the plug-in always gets a color object, its + components clamped, such as `{"model": "rgb", "r": 0.23, "g": 0.48, "b": 0.84}`; a hex string and the picker's choice + are display colors, given as the working RGB color that shows as them, so in a working RGB space other than sRGB the + numbers differ from the hex). Hosts from before `color` refuse a manifest that uses it. A plug-in declares up to 256 parameters, at most 64 of them outside groups. Each parameter may also say how dialogs show it. Hosts from before these keys ignore them, so a plug-in that @@ -540,17 +569,18 @@ parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the paramet order (bottom first): the selected ones and those inside selected groups and layers; hidden, locked, guide (compound guides too) and clipping paths are left out, and so are other kinds of object (type, images, symbols, live blends…), which a filter never touches unless its manifest lists them in `inputs` ([reading type, images and -symbols](#reading-type-images-and-symbols)). With nothing selected the list is empty (a generator then adds its own objects). A live effect gets one -object: its geometry (`type`, `path`, `fillRule`, `bounds`) and its `fills` and `strokes`, as a filter gets them (hosts -from before these give geometry only). The paints are read only: an effect may draw as wide as a stroke or use a -fill's colour to decide its shape, but it changes only the geometry, unless it declares `paintOutput` ([painted live -effects](#painted-live-effects)). +symbols](#reading-type-images-and-symbols)). With nothing selected the list is empty (a generator then adds its own +objects). A live effect gets one object: its geometry (`type`, `path`, `fillRule`, `bounds`) and its `fills` and +`strokes`, as a filter gets them (hosts from before these give geometry only). The paints are read only: an effect may +draw as wide as a stroke or use a fill's colour to decide its shape, but it changes only the geometry, unless it +declares `paintOutput` ([painted live effects](#painted-live-effects)). An **exporter** gets something else: the native `.vectorcraft` document JSON without indentation, optional preview/PDF -renditions or save-preference metadata (the format is documented in [`crates/format/src/lib.rs`](../crates/format/src/lib.rs)). That is every layer, object, -appearance and effect record, artboard, swatch and symbol, so an exporter reads whatever the document holds; it checks -`version`, since a later host may write a newer one. Images of 8 KiB or more are listed in `images` with their MIME -type and `blob` but without their data, which follows the JSON in a saved file; smaller ones keep their base64 `data`. +renditions or save-preference metadata (the format is documented in +[`crates/format/src/lib.rs`](../crates/format/src/lib.rs)). That is every layer, object, appearance and effect record, +artboard, swatch and symbol, so an exporter reads whatever the document holds; it checks `version`, since a later host +may write a newer one. Images of 8 KiB or more are listed in `images` with their MIME type and `blob` but without their +data, which follows the JSON in a saved file; smaller ones keep their base64 `data`. An **importer** gets the bytes of the file being opened, as they are (not JSON), at most 128 MiB of them. @@ -579,12 +609,11 @@ An **importer** gets the bytes of the file being opened, as they are (not JSON), (absent: no handle), `kind` `"Smooth"` when the handles stay collinear. Coordinates are points, y down. - `fills`, `strokes`: the object's fills and strokes in paint order (bottom first); `null` is no paint. A stroke has its `paint`, `width` in points, `join` (`"miter"`, `"round"` or `"bevel"`), `cap` (`"butt"`, `"round"` or `"square"`) - and `miterLimit`. Paints use the - native file format's form: `{"type": "solid", "color", "swatch"?, "tint"?}`, `{"type": "gradient", "gradient": - {"kind": "Linear"|"Radial"|"Freeform", "stops": [{offset, color, opacity, midpoint}], "dither"?, "method"?: "Perceptual"}, "geom"?, "angle", - "freeform"?}`, `{"type": "pattern", "pattern", "xf"?}`. Colours are `{"model": "rgb", r, g, b}`, `{"model": "cmyk", - c, m, y, k}`, `{"model": "gray", k}` (ink: 0 white, 1 black) or `{"model": "lab", l, a, b}`; components 0–1 except - Lab's. + and `miterLimit`. Paints use the native file format's form: `{"type": "solid", "color", "swatch"?, "tint"?}`, + `{"type": "gradient", "gradient": {"kind": "Linear"|"Radial"|"Freeform", "stops": [{offset, color, opacity, + midpoint}], "dither"?, "method"?: "Perceptual"}, "geom"?, "angle", "freeform"?}`, `{"type": "pattern", "pattern", + "xf"?}`. Colours are `{"model": "rgb", r, g, b}`, `{"model": "cmyk", c, m, y, k}`, `{"model": "gray", k}` (ink: 0 + white, 1 black) or `{"model": "lab", l, a, b}`; components 0–1 except Lab's. - `effects` (filters): the object's own effects in order, as its effect records: `id` (as `effect.list` lists it, or `plugin.<id>` for a live-effect plug-in), `params` and `visible`. Its fills' and strokes' own effects aren't listed. - `bounds`: `[x0, y0, x1, y1]`, the geometric bounds (read only). @@ -595,9 +624,9 @@ A filter whose manifest lists `inputs` also gets the selected objects of those k and under the same rules (hidden and locked ones, objects that clip a clip group, alone or inside a group that clips it, and anything inside a symbol, a placed document or a live object are left out). They are never turned into outlines, rectangles or the symbol's art. Each has `id`, `type`, `name` (when it has one), `bounds` (`null` until the -object has been laid out or drawn) and -`transform`, `[a, b, c, d, e, f]` mapping its own space (text space, pixel space, the symbol's art) into the document. -In this example the character and paragraph styles are cut short; a filter gets every attribute: +object has been laid out or drawn) and `transform`, `[a, b, c, d, e, f]` mapping its own space (text space, pixel space, +the symbol's art) into the document. In this example the character and paragraph styles are cut short; a filter gets +every attribute: ```json {"objects": [ @@ -626,13 +655,13 @@ In this example the character and paragraph styles are cut short; a filter gets `pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile, as sRGB. The pixels of all the images in one input take at most 16 MiB in base64, and an image the host starts to decode takes its size from those 16 MiB even when decoding fails. A larger image, one whose pixels don't fit what the images before - it in paint order left, and a linked image (`linked: true`) have - `pixelsOmitted: true` and no pixels; the host checks an image's size before it decodes the image. An image of any - size also has `pixelsOmitted: true` when its data is missing from the document, when its width or height is 0, when - its data cannot be decoded (including a non-CMYK image whose decoder enforces the host's 64 MiB memory limit and - needs more, and a TIFF the host rejects as too large), or when the dimensions in its data differ from `pixelSize`. - A plug-in checks `pixelsOmitted` before it reads `pixelsBase64`, which is present only when `pixelsOmitted` is `false`. The host never - reads a linked image's file for a filter and never gives its path. + it in paint order left, and a linked image (`linked: true`) have `pixelsOmitted: true` and no pixels; the host checks + an image's size before it decodes the image. An image of any size also has `pixelsOmitted: true` when its data is + missing from the document, when its width or height is 0, when its data cannot be decoded (including a non-CMYK image + whose decoder enforces the host's 64 MiB memory limit and needs more, and a TIFF the host rejects as too large), or + when the dimensions in its data differ from `pixelSize`. A plug-in checks `pixelsOmitted` before it reads + `pixelsBase64`, which is present only when `pixelsOmitted` is `false`. The host never reads a linked image's file for + a filter and never gives its path. - A symbol instance (`"symbolInstance"`): `symbolId` is the name of the symbol it shows, with `missing: true` when the document has no symbol of that name. `overrides` is `{}`. @@ -663,16 +692,16 @@ toward the 64 MiB output cap. ``` `mode` is `"filter"`, `"effect"`, `"export"`, `"import"` or `"command"` (a [command](#commands) run, whose -`command` is the command's id); `bounds` the selection's geometric bounds (a live effect: the reference -box of the effect, the object's bounds or those of the previous effect's result); `artboard` (filters) the artboard -under the selection's centre, else the first; `documentData` (filters) what the plug-in last kept with the document -(`null` until it keeps something; see Output). A live effect's `item` says where it sits: `"object"` (one of the -object's effects), or `{"fill": i}` / `{"stroke": i}` (in the own effects of the object's `i`th fill or stroke, -counted from the bottom as in `fills` and `strokes`). An export's `_context` is `{"mode": "export", "extension": "plt", -"name": "Poster"}` instead: the extension of the file being written (one the exporter lists) and its name without the -extension (the document's name when the export is not given a path), which some formats keep in their header. An -import's `_context` is `{"mode": "import", "extension": "plt", "name": "Poster"}`: the extension of the file being -opened and its name without the extension. +`command` is the command's id); `bounds` the selection's geometric bounds (a live effect: the reference box of the +effect, the object's bounds or those of the previous effect's result); `artboard` (filters) the artboard under the +selection's centre, else the first; `documentData` (filters) what the plug-in last kept with the document (`null` until +it keeps something; see Output). A live effect's `item` says where it sits: `"object"` (one of the object's effects), or +`{"fill": i}` / `{"stroke": i}` (in the own effects of the object's `i`th fill or stroke, counted from the bottom as in +`fills` and `strokes`). An export's `_context` is `{"mode": "export", "extension": "plt", "name": "Poster"}` instead: +the extension of the file being written (one the exporter lists) and its name without the extension (the document's name +when the export is not given a path), which some formats keep in their header. An import's `_context` is `{"mode": +"import", "extension": "plt", "name": "Poster"}`: the extension of the file being opened and its name without the +extension. ### Output @@ -749,17 +778,17 @@ is a piece drawn by itself, in the order returned, with paints of its own: path or compound path is hit-tested on its source path and appearance. On an object with no geometry effect of its own, Pathfinder effects and compound shapes use the object's path for an effect on a fill or stroke, as they do for every other effect on a fill or stroke; on an object that has one, they also use the pieces of a painted effect on a - fill or stroke. A 3D effect later in the stack uses the - object's input path when the pieces name a swatch or pattern. Each piece counts against the budget of the - object's geometry effects as well as its anchors, so all the painted effects in a stack make at most 100,000 pieces - together; a run whose pieces would pass the budget draws its input as it was. + fill or stroke. A 3D effect later in the stack uses the object's input path when the pieces name a swatch or pattern. + Each piece counts against the budget of the object's geometry effects as well as its anchors, so all the painted + effects in a stack make at most 100,000 pieces together; a run whose pieces would pass the budget draws its input as + it was. - The result is checked whole before any of it is drawn: the limits of a filter's output (100,000 objects, 4,000,000 anchors, 256 fills and 256 strokes per piece, 256 stops per gradient), finite numbers in range with nothing clamped (color components, tints, offsets, opacities, midpoints 0.13 to 0.87, stops in order of `offset`, stroke - widths 0 to 1,000 pt, miter limits 1 to 500), and every swatch a solid paint, gradient or stop links to and every pattern named in - the document. One fault refuses the whole result: that step of the stack draws its input as it was, the effect - record stays, and `plugin.info`'s `lastError` names the plug-in and the field, for example - `Test Tone: plug-in output: objects[1].strokes[0].width: …`. + widths 0 to 1,000 pt, miter limits 1 to 500), and every swatch a solid paint, gradient or stop links to and every + pattern named in the document. One fault refuses the whole result: that step of the stack draws its input as it was, + the effect record stays, and `plugin.info`'s `lastError` names the plug-in and the field, for example `Test Tone: + plug-in output: objects[1].strokes[0].width: …`. - The pieces are never written into the document while it is drawn, measured, previewed, saved or exported. PDF and SVG export draw them as the canvas does, from a copy of the document. Object › Expand Appearance writes each piece as an ordinary path or compound path with its fills and strokes, as one undo step. Object › Expand of gradient and pattern @@ -787,12 +816,13 @@ crates/plugins/example/build.sh # cargo build --release --target wasm32-unk The script also refreshes `crates/plugins/tests/fixtures/desaturate.wasm`, the test fixture built from that source. The crate is not a workspace member. Any language that targets core WebAssembly works (C, Zig, AssemblyScript, -WAT…), as long as the module imports nothing but the host imports: in Rust, `std` on `wasm32-unknown-unknown` is fine as long as it never -touches WASI. `vectorcraft_plugins::wat::module` is the skeleton of a plug-in in WebAssembly text, which the tests -build their plug-ins from; `wat::echo_exporter` is an exporter whose file is its input or its parameters (with a -base64 encoder written out in WebAssembly text), which the tests read back what the host hands a plug-in with, and -`wat::when_given` a plug-in whose output depends on whether its input or parameters hold a given text, which shows in a -live effect's geometry. `wat::reporting` and `wat::cooperating` build level 2 plug-ins that import the host functions. +WAT…), as long as the module imports nothing but the host imports: in Rust, `std` on `wasm32-unknown-unknown` is fine as +long as it never touches WASI. `vectorcraft_plugins::wat::module` is the skeleton of a plug-in in WebAssembly text, +which the tests build their plug-ins from; `wat::echo_exporter` is an exporter whose file is its input or its parameters +(with a base64 encoder written out in WebAssembly text), which the tests read back what the host hands a plug-in with, +and `wat::when_given` a plug-in whose output depends on whether its input or parameters hold a given text, which shows +in a live effect's geometry. `wat::reporting` and `wat::cooperating` build level 2 plug-ins that import the host +functions. ## Performance diff --git a/docs/releasing.md b/docs/releasing.md index 64c177618c..bfa3f4e21c 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -42,6 +42,12 @@ pick that branch for a full run. Run on any other branch, it is a dry run: the L FreeBSD and web jobs build and upload their artifacts, the environment refuses the signing jobs, and no draft release is created. +Flatpak permission repairs need one update through the existing host-side installation method. +After that update, Help > Check for Updates can inspect and update standalone bundles. +Repository-managed installations continue to use their package manager; launcher-pinned +versions keep their selected version. Both Flatpak manifests must grant network access, +the host Flatpak interface, and read-only access to the shared version choices. + ## What gets built | Platform | Artifacts | Built on | @@ -164,7 +170,7 @@ to the target triple, so host build scripts aren't affected. AppStream metainfo, the MIME type for VectorCraft documents, the icons and the licence files. **Document types.** The desktop entry's `MimeType` lists every format File › Open reads but PSD, -PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000 and HEIC/HEIF, so file managers list VectorCraft under Open With for them. +PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF and HP-GL, so file managers list VectorCraft under Open With for them. `ai.storyteller.vectorcraft.mime.xml` declares the types that shared-mime-info lacks: VectorCraft documents and templates, `.ait` templates and Affinity files (`application/x-affinity`). An `.af` file gets the Affinity type by its content, and `.afdesign` and `.afpub` files by their extension. diff --git a/docs/roadmap.md b/docs/roadmap.md index 241e786f95..f1ca48fab1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -142,18 +142,18 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, four generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, five generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, five generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, seven generated libraries including Bristle Brushes, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -190,6 +190,11 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | M14: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects all (#6659, follow-up to #1326); estimates unchanged. | +| 2026-11-12 | minor | M12: Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | +| 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | +| 2026-11-11 | minor | M10/G5: Energy Beams built-in brush library; MCP docs catch-up; estimates unchanged | +| 2026-11-11 | minor | M10/G5: Skill Icons built-in symbol library; MCP docs catch-up; estimates unchanged | | 2026-11-10 | minor | M10/G5: Status Effects built-in graphic style library; MCP docs catch-up for UI Frames and Map Markers; estimates unchanged | | 2026-11-10 | minor | M10/G5: Inventory Icons built-in symbol library (Sword, Shield, Potion, Key, Gem); estimates unchanged | | 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | @@ -377,4 +382,4 @@ separate. Scores and hours unchanged. [Behavior and command details](development 2026-10-28 behavior correction: Flare ray rotation follows vertical travel at one degree per document point, independent of pointer event count. Shift freezes the current orientation; Space also freezes rotation on the first update. This is the chosen application interaction rate. Scores and estimates unchanged. ## EPS Save evidence (2026-10-26) -Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. +Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f52cee3a7f..1880920e20 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,8 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> +> Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -216,27 +218,27 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de |---|---:|---:|---|---:|---| | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged | -| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (five generated libraries including Game Trails, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (seven generated libraries including Bristle Brushes, Game Trails and Energy Beams, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons and Skill Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces; materials, shadows, ray tracing, the rest of 3D Classic (Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step` | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons and Skill Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | @@ -245,7 +247,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -349,7 +351,7 @@ Depth here is "does the basic use work", not the area's full score. | Shape tools (rectangle, ellipse, polygon, star, line) | 9 | 95% | all shape tools, Live Corners | | Selection, move, scale, rotate | 9 | 92% | bounding box, smart guides, transform tools | | Pen and Pencil, basic use | 7 | 88% | [ui-parity.md](ui-parity.md); a few Pencil and Curvature options missing | -| Fill, stroke, colour, swatches | 9 | 95% | M3 done; highlighted-text Eyedropper font/paint and source/target transparency refusal regression-tested; scores and hours unchanged | +| Fill, stroke, colour, swatches | 9 | 95% | M3 done; transform-aware Eyedropper character dimensions (#6404); highlighted-text Eyedropper font/paint and source/target transparency refusal regression-tested; scores and hours unchanged | | Gradients, basic | 4 | 90% | Gradient panel and on-canvas annotator | | Type: point and area text, font, size | 8 | 88% | font menu with previews; Hyphenation… and Justification… options per paragraph (#2310, #2755) | | Align, group, arrange | 6 | 95% | | @@ -487,16 +489,16 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (five generated in code including Game Trails are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (seven generated in code including Bristle Brushes, Game Trails and Energy Beams are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | -| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | +| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | -| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | +| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons and Skill Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -539,7 +541,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~42% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have four (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons), graphic style libraries eight (including Game HUD and Status Effects) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have five (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons), graphic style libraries eight (including Game HUD and Status Effects) and brush libraries seven (Art Ribbons, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -558,6 +560,7 @@ since 2026-10-01. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. +- 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. Softness and the shadows of lights after the first are not built. Scores unchanged. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. @@ -574,6 +577,9 @@ since 2026-10-01. **Review follow-up:** The fit-query follow-up covers fitting after draft dimensions change, updated artwork after a document revision, cache scope and new-artboard fitting/history. Selection uses the existing application bounds cache; global artwork queries include all drawn document art and are cached by active document and revision; draft geometry and target artboards do not limit membership. This is not a native timing claim. - **Stable status-bar readouts:** The status message keeps its left anchor and clipping allocation as live values, canvas hover and background-job state change. Coordinate and spinner slots stay reserved; narrow windows hide optional diagnostics, then coordinates, to preserve message space. Widths are measured from the active font, translated labels and fixed numeric samples, never current readings. Coordinates through +/-9999.99 selected units, timings through 9999.9 ms and FPS through 9999 remain readable. Extreme values are elided with full tooltip/accessibility text; only elided fields show a tooltip. Coordinate inspection retains the last point per document and clears on PointerGone. Regressions cover message origin/clip/bounds/elision invariance, all registered languages and ten units, responsive layouts, coordinate inspection and document switching, and accessible busy transitions. The contributor rebuilt and confirmed the original status-bar issue is fixed with their own artwork on 2026-10-19; the subsequent upstream rebase is checked by regressions and full CI. The artwork stays local. Scores and estimates are unchanged. Sample widths use a bounded single-entry UI cache keyed by language, unit and pixels per point; two regressions verify reuse during live updates and invalidation after each display-setting change. +- **Clipped bottom-bar text (#6622):** A Help Bar hint wider than the window, such as the Dimension tool's hint in an 800-point window, ends in an ellipsis, as the status message does. In a narrow status bar the tool name ends in an ellipsis and leaves the status message its room. Resting the pointer on a clipped hint, tool name or message shows the full text in a tooltip that wraps within the window. Text that fits shows no tooltip, and screen readers receive the full text. Scores and estimates are unchanged. +- **Notes of an open in the status bar:** After File › Open the status message names the first note that says reading the file left something out (the notes that make Save ask before writing over the file), else the first note, and counts them all. With several notes, resting the pointer on the message lists them in that order, as many as fit in the window and at most 30, then how many more. Screen readers receive the list after the message. Scores and estimates are unchanged. +- **Notes of a save or an export in the status bar:** After Save, Save As, Save a Copy, Save as Template, Save a Timestamped Copy, Save as PDF, Export As, Export Selection, Export for Screens, Asset Export, Save for Web, Preview in Browser, Save for Office Documents, Text Export Options, a print to a file or the CSS Properties panel's export, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order the reply gives them (a save's notes start with what the format loses), as it lists an open's notes. Scores and estimates are unchanged. - **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. Scores and estimates are unchanged. - **Cached canvas frames during viewport changes:** Cached screen textures use their own raster dimensions and pixels-per-point when reprojected. `canvas::tests::cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes` holds the worker and checks every UV corner against the cached render transform, including isolated viewport-only resize at zero/30-degree rotation, fractional raster dimensions, zoom/pan, changed rotation, monitor-DPI changes in both directions, Pixel Preview and replacement-frame delivery. The contributor rebuilt and confirmed the original resize issue is fixed with their own artwork on 2026-10-19; the subsequent upstream rebase is checked by regressions and full CI. The artwork stays local. Scores and estimates are unchanged. @@ -585,6 +591,8 @@ since 2026-10-01. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes, the distances of its later effects and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). Not yet: object effects after a Transform effect keep their distances. Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Warp Options (#1760):** Effect > Warp and existing Appearance effect links share the fifteen existing styles, original schematic previews, orientation choices and percent Bend/Distortion controls. Focused tests passed for real numeric entry and slider input, Preview/Cancel, immediate Enter/OK, mixed-style edits, target/slot/visibility preservation and Undo/Redo. Each applied style stays unchanged until an explicit Style choice. Original style-menu and live-preview captures were reviewed; their numeric values were supplied programmatically. Public references: [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) and [Using effects](https://helpx.adobe.com/illustrator/using/effects.html). Warp geometry, optional Properties integration and remembered defaults are unchanged; no broader parity claim. - **Placed gradients follow the Warp effects:** under each of the fifteen Warp styles with a bend or a distortion, a gradient placed with the Gradient tool moves and scales from the object's bounds before the warp to its bounds after it, as under Free Distort; a stroke's gradient uses those bounds inflated by the stroke. This holds for an object's own Warp and for a fill's or stroke's own, on the canvas and in Object › Expand of the fill. In a group with a Warp effect, each path's and compound path's gradients follow its own bounds, a nested group's own fills and strokes follow the nested group's bounds, and the group's own fills and strokes follow the group's bounds. In the art Pathfinder and compound shapes take, a symbol instance's Warp moves the gradients of its symbol's art by the art's bounds, and a compound shape's Warp moves its gradients by the bounds of its area. A gradient fitted to the object still fits the warped outline, and a warp with no bend and no distortion leaves the gradient exactly in place. Existing documents with a Warp effect on art with a placed gradient draw differently: before, the gradient stayed where it was while the outline changed. How gradients follow the warp is VectorCraft's own rule; what the Warp effects do to the object is described in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) (effects `tests::warp_bends_when_the_warp_moves_the_outline`, `bake::tests::baked_warps_move_placed_gradients_from_the_bounds_to_the_warped_bounds`, `bake::tests::a_warp_with_no_bend_leaves_a_placed_gradient_exactly_in_place`, `bake::tests::a_fills_and_a_strokes_own_warp_move_its_placed_gradient_with_the_bounds`, `group::tests::a_groups_warp_moves_the_gradients_placed_on_its_paths_by_each_paths_bounds`, `group::tests::a_groups_warp_moves_its_own_a_nested_groups_and_a_compound_paths_gradients_by_their_bounds`, `group::tests::shape_art_moves_the_gradients_of_a_symbol_instances_art_and_a_compound_shape_with_a_warp`; render `objectfx::a_paths_gradient_moves_and_scales_with_its_warped_bounds`; engine `objexpand::a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it`). Scores and hours unchanged. +- **Warp as a Bézier patch per style:** each of the fifteen Warp styles bends the object's bounds as one Bézier patch whose control points the style sets from the bend and the size of the bounds; the horizontal distortion then scales each column of control points about its middle and the vertical distortion scales each row. The Warp effects and warp envelopes share the map, and content with no width or no height takes the middle of the patch along that side. New warps, the built-in graphic styles' Warps and warps opened from `.ai` files carry `version` 1 for it. Warps in `.vectorcraft` documents saved before it read as `version` 0 and keep their earlier look, and edits keep a warp's version; a `version` 0 warp saved to `.ai` opens again with `version` 1, since the file holds only its settings. The patches are VectorCraft's own rules; the styles and ranges are those of the Warp options in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (doc `live::tests::warp_nets_bend_each_style_as_its_own_patch`, `warp_net_arc_edges_are_concentric_circles`, `warp_net_distortion_scales_the_columns_then_the_rows`, `warp_net_takes_any_numbers`, `warp_net_bends_a_huge_box_without_overflowing`, `warp_envelopes_bend_flat_content_as_the_middle_of_the_patch`, `warp_envelopes_write_their_map_version_only_when_it_has_one`, `style_libs::tests::builtin_warp_styles_take_the_nets_map`; effects `tests::a_warp_draws_with_the_map_its_version_names`, `tests::a_warp_bends_a_flat_box_as_the_middle_of_its_patch`, `tests::new_warps_take_the_nets_version`; engine `effectedit::warps_keep_the_map_their_version_names`, `envelope::new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map`; eps `ai_editing::tests::every_effect_a_graphic_style_holds_is_read_back`, `import::ai::tests::a_warp_envelope_opens_live`, `import::ai::tests::warp_envelopes_read_every_style`, `import::ai::style::tests::a_stack_of_fills_with_effects_of_their_own_is_read_as_itself`; ui-egui `dialogs::tests_warp::warp_options_edit_keeps_each_targets_map_version`). Scores and hours unchanged. +- **Warp effects bend images:** a Warp effect on an image, or on a group that holds one, bends the image's pixels with its frame, as the Warp effect is documented to distort bitmap images in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html): after the last effect, the image is cut into 10 × 10 cells of two triangles, each a clipped piece under its own affine map. Effects after the Warp reshape only the frame, a second Warp bends the same pieces, and warps saved without a version bend the pixels with their earlier map, as they bend the frame. A placed gradient on a group that holds the image follows the group's bounds as the pieces draw them. SVG writes the image once for the pieces; PDF, EPS, `.ai` and PNG write the bent pieces. The images stay unbent when their pieces would make the art pass 2 million objects, and so does an image whose frame keeps its shape past the anchor budget. A grayscale image's fill color now colorizes the pieces of a warp or an envelope, and an image under any geometry effect keeps that color and its smoothing setting. Existing documents with a Warp effect on an image, or on a group that holds one, draw differently: before, the image showed unbent, cut by the bent frame. So do existing documents with a colorized image under an envelope or a geometry effect, or an image drawn without smoothing under a geometry effect: before, those lost the color or the setting. The cell count and the limits are VectorCraft's own (effects `tests::warped_images_stay_within_the_object_budget`, `tests::warped_images_keep_document_keys_and_hidden_images_apart`, `tests::an_image_whose_frame_passes_the_budget_stays_whole`, `tests::effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces`, `tests::an_images_pixels_take_the_map_their_warps_version_names`, `tests::an_image_under_a_geometry_effect_keeps_its_color_and_smoothing`, `tests::a_nested_groups_gradient_follows_its_warped_image`; engine `warp_images::an_images_pixels_bend_with_effect_warp`, `a_warped_image_keeps_its_bend_in_svg`, `a_warped_image_keeps_its_bend_in_pdf`, `a_warped_image_keeps_its_bend_in_ai`, `a_warped_image_keeps_its_bend_in_eps`, `a_warped_image_keeps_its_bend_in_png`, `svg_writes_an_image_clipped_twice_in_a_users_group_twice`, `expand_appearance_of_a_warped_image_draws_as_the_canvas_did`, `a_colorized_image_keeps_its_color_when_warped`, `a_warp_on_a_group_bends_the_image_in_it`, `envelope_distort::a_colorized_image_keeps_its_color_in_an_envelope`). Scores and hours unchanged. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. @@ -594,11 +602,13 @@ since 2026-10-01. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. - **Global Edit's enabled check on large paths:** the check that decides whether Select › Start Global Edit can run on the selected path, compound path or symbol instance (which the Control bar makes every frame) measures the box of its anchors and handles instead of building and normalizing a copy of every anchor, with the same answer. On a 200,000-anchor path the check takes 0.7 ms instead of 2.2 to 3.0 ms. Regression tests: `support_*` in `crates/engine/src/cmd/globaledit.rs`. - **Control bar's inline X, Y, W and H fields fit the bar:** the Control bar shows the inline X, Y, W and H fields only when all four, their labels as drawn in the current language and the W/H link fit inside the bar's margin; otherwise it shows the Transform link alone. This is VectorCraft's own layout rule. Regression test: `the_control_bar_shows_the_inline_transform_fields_only_when_they_fit` in `crates/ui-egui/src/chrome/tests.rs`. - **Control bar docks to the top or the bottom:** the Control bar's panel menu, at the bar's right end, has Dock to Top and Dock to Bottom, the edge in use checked, and dragging the bar's gripper docks it at the top or the bottom edge of the window, whichever the pointer is released nearer, with a band along that edge while it moves (`window.control.dock {edge}`), as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). Keeping the edge with the workspace, with older workspaces docking the bar at the top, is VectorCraft's own rule. Not done: dragging the gripper away from both edges to float the bar. Regression tests: `the_control_bar_panel_menu_docks_it_to_the_top_or_the_bottom`, `dragging_the_control_bar_gripper_docks_it_at_the_nearer_edge`, `the_control_bar_dock_command_takes_top_or_bottom` and `menus_stop_above_a_control_bar_docked_at_the_bottom` in `crates/ui-egui/src/chrome/tests.rs`, `saved_workspaces_restore_the_control_bar_edge` in `crates/ui-egui/src/workspaces.rs`. +- **Control bar panel menu turns groups of options on or off:** the Control bar's panel menu lists the bar's groups of options (Snapping, Anchor Points, Tool Options, Object Options, Image Options, Fill and Stroke, Opacity, Graphic Style, Character, Paragraph, Vertical Alignment, Align and Distribute, Transform, Artboard Options and Document Options) above Dock to Top and Dock to Bottom, each checked while it is on; a click turns that group off or on (`window.control.options {group, visible?}`), and a group that is off stays out of the bar even while its tool or object is selected, as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). The list of groups and what each holds, every group on to start, a group that is off leaving its room to the groups after it, and keeping the groups with the preferences and the workspace are VectorCraft's own rules. Regression tests: `the_control_bar_panel_menu_turns_each_group_on_or_off`, `the_control_bar_keeps_its_label_and_menu_with_every_group_off`, `the_control_bar_panel_menu_scrolls_in_a_short_window`, `the_control_bar_options_command_turns_a_group_on_or_off`, `groups_that_are_off_leave_their_room_to_the_later_groups`, `the_artboard_tool_s_control_bar_follows_its_two_groups` and `the_anchor_points_group_holds_convert_and_anchors` in `crates/ui-egui/src/chrome/tests.rs`, `the_image_options_group_holds_the_image_and_trace_controls` in `crates/ui-egui/src/tests/place.rs`, `the_character_and_paragraph_groups_hold_the_type_controls` in `crates/ui-egui/src/panels/paragraph/tests.rs`, `saved_workspaces_restore_the_control_bar_groups` in `crates/ui-egui/src/workspaces.rs`. - **Pattern-only backquote drags:** With Selection move, bounding-box scale or rotate, or the Rotate, Reflect, Scale or Shear tool, backquote held at mouse release applies the drag matrix to selected pattern paint while object geometry stays in place. The key may be pressed after mouse press; if released before the mouse button, the drag commits as an ordinary transform. Objects without pattern paint stay still; stroke-only patterns and patterned objects in mixed selections take the same matrix. Regression tests: `backquote_move_uses_release_state_and_one_commit` and `backquote_box_scale_and_rotate_use_pattern_matrix_at_release` in `select/tests.rs`, `backquote_drag_previews_and_commits_pattern_only_for_each_transform_tool` in `xform/transform.rs`, `selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art` and `selection_backquote_drag_changes_stroke_only_pattern` in `tests/pattern.rs`, `egui_backtick_drag_uses_key_state_at_release` in `canvas/tests.rs`, and `synthetic_pointer_backquote_keeps_solid_object_in_place` in `control/tests.rs`. Scores and hours unchanged. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. @@ -612,6 +622,8 @@ since 2026-10-01. - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. +- **EPS Save with Use Artboards:** Save As › EPS Options show Use Artboards with All or Range, for a separate file per artboard ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with a default of false, [scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, without the artboards' background colors; when no art shows, the page is the first artboard in its color. An opened EPS saved back this way loses its page margins. Checked with two or more chosen artboards, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it. Checked with one chosen artboard, VectorCraft writes that artboard as the page of the file at the path alone (the behavior Save had since #4293). Evidence: `cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `tests::save::eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, `tests::save::eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, `dialogs::save_options::tests::eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. + - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. - **Selected artboard deletion:** the Artboards panel menu, panel trash button and Properties use the same selected set; selecting all retains artboard 1. Pointer-event tests cover nonadjacent and single selections, the original first-board survivor, ordinary artwork, Undo/Redo and the single-board guard. Public reference: [Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). @@ -628,10 +640,12 @@ since 2026-10-01. - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). -- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), the Tate-chu-yoko Settings Up/Down and Left/Right (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0 pt, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these seven. Language sets the language the characters are shaped in, not hyphenation or spelling. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html). - **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). -- **Opening style options from the style panels:** a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), as the panel menu's item does; a paragraph style's row opens its Paragraph Style Options, the rename dialog (`ui.paramDialog` running `paraStyle.rename`) the panel menu opens. A single click still applies the style, the second click of the double-click does not apply it again, and the built-in Normal style opens no dialog. Test `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`. +- **Opening style options from the style panels:** a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), as the panel menu's item does; a paragraph style's row opens its Paragraph Style Options (`ui.paraStyleOptions`), as the panel menu's item does. A single click still applies the style, the second click of the double-click does not apply it again, and the built-in Normal style opens no dialog. Test `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`. - **Character Style Options window size:** the dialog keeps a fixed width wide enough for the widest tab's controls and scrolls its sections inside a window shorter than them, so it stays on screen and its OK and Cancel buttons stay visible; the width is the same in every section and the height follows the section. Test `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. +- **Paragraph Style Options, General, Basic Paragraph Formats, Composition, Hyphenation and Justification:** Paragraph Style Options (`ui.paraStyleOptions`, `paraStyle.edit`) and New Paragraph Style edit a style's name, Alignment, left, right and first-line indents, space before and after, composer, Roman Hanging Punctuation, Hyphenation with its options, and Word Spacing, Letter Spacing, Glyph Scaling, Auto Leading and Single Word Justification; paragraphs that use the style take them and keep their local overrides. Fields left as they were keep the style's values, empty fields remain unset, each section's Reset Panel clears only its own attributes, Preview can be canceled without changing history, OK saves one undo step, and out-of-range values keep the dialog open. The character formats of a paragraph style are not in the dialog yet. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Paragraph Style Options, Tabs:** the Tabs section of Paragraph Style Options and New Paragraph Style lists a style's tab stops and edits the selected stop's Alignment (Left, Center, Right or Decimal), position (X:, or Y: for vertical type), Leader and Align On character; Add, Delete Tab and Clear All Tabs add a stop 36 pt past the furthest, remove the selected one, or leave the style with no stops. OK sorts the stops by position, keeps the stop edited last of two at one position, and saves one undo step; Preview and Cancel restore the paragraphs, Reset Panel removes the style's tabs, and a position outside 0 to 100000 pt, a leader longer than 8 characters or more than 256 stops keeps the dialog open. Tests `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` and `tabs_preview_cancel_and_ok_update_the_paragraphs_in_one_undo_step`. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy `<name> copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading (<https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>) also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`. @@ -639,6 +653,7 @@ since 2026-10-01. - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Naming a new text style first:** Alt-click on New in the Character Styles or Paragraph Styles panel opens New Character Style or New Paragraph Style (`ui.newCharStyle`, `ui.newParaStyle`) with the name a plain click's style gets; OK makes the style from the text selected when the dialog opened, and Cancel adds none. Tests `panels::text_styles::tests::alt_clicking_new_character_style_asks_for_its_name` and `alt_clicking_new_paragraph_style_asks_for_its_name`. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), which lists Alt-click for opening panel options and names Actions, Brushes, Swatches and Symbols as exceptions. - **Moving all tab stops:** in the Tabs panel, a stop dragged on the ruler with Ctrl held (Command on macOS) moves every stop by the same distance, in one `text.tabs.set` and one undo step; the stops keep their order, alignment and leaders, the ruler shows them moving during the drag, and a drag that would take the leftmost stop below 0 leaves it at 0, or the rightmost past 100,000 pt leaves it at 100,000 pt, with the other stops at their spacing from it. A drag that leaves every stop where it was records no undo step. Ctrl must be held when the drag starts. Tests `panels::tabs::tests::command_drag_moves_all_the_stops_together`, `command_drag_stops_at_zero_and_keeps_the_spacing`, `command_drag_stops_at_the_largest_position_and_keeps_the_spacing` and `a_drag_that_moves_no_stop_records_no_undo_step`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which says that a Ctrl-drag (Windows) or Command-drag (macOS) of a tab moves all the tab stops at the same time. +- **Tabs indent markers on threaded frames:** when a marker drag gives the paragraphs of a threaded story values of their own, the Tabs panel sends one `text.setFormat` for each paragraph of the story, from its last paragraph to its first, whatever order the frames were selected in with the Selection tool; a paragraph that runs on from one frame into the next gets one step, after Type tool Select All too. With the Selection tool only the paragraphs with text in a selected frame change, so a frame selected alone that starts or ends inside a paragraph sets that paragraph. Tests `panels::tabs::tests::indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once`, `indent_markers_after_select_all_list_a_split_paragraph_once` and `indent_markers_on_some_threaded_frames_list_their_paragraphs_once`. Public reference: [Indent text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/indent-text.html). - **Width Point Edit:** Shift-double-click enables Adjust Adjoining Width Points; plain double-click and direct opening retain the default. Tool dispatch and headless dialog tests cover neighboring widths, Undo/Redo and Cancel. Public reference: [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. @@ -652,14 +667,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes). - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. - **Ruler double-click (#5239):** a double-click (both clicks on that ruler) on the top ruler adds a vertical guide at the pointer's x and one on the left ruler a horizontal guide at its y (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), through `guide.add` in one undo step; the guide is not snapped, is shown even when guides were hidden, and is an artboard guide with the Artboard tool, as a drag from a ruler makes one. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe the gesture, so it follows the request in #5239. egui frame tests cover both rulers, a lone click, Undo, a canvas click before a ruler click, and rotated views. -- **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). +- **Rulers (#1212):** drag the intersection to preview and set a document zero point, snapped as a drawn point is (with Smart Guides onto the art's and the artboards' anchors, centres, edges and paths or into line with them, with Snap to Point along the ruler guides, else to pixels or the grid), or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). - **Artboard guide labels (#6414, in part):** Artboard Options' Guide Label gives an artboard a color label (`artboard.setProps`/`artboard.new` `guideLabel`: a layer color's name, `#rrggbb` or null), and the canvas draws that artboard's own guides in it; canvas guides, guides of an unlabeled artboard and guides whose artboard is gone keep the guide color preference, and selected guides keep the selection color. The [help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) describes guides restricted to an artboard, not a label, so the label, its palette and the color precedence are VectorCraft's own. It is screen-only (exports and print leave it out), written to the native format only when set, kept by duplicates and copies, and changeable on a locked artboard; `artboard.setProps` adds no undo step when nothing changes. This VectorCraft addition does not raise a score. Regression tests: `tests/panelcmds.rs` (`artboard_guide_labels_are_set_and_cleared_in_one_undo_step`, `artboard_guide_labels_round_trip_through_the_native_format`), `doc` `tests.rs` (`guide_label_text_names_a_layer_color_or_rgb`, `artboard_guide_label_defaults_and_skips_in_json`), `canvas::tests` (`artboard_guide_label_colors_only_its_own_guides`), `dialogs/tests.rs` (`artboard_options_shows_sets_and_clears_the_guide_label`). - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. -- **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. @@ -670,6 +684,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. +- **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). @@ -686,7 +701,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests/distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. - **Locked artboards:** a click in the Artboards panel's lock column locks or unlocks an artboard in one undo step (`artboard.setProps {index, locked}`), and the native format saves the lock. The Artboard tool doesn't move, copy, resize or delete a locked artboard, Rearrange and Fit to Artwork Bounds leave it as it is, and its name isn't edited on the canvas. The art on it (each object whose bounds overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, `select.set`, `select.all` and the tools pass over it, and commands that act on the selection leave it; art drawn or pasted onto it stays selected and editable until the selection leaves it out. Tests in `crates/doc/src/lib.rs`, `tests/panelcmds.rs`, `xform/artboard.rs`, `panels/artboards.rs` and `canvas.rs` cover them. Public references: [Lock artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/lock-artboards.html) and [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/). - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. -- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF and JPEG XL, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. +- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL and HP-GL, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document; saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. @@ -710,10 +725,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: expand an action to show its recorded steps, then clear a step's checkmark to keep it in the action but skip it during playback. The action and set checkmarks include or exclude all their steps; a mixed checkmark includes all. Alt/Option-clicking a step checkmark keeps that step as it was and applies the opposite inclusion state to the other steps in its action. This follows the public [Exclude commands from an action](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) guide; the scope of the mixed-state and Alt-click behavior is VectorCraft's design. The exclusion survives UI restart, action duplication, and `.vcactions` save/load. Existing version 1 action set files load with every step included. - Actions panel: the panel menu's Playback Options… sets how actions play: Accelerated (the default) plays every step at once, Step by Step plays one step at a time with the canvas drawn after each, and Pause For waits the given number of seconds between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html); `ui.action.playbackOptions`). VectorCraft's own rules, which the page does not cover: the pause is a whole number of seconds from 1 to 60, the setting is kept with the UI preferences, a paced playback ends at Stop Playing/Recording or when a step comes due while another document is active, each step of a paced playback is its own undo step, and Batch… plays at full speed. - Actions panel: the panel menu's Insert Stop… opens Record Stop, with a Message box and Allow Continue, and adds a stop to the recording in progress, after the selected command, or at the end of the selected action ([Insert stops in actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-stops-in-actions.html); `ui.action.insertStop`). A playing action waits at the stop and shows the message so the user can do a manual task, and Play Current Selection plays the rest ([Illustrator CS5 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=459); `ui.action.continue`). With Allow Continue, the message box also has Continue. VectorCraft's own rules, which the pages do not cover: an empty message still waits, Stop Playing/Recording ends the playback and keeps the steps already played, the rest plays on the document active then, a stop waits at every playback speed, at Accelerated the steps between two stops are one undo step, Batch… refuses an action with an included stop, and Delete Selection on a selected step deletes that step, a stop or a command, without asking (`ui.action.deleteStep`). + - Actions panel: the panel menu's Insert Menu Item… adds a menu command to the recording in progress, after the selected step, or at the end of the selected action, without running it, and playback runs it as the menu does ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertMenuItem`). The dialog's Find box picks the one item that matches the words typed, and a click on a listed item picks it. VectorCraft's own rules, which the page does not cover: items that open a dialog, the Object › Align items, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern, and the File, Window and Help menu items are not listed, and an action holds at most 10,000 steps and its set file at most 8 MiB, for stops too. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - The Batch dialog shows its data set File Name row only when Destination is Folder, and keeps the choice while another destination is picked. With None or Save and Close it does not send `datasetFileNaming`. - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. @@ -733,30 +750,44 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. + - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), and `#targetengine` and `#engine` are refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. + - Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`. + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. + - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. `crates/engine/src/tests/script_engines.rs`. + - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens, links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. + - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. + - Saves, Export for Screens and Package under `--automation-read-root`: a save without a path leaves the document's own file out of its reply, and a save without a path known leaves out the suggested folder, when they are outside the read roots; Export for Screens into an export preset's folder outside them lists its files relative to that folder and names that folder by its name in an error, and the export settings and saved presets leave out a folder outside them when read or exported; Package's report and warnings, and Document Info's linked images, name a file outside them by its file name. A path the client gives stays in the reply. `crates/engine/src/tests/save.rs`, `crates/engine/src/cmd/fileio/tests_screens.rs`, `crates/engine/src/tests/package.rs`, `crates/ui-egui/src/tests/automation.rs`. - `ui.inspect` under `--automation-read-root`: the documents still opening, the recent files, library panels' files and folder preferences (saved, and in an open Preferences dialog) outside the read roots are left out of the reply, a library loaded from outside them shows by its file name in `ui.inspect` and `ui.docking`, and the app's state is not changed. `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_leaves_out_paths_outside_the_read_root`). + - Link replies under `--automation-read-root`: `links.list`, `links.check`, `links.info` and `document.open`'s link rows leave out the path, found path and folder of a linked file outside the read roots, and the stored size and date of it in `links.info`; each row keeps its id, file name and status, and the document's links are not changed. `crates/engine/src/tests/linkspanel.rs` (`link_paths_outside_the_read_roots_are_left_out`), `crates/engine/src/tests/placed_document.rs` (`link_info_leaves_out_a_placed_documents_path_outside_the_read_roots`). + - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. + - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: library files and the user library folder outside the read roots are left out, a library loaded from outside them is listed and found by its file name, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. + - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. + - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 16.0, so characters assigned in later Unicode versions are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_16_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). + - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings (`xpath` is not provided). `<!DOCTYPE>` in an XML string gives a `SyntaxError`. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. + - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. + - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `<!DOCTYPE>` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. - **UI:** Illustrator 2026 layout restyled to measured values: - Medium Dark theme, categorized and Advanced toolbars (a tool group's flyout opens on a right press, a long press or a press on its corner triangle), 35 pt document tabs, 33 pt panel tabs. - Hint bar, contextual task bar, 19 dock panels with ≡ menus. - Window › SVG Interactivity attaches JavaScript to the selected objects' events (`onclick`, `onmouseover` and 17 more) and links JavaScript files to the document (Link JavaScript Files…); SVG export writes the events as event attributes and the files as `<script xlink:href>`, SVG import reads both back as text without running them, and the native format keeps them (`svgInteractivity.*`). - - Numeric fields keep the pointer's pressed character as the text-drag start when movement exceeds the click threshold (#1326, in part); a completed focus click selects the unit too. Pixel/point, plain and optional fields are regression-tested in both directions, before/after focus, with replacement text; keyboard focus, double-click, arrows and wheel keep their prior behavior. Native egui input confirms partial replacement gives 17 px instead of 700 px, one Undo/Redo, window captures and an exact saved-document read in a separate CLI process. Short movements still counted as clicks can select all; that case remains open. + - Numeric fields keep the pointer's pressed character as the text-drag start when movement exceeds the click threshold (#1326); a completed focus click selects the unit too. Pixel/point, plain and optional fields are regression-tested in both directions, before/after focus, with replacement text; keyboard focus, double-click, arrows and wheel keep their prior behavior. Native egui input confirms partial replacement gives 17 px instead of 700 px, one Undo/Redo, window captures and an exact saved-document read in a separate CLI process. A focus click released more than 1 pt from its press keeps the caret, and a tap within 1 pt still selects all (#6659; short-drag and jitter-tap regressions in `tests/numfields.rs`). - Unit fields and length strings take `%` in arithmetic: `3cm*50%` reads as 1.5 cm, and `50pt+25%` reads as 62.5 pt. - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools and the Artboard tool show it). - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). @@ -778,12 +809,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A menu in a floating panel's OS window stops at that window's bottom edge and scrolls past it, and is never taller than the window (#5347; `a_long_panel_menu_scrolls_inside_a_short_native_window`). A panel's long submenus (Digits, Stylistic Sets, Save Selection, Move to Group), the libraries menu, the Color Guide's Limit to Library menu and the Layers panel's Filter popup scroll the same way. - The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done. - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). + - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). - Hindi (2026-11-06): 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. [Terminology and limitations](localization-hi.md). - Window › Help Bar shows or hides the tool-help strip at the bottom of the window apart from the status bar (`window.helpBar`). Each setting is kept with the UI preferences and in saved workspaces, and Presentation Mode hides both bars. Layouts saved before the setting existed show the Help Bar where they show the status bar (`help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar`, `a_help_bar_setting_the_file_lacks_is_saved`). - Czech render-site labels: desktop/web file filters, diagnostics, suggested preset names and contributor tooltips/plurals now use catalog lookups; gradients have Czech adjective agreement and printer marks have a separate context (PDF/Print and Summary). Search, Home, toolbar/panel tooltips and Preferences already look up their labels. Every complete catalog has rows for these labels and for the Roman and Japanese printer mark styles. Evidence: `i18n::tests::czech_render_site_follow_up`, `i18n::tests::complete_catalogs_translate_render_site_labels`, `dialogs::tests_modal::printer_mark_labels_are_distinct_from_language_names`; see [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). + - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with their notes name one item in the singular and more in the plural, in English and in each language's plural forms (`counted_status_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). @@ -795,8 +828,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). - The Transform panel's Align to Pixel Grid checkbox (`object.setPixelAligned`) gives paths and compound paths a pixel-aligned property, saved in the native file: their horizontal and vertical straight segments sit on whole points (half points under an odd centered stroke) with whole stroke weights, and every move, scale, rotation, reflection, Transform Each, Align move, Transform panel change, move of direct-selected anchors or of one anchor, move of a compound path's path on its own, artboard move, resize or copy that carries the art, Duplicate or paste that moves a copy, stroke edit and appearance edit that adds, removes, hides, repaints or reweighs a stroke snaps them again, while diagonal segments and curves keep their shape; a compound path made from an aligned path or compound path is aligned and snaps its paths with its own stroke; the box shows a dash for a mixed selection and is unavailable for type, images and groups ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::turning_it_on_snaps_the_path_in_one_undo_step`, `it_stays_aligned_through_transforms`, `it_stays_aligned_when_its_artboard_moves`, `diagonal_segments_and_curves_keep_their_shape`, `type_and_images_cannot_be_aligned`, `the_property_is_saved_and_read_back`, `stroke_edits_keep_it_aligned`, `a_compound_path_of_aligned_paths_is_aligned`, `a_compound_path_of_an_aligned_compound_path_is_aligned`, `a_stroke_without_paint_snaps_to_whole_points`, `moving_direct_selected_anchors_keeps_it_aligned`, `moving_one_anchor_keeps_it_aligned`, `moving_a_path_of_an_aligned_compound_path_keeps_it_aligned`, `artboard_options_and_artboard_copies_keep_it_aligned`, `appearance_edits_keep_it_aligned`, `placed_gradients_follow_the_snapped_path`, `duplicates_and_pastes_keep_it_aligned`, `paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned`, `the_art_of_a_linked_opacity_mask_keeps_it_aligned`, `a_linked_opacity_mask_follows_a_snap`, `aligning_direct_selected_anchors_keeps_it_aligned`, `global_edit_keeps_its_members_aligned`, `a_path_with_live_corners_snaps_its_inner_edges`, `geometry_edits_keep_it_aligned`, `other_path_edits_keep_it_aligned`, `panels::transform::tests::align_to_pixel_grid_shows_and_sets_the_property`). + - Align New Objects to Pixel Grid (`document.setup {alignNewObjectsToPixelGrid}`, a checkbox in New Document's Advanced Options and a checked item in the Transform panel menu) gives every path and compound path drawn in the document, the paths of a new grid or flare included, the pixel-aligned property, snapped in the step that draws it; it is on in the Mobile and Web presets and off in the others, saved presets and Recent keep it, and the document saves it. Type, images and groups do not take it, and art already in the document, pasted, duplicated or placed keeps its own property (VectorCraft's own rules) ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::align_new_objects_makes_new_paths_pixel_aligned`, `align_new_objects_reaches_grids_flares_and_add_on_shapes`, `align_new_objects_is_saved_and_read_back`, `tests::newdoc::align_new_objects_to_pixel_grid_follows_the_preset`, `panels::transform::tests::align_new_objects_menu_item_toggles_the_active_document`, `dialogs::new_document::tests::align_new_objects_checkbox_follows_the_preset_and_reaches_the_document`). - Object › Transform › Reset Bounding Box squares the box of every object inside the selected ones as well: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. Ungroup and the release commands then bring back boxes square to the page (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_squares_the_objects_inside_a_group`, `reset_bounding_box_squares_the_turned_members_of_a_square_group`, `reset_bounding_box_then_release_clipping_mask` and the other `reset_bounding_box_then_*` tests, `reset_bounding_box_leaves_the_art_of_an_unlinked_opacity_mask`). - Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). + - The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their tutorial counts and empty progress rings; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list` and `learn.show {tutorial}` script it ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). - The errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add Spine Point and Delete Spine Point) show in the status bar in the interface language: each has a row in every catalog that translates all status and error messages and in Bulgarian (`blend_spine_param_errors_are_translated`). - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. @@ -807,7 +842,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`. - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides), Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice) and Inventory Icons (Sword, Shield, Potion, Key and Gem, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides), Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice), Inventory Icons (Sword, Shield, Potion, Key and Gem, no default 9-slice) and Skill Icons (Attack, Defend, Heal, Buff and Ult, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a `<use>`, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - **Dynamic symbol appearance follows what an object draws** (VectorCraft's own rule): `symbol.instance.setAppearance` refuses a fill or stroke for an object of the art that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a nested symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect) with an error that names the key and the object, and the call changes nothing. Opacity, blend and `null`, which takes a stored change back, are taken for every object. Tests: `crates/engine/src/tests/dynamic_symbols.rs`. @@ -816,10 +851,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it stays within the art's box (guides outside the art are not supported yet) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. + - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. - A right-click over locked objects adds an Unlock submenu to the canvas context menu. The submenu lists up to 20 locked objects under the pointer, topmost first, by the name the Layers panel shows, and choosing one unlocks it (`layer.setProps`). A locked group is listed as one item. Objects on hidden, locked or template layers are not listed. - Native macOS save sheets offer a localised Format menu (#866), built from the request's existing format filters. It selects the suggested filename's format and updates the suffix when changed, including legacy `.drawcraft` names. `apps/vectorcraft/src/mac_save_format.rs` has filename regressions; an actual native SVG save, selection of PDF and cancellation without changing the saved document were verified. @@ -869,7 +906,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With the Artboard tool, Cmd/Ctrl+A after a click on a row of the Artboards panel selects every artboard, as the macOS menu bar's Select All does then; the active artboard stays active, and the art's selection does not change. After a press outside the panel's list, Cmd/Ctrl+A selects every object again. It used to select every object after a click in the panel too. Public reference: [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html). - Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) add a new fill and a new stroke to the selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a new fill and a new stroke. Keyboard Shortcuts lists both under Window › Appearance. - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. - - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning of the character before it. + - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning there: of the character before it, or at the start of a line the space before the character after it (#5111). - Cmd/Ctrl+Alt+K (`type.highlightKerning`) and Cmd/Ctrl+Alt+Shift+F (`type.highlightFontName`) show the Character panel and give its Kerning field the keyboard focus with the value selected, or open its font family menu with the search field focused, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for highlighting kerning and the font name field. The page lists the same key for selecting the tracking value; `type.highlightTracking` focuses the Tracking field the same way and has no default key in Keyboard Shortcuts. - Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a layer through the New Layer dialog box. OK adds the layer above the current layer, and Cancel adds none. Cmd/Ctrl+L still adds a layer without the dialog. - F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for making a new symbol. OK makes the symbol and puts an instance of it in place of the art, and Cancel makes none. With nothing selected, F8 opens no dialog, and the status bar says that nothing is selected. Shift+F8 and Cmd/Ctrl+F8 still show the Transform and Info panels. @@ -905,6 +942,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A marquee selects an Intertwine group only when it reaches one of the group's members, as for a plain group, and it selects a repeat only when it reaches one of the copies the repeat draws. Direct and Group Selection's marquees select the anchor points of an Intertwine group's members, not the group, and Group Selection's E marquee selects the members inside it. A key object needs another selected object outside it. A Shift-click or any other change that leaves one object selected clears the key, and `select.key` sets none on one object or on a group selected with only its own members. With one object selected, the Align panel, the Control bar and the Properties panel align it to the artboard whatever Align To is set to. With two or more objects selected and no key object, Align to Key Object makes the topmost of them the key, whatever order they were selected in, and the Align panel, the Control bar and the Properties panel align to it. Align To keeps its Selection or Artboard choice and shows it again once the key is cleared. + The Control bar has an Align To menu after its Align buttons. The public documentation offers Align to Selection, Align to Key Object and Align to Artboard in the Control panel (VectorCraft's Control bar) as well as in the Align panel ([Move, align, and distribute objects](https://web.archive.org/web/20250115013546/https://helpx.adobe.com/illustrator/using/moving-aligning-distributing-objects.html)). The menu shows the icon of the choice the Align panel's Align To shows, and a pick sets the same choice as the Align panel's buttons do. Align to Key Object is off while no key object can be made. When the bar runs short of room, it drops the Distribute buttons first, then the Align To menu, then the Align buttons. Object › Align aligns objects as the align buttons do: it aligns one object to the active artboard whatever Align To is set to, and otherwise it aligns to the key object while there is one, else to the Align To choice, which is saved with the preferences (`ui.inspect` → `ui.align_to`). With direct-selected anchor points, Object › Align aligns the points to their own bounds. While one object is selected, Align To shows Artboard. Edit › Keyboard Shortcuts lists each of the Align panel's Align Objects, Distribute Objects and Distribute Spacing buttons under Align, with no default shortcut, as the reference app's [release notes](https://web.archive.org/web/20261006170350/https://helpx.adobe.com/illustrator/desktop/new-features/release-notes.html) describe for its Align and Distribute commands. A shortcut set there runs what a click on the button runs, with the Align To choice, the key object and the Distribute Spacing value (`align.horizontalLeft` and the other `align.*` UI commands). The command palette lists `select.key` as Cancel Key Object, and a pick cancels the key object (#541). @@ -913,6 +951,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Agents read the key object: `select.key` returns it, and `document.inspect` and the `ui.pointer` and `pointer_gesture` replies report it as `key`. `select.key` with an id that isn't a selected top-level object returns an error and leaves the key unchanged. The Select menu's Same commands, its Object commands that select art, Next Object Above and Below, saved selections and the Magic Wand (#2655) select only objects that Select All selects and objects inside them: nothing hidden or locked, nothing in a hidden or locked group, layer or sublayer, nothing on a template layer, and in isolation mode nothing outside the isolated group or layer. In isolation mode Select All, All on Active Artboard and Inverse select nothing while the isolated group or layer, or a group or layer it is in, is hidden, locked or a template layer. Select ▸ Object ▸ Bristle Brush Strokes selects the objects whose topmost stroke has a bristle brush, whatever the brush is named, and leaves out objects whose brush is of another type, also when its name has "Bristle" in it. + Select ▸ Object ▸ Not Aligned to Pixel Grid (`select.object.notAlignedToPixelGrid`) selects the paths and compound paths whose pixel-aligned property is off, whatever their coordinates, and leaves out guides, type, images, groups and the paths inside a compound path ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185); `tests::pixelalign::not_aligned_to_pixel_grid_selects_paths_without_the_property`, `not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected`). Align and Distribute Spacing keep a compound path or selected group that contains the key object in place, as they keep the key object itself. Align to Glyph Bounds (#4231): the Align panel menu's Align to Glyph Bounds submenu has Point Text and Area Text, each checked while on (`alignGlyphBoundsPoint`, `alignGlyphBoundsArea`, off by default). With one on, Align, Distribute Objects and Distribute Spacing measure that kind of type by the ink of its glyphs instead of its em box (point type) or frame (area type), so lowercase type aligned to a rectangle's top lines up the tops of its letters; the other kind, type on a path and type in a selected group are measured as before, and Use Preview Bounds adds the characters' strokes ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html); `tests::glyphbounds`, `panels::align::tests::align_to_glyph_bounds_toggles_point_and_area_text`). The Character and Properties panels' controls for the same setting are not done. Anchor Align moves the selected points to their bounds or the artboard (#1180). Repeating it, or moving by at most 1e-9 pt on both axes as whole-object Align does, leaves the document, Undo, Redo and saved state unchanged; actual moves still take one undo step. `crates/engine/src/tests.rs` covers repeated alignment, rounding-only alignment, unchanged handles, saved state, command recording and Undo/Redo. @@ -932,7 +971,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Curvature point markers are circular, with no direction handles. While drawing, its own point feedback replaces generic selection markers; existing paths use the selection overlay, including partial selections and Hide Edges. Anchor Size applies, and Direct Selection and Pen retain their handles. The real egui-frame regressions in `crates/ui-egui/src/canvas.rs` verify marker positions, counts and unchanged documents (#1236, in part); the existing-path interpolation request remains open. The curve through the points (`curvature_spline` in `crates/tools/src/draw2.rs`) makes each stretch of three points follow the circle through them: a smooth point's handles lie along that circle's tangent, each `chord / (3 cos²(α/2))` long (α between handle and chord, capped at 90°), and the ends of an open path mirror their neighbour's tangent in their chord, so a J or a U curves evenly, a turn tighter than 30° comes to a point, and uneven spacing doesn't loop; the rubber band, a dragged or inserted point and `path.convertAnchor` to smooth use the same rule, while the Pencil's fitting keeps its own; `tests/draw2.rs` checks that the rubber band is the path the click makes (#1236, in part). The Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512). While Alt is held during a Paintbrush stroke or before a press with no path selected that the Smooth tool can act on, the Paintbrush shows a closing cursor (a crosshair with a ring), and so does the Pencil with Alt key toggles to Smooth Tool off when Alt is pressed after the drag starts; releasing the mouse button with Alt still held closes the path. Before a Paintbrush press with such a path selected, Alt shows the Smooth cursor, and holding Alt at the press smooths that path with the Smooth tool's radius and Smooth Tool Options' Fidelity. A Pencil drag started with Shift or Alt held draws a straight line instead, which stays open. With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, whose ends snap to Smart Guides, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short line), and over an end of a selected open path, where the line continues the path, a path-continuation cursor (the same line leaving a small square), as the page describes. - - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). @@ -952,7 +991,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). - - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). + - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Moving the closing anchor with Space held, which that page also describes, is still missing. Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). @@ -1060,6 +1099,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Artboards › Fit to Selected Art resizes the active artboard (`artboard.fitToSelection {index}`). It used to resize artboard 1 whichever artboard was active. When an action plays, its Fit to Artwork Bounds and Fit to Selected Art steps that name no artboard resize the artboard that is active then. Object › Artboards › Fit to Artwork Bounds and the Artboards panel menu's Fit to Artwork Bounds fit each selected artboard (those the Artboard tool has selected, else the active one) to the art on it, as the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page describes (`artboard.fitToArt {indices}`). An object partly on an artboard counts for each artboard it overlaps, and an artboard with no art on it keeps its size and place. They used to fit the active artboard to all the art in the document. The Artboards panel menu's Duplicate Artboards copies each selected artboard (those the Artboard tool has selected, else the active one) with its art, in one undo step, and the copies are then selected, as the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page describes. With the Artboard tool, Copy and Cut take every selected artboard with its art, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes, and Paste brings them all back in one undo step (`artboard.duplicate`, `artboard.copy` and `artboard.cut` with `indices`). The copies keep their places relative to each other, together right of the last artboard. All three used to act on the active artboard only. + With the Artboard tool selecting several artboards, Paste in Place, Paste in Front and Paste in Back put a copy of the copied art on each, where it was on the artboard it was copied from, in one undo step, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes (`artboards` on the three commands). Art copied from no artboard keeps its place on the first selected artboard and its offset to it on the others, and an `artboard` or `artboards` index the document does not have is an error; these rules are VectorCraft's own. The three commands used to paste one copy, on the active artboard, and an `artboard` index the document did not have pasted the art where it was. A replay of the journal repeats a Cut or Copy made with the Artboard tool on the artboards it took (`edit.cut` and `edit.copy` record `selectedArtboards` and `art`), whichever tool is chosen in the new session and whatever is selected there. A recorded action follows the tool chosen when it plays. The replay used to act on the objects selected then, or stop with nothing selected. This rule is VectorCraft's own. With the Artboard tool, the canvas context menu lists the entries of the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page in its order: Cut, Copy, Paste at the pointer, Undo, Redo, New Artboard, Duplicate Artboards, Rename (`artboard.rename`), Delete Artboards, Delete Empty Artboards, Select All Artboards (`artboard.selectAll`), Lock Artboards and Unlock Artboards, Rearrange, Fit to Artwork Bounds, Switch Orientation (`artboard.switchOrientation`), Artboard Options and Export. A right-click on an artboard that is not selected selects it first. The Artboards panel menu's New Artboard adds the artboard in one undo step and makes it the active one, as the panel's button, the Control bar and Properties do; with the Artboard tool it is then the only one selected. This is VectorCraft's own rule. The menu item used to leave the active artboard where it was. @@ -1083,6 +1123,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. The shared planar map keeps a segment cap (65,536 since #937, was 4,096) and its filled-area fallback; other Pathfinder operations are unchanged. - Type that Transform effects only move and copy (no scale, rotation, reflection or Random) exports as type in each place, and PDF export writes every copy as selectable, searchable text, when its characters are in solid colors without underline or strikethrough, the type object has no fills or strokes of its own, no inline graphics and no perspective, its transform does not scale or shear stroked characters, and the copies do not overlap. When the effect is on the type itself, the type can also have transparency, an opacity mask and raster effects. When the effect is on the group or layer holding the type, the type has no transparency or effects of its own and is not in a clipping path, the group or layer has no fill, stroke or Pathfinder effect of its own, and no group between them has a fill, stroke, Pathfinder or geometry effect. Type still exports as outlines when the effect stops its copies early, or when the copies would number more than 10,000 or take more than 20,000,000 bytes of document data, and so does other type under a geometry effect. - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). + - With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`. - Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). @@ -1118,6 +1159,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). +- **Kerning at the start of a line:** at the Type tool's caret before the first character of the text, of a paragraph, or after a forced line break, the Kerning field, Alt+←/→ (Alt+↓/↑ in vertical type) and Reset Tracking and Kerning set the space before the character after the caret (`kerningBefore`), as the reporter of #5111 describes the reference; the character moves along its line and the rest of the line follows, as one undo step (#5111). It used to do nothing there, or kern the invisible line break. Inside a line the caret still kerns the character before it. A line that wraps in area type takes no space before its first character, and Touch Type still moves a line's first character only up and down. SVG export starts the line where the character is drawn, and on a path writes the space as the first character's `dx`; vertical type moves the character down its column. A space on the first letter of a ligature keeps the ligature whole. Tests: `tests::caret_kerning` (engine), `tests::kerning_before` (text), `the_space_before_a_lines_first_character_moves_its_tspan` (SVG). - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own: each pair moves part of the way toward the font's own stem spacing (the gap of `nn`, else `HH` or `oo`), keeps at least part of that gap where the outlines come closest, and changes by at most 0.12 em tighter or 0.06 em looser, so ordinary text keeps the font's spacing (#5336). Ideographs, kana, hangul, fullwidth and CJK punctuation forms and dashes keep the font's spacing. Optical keeps its mode across cosmetic style runs. Choosing Optical clears manual pair values, as Auto does, and leaves additive tracking intact; a manual value typed afterwards replaces that pair's correction ([Adjust kerning and tracking](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-kerning-and-tracking.html)). Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. @@ -1151,15 +1193,21 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Select › Object › All on Same Layers takes the layers only of the selected objects that can be selected: an object that is hidden or locked, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group adds no layer. This is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. Object › Flatten Transparency, the Flattener Preview, and EPS, PDF and print output that flatten transparency stop building a group's flat regions at the first region past the raster/vector balance's limit (10^(balance/20), rounded down) and rasterize the whole group without building the remaining regions. Building every region gives the same flattened art and the same files. With Clip Complex Regions on, a group builds every region and its image is clipped to them. + Object › Flatten Transparency, the Flattener Preview, and EPS, PDF and print output that flatten transparency leave art without transparency as it is when it overlaps only other art without transparency, unless it overlaps a member of a see-through object's group and lies above that member and below the group's topmost object. Such art joins the group, and the group takes the place of its topmost object, so the stacking order stays the same. In files without transparency with Clip Complex Regions on, art under the group within one image pixel of a member joins it too. The 1 pt antialiasing margin goes around a group's art once, however deeply its groups nest. On a grid of 3,000 rectangles with a 0.5 pt stroke, 60 of them with a drop shadow, the Flattener Preview counts 180 affected objects where it counted 3,000, and Flatten Transparency with the Medium preset makes 240 flat regions and 2 images where it made one image of the whole grid. These rules are VectorCraft's own (`tests::flatten::opaque_art_that_touches_only_opaque_art_stays`, `tests::flatten::opaque_art_the_group_would_move_under_joins_it`). New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. + Type › Type on a Path › Center on Top and Center on Bottom (`type.pathCenter.top`, `type.pathCenter.bottom`, also on the Contextual Task Bar for type on a closed path) slide type on a closed path so the middle of its span lands on the path's topmost or bottommost point as drawn, keep the span's length, and set the first paragraph to Center unless it is Center or Justify Center. This is VectorCraft's own behavior (`crates/geom/src/arc.rs`, `crates/engine/src/tests/pathtype.rs`). Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). + Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: reshaping or scaling the path fits the text again; one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off, threading the type or Release Type on a Path keeps the drawn sizes; SVG, EPS, legacy `.ai` and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, the sizes are written into the characters, threaded frames cannot use it, and Convert To Point Type turns it off, keeping the sizes (`crates/engine/src/cmd/typecmd/block_tests.rs`). + Type › Dynamic Text Presets › Circle, Arch and Bow (`type.dynamicTextPreset`) put point type or type on a path on a circular, upward-curving or downward-curving path with Dynamic Text on, with the text's position against the path (above, center, below) and its direction ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)). VectorCraft's own rules: the circle is as wide as the text and the text starts at its bottom; Arch and Bow are a 120° arc whose chord is as wide as the text; above, center and below are Align to Path's Descender, Center and Ascender (`crates/engine/src/tests/dynamic_text.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. The frames of threaded text share one writing direction: Type › Type Orientation (`type.orientation.vertical`, `type.orientation.horizontal`) in one frame sets every frame, threading frames gives the thread its first frame's direction, frames taken out of a thread keep theirs, and the story flows through every frame in the thread's direction. Type › Optical Margin Alignment (`type.opticalMarginAlignment`) hangs the punctuation and letter edges at the ends of a type object's lines outside its margins: at the left of left-aligned lines, at the right of right-aligned lines, and at both ends of centered and justified lines, in point and area type of left-to-right paragraphs. Quotation marks, hyphens, full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their width. It is off by default and saved with the type object. Justification's Glyph Scaling leaves the glyphs that hang at their width, so they hang exactly their share, and Standard burasagari counts what hangs at a line's start as room before hanging a comma; `crates/text/src/tests/hang.rs` checks whole paragraphs with both composers, ragged, centred and justified, with Line-end Punctuation Half Width and bidirectional lines. Optical Margin Alignment and Roman Hanging Punctuation hang right-to-left paragraphs of point and area type, and type on a path whose first paragraph runs right to left, too. Auto aligns a right-to-left line at its right, or at the end bracket of a path, so it hangs there. A right-to-left line is read from right to left: where it hangs at its left margin, `."` ending it hangs both glyphs. The Paragraph panel menu's Kinsoku Shori Type (`text.setFormat {kinsokuType}`, with the East Asian options) picks Push In First, Push Out First or Push Out Only for each paragraph: a character the Kinsoku Set keeps off a line's start or end is set on the line, with the line's gaps next to CJK characters closed by at most a tenth of an em each to fit, or moved to the next line with the character before it. Push Out First pushes in only when pushing out would leave the line more than an em short. Push Out Only is the default, the setting is saved only when it is not, and paragraph styles carry it. - The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Roman Hanging Punctuation off, no kashidas and no tab stops, as one undo step. + The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. + The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. @@ -1183,6 +1231,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). + With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. @@ -1228,6 +1277,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own. Envelope Options › Anti-Alias off draws an envelope's distorted images without smoothing, and Preserve Shape Using › Transparency gives each piece of a distorted image an opacity mask in its shape instead of a clipping mask ([Envelope panel options](http://web.archive.org/web/20260513013456/https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/envelope-panel-options.html)). + With Envelope Options › Distort Appearance on, type's strokes (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight instead of bending with the art, as the drawn art of users' `.ai` files strokes type in an envelope. This is VectorCraft's own rule from those files: the public page names applied effects and graphic styles, not strokes. This holds in an envelope inside an envelope too. Paths' strokes, geometry effects (type's included), opacity masks (on type too), linear gradients and pattern fills bend as before; Expand gives type's bent outlines with their strokes on them. The visual bounds of envelopes, blends and repeats, and the reach of symbol art, count type's character strokes as type's own visual bounds do (half the weight of a centred stroke); they left them out, though those strokes already painted past an envelope's grid. Envelopes of stroked type made in VectorCraft before this draw their strokes at their own weight now (#6644; `crates/engine/src/tests/envelope_distort.rs`, `crates/effects/src/bake/tests.rs`). The four polynomial distributions are original approximations of the public description, not measured numeric parity. See [Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). A blend in a `.ai` or EPS opened from its editing data keeps a Specified Distance spacing with its distance ([Blend Options](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-options-overview.html)) where VectorCraft lays out as many steps between each pair of keys as the file draws, in the same places and colors. A Smooth Color blend opens live only where VectorCraft's own Smooth Color step count equals the drawn steps, and VectorCraft often counts a different number. A blend that VectorCraft doesn't lay out as drawn keeps its drawn steps with a note (`import::ai::tests::a_blend_keeps_its_spacing`, `a_blend_of_three_keys_keeps_its_distance_between_each_pair`, `a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them`). @@ -1245,13 +1295,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A drag with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. + The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Move All and Select/Move widgets and Detach are missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Select/Move widget and Detach are missing. Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. + Objects on Path Move All widget: with one Objects on Path group selected whose objects have room to move, the Selection and Objects on Path tools show a diamond below its first object; dragging it along the path, round its bends, moves every object along the path together in one undo step, keeping the distances between them (`object.objectsOnPath.options {start}`). On an open path the widget shows only when the distance from the first object to the last is shorter than the path, so not for objects spread evenly from end to end, and the objects stop at the path's ends; on a closed path they go on round across its first anchor. The first object's distance along the path shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Evidence: `objects_on_path::tests::{dragging_the_move_all_widget_moves_every_object_along_the_path, a_move_all_drag_on_a_closed_path_goes_round_across_the_first_anchor}` in `crates/tools`, `canvas::tests::a_selected_objects_on_path_group_shows_its_move_all_widget_when_it_has_room` in `crates/ui-egui`. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. - - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, five gradient libraries and a pattern library (Geometric Patterns, whose swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. + - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and two pattern libraries (Geometric Patterns, and Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. @@ -1263,6 +1315,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. + Unchecking Show Recent Colors in the Color panel's menu hides its Recent Colors row, and checking it shows the row again ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). In VectorCraft the item is checked by default and kept between sessions, applied colors still join the list while the row is hidden, Hide Options hides the row either way, and the Swatches panel keeps its row (`ui.colorPanel {recentColors}`). Tests: `show_recent_colors_hides_and_shows_the_row` in `crates/ui-egui/src/panels/color/tests.rs`. A Cmd/Ctrl-click on the Color panel's spectrum applies Complement and a Cmd/Ctrl+Shift-click applies Invert to the active Fill or Stroke (`paint.complement`, `paint.invert`); with Alt also held, the click recolors the inactive one, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) list them. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). @@ -1286,11 +1339,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. - The Gradient panel's Delete Stop sits at the right end of the ramp, level with it, so a panel too short to show the stop fields still shows it; it deletes the selected stop (never below two), as dragging a stop down off the ramp does (#5403). + - Conic gradients, VectorCraft's own gradient type: the stops sweep once around the center from the vector, clockwise on the page (a negative aspect, or a reflection, turns the sweep the other way), with a Conic button in the Gradient panel's Type row and the Gradient tool's extent ellipse and aspect handle; they follow transforms, Expand into wedges or a mesh, open from `.af` files, and export to PDF as a function-based shading that PDF import reads back as a conic gradient; SVG, EPS and legacy `.ai` files get solid wedges, and CSS a `conic-gradient`. + - Diamond gradients, VectorCraft's own gradient type: the stops run from the center out to a square with a corner at the end of the vector (the aspect stretches it into a rhombus), with a Diamond button in the Gradient panel's Type row and the Gradient tool's square and aspect handle; they follow transforms, Expand into nested squares or a mesh, and export to PDF, SVG, EPS and legacy `.ai` as four linear gradients, one for each quarter of the square (an image in PDF and SVG for translucent stops, a dithered fill, the Perceptual method other than spot color shadings in PDF, or a square with no area), and on type characters in SVG as a radial gradient; PDF import reads a function-based shading whose color is the same along each square about its origin as a diamond gradient. - The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. + - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>) and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -1305,10 +1360,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). Document Info's Pattern Objects category lists the objects whose fill or stroke is a pattern, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, each by name with the patterns it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "patterns"}`, `patternObjects`). Listing an object with a pattern fill and a pattern stroke once, listing objects inside groups and type objects whose characters use a pattern, and leaving out hidden fills and strokes, strokes with no width, guides, a compound path member's own fills and strokes, an image's fills and strokes without a shape, characters the type does not draw and patterns no art uses, and counting the listed objects in Objects, are VectorCraft's own rules. Test: `cmd::docinfo::tests::info_lists_the_pattern_objects` (vectorcraft-engine). + Document Info's Gradient Objects category lists the objects whose fill or stroke is a gradient, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as the count of objects with gradient fills or strokes. Each object is listed by name with the gradients it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "gradients"}`, `gradientObjects`). Naming a linked gradient by its swatch and any other gradient by its kind, and leaving out paint that draws nothing by the rules Pattern Objects follows, gradient swatches no art uses, gradient meshes and gradients drawn by effects, are VectorCraft's own rules. Objects counts the listed objects as Gradient Objects. Test: `cmd::docinfo::tests::info_lists_the_gradient_objects` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. - Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes. With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. + A scatter, art or pattern brush dragged from the Brushes panel onto an empty part of the canvas places a copy of its art there to edit, as the [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) page describes (`brush.placeArt`). The copy is centered where it is dropped. A pattern brush comes out as its tiles in a row, 10 pt apart, each in a group named for its tile, with an unpainted rectangle at the back of a tile that has a repeat frame. The centering and the tile layout are VectorCraft's own rules. Evidence: `tests::brushsym::place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped`, `tests::brushsym::pattern_brushes_place_their_tiles_in_a_row` (vectorcraft-engine), `canvas::tests::a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there` (vectorcraft-ui-egui). + Art Alt-dragged (Option-dragged on macOS) from the canvas onto a scatter, art or pattern brush in the Brushes panel becomes the brush's art, as the [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) page describes (`brush.replaceArt`). When strokes use the brush, a dialog asks whether to change those strokes (Apply to Strokes) or leave them as they are (Leave Strokes), or to cancel, the choice the [help reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=263) (archived copy, p. 263) describes for a modified brush in use. Leave Strokes keeps the brush and its strokes as they were and adds a copy of the brush with the new art, named "`<name>` copy", which becomes the current brush. That copy is VectorCraft's own rule. A pattern brush takes back the tile groups `brush.placeArt` places, frames included, and takes other art as its side tile, which is also VectorCraft's own rule. Evidence: `tests::brushsym::replace_art_applies_to_strokes_or_leaves_them_on_the_old_brush`, `tests::brushsym::placed_pattern_tiles_go_back_into_the_brush_tile_by_tile`, `tests::brushsym::other_art_replaces_the_side_tile_of_a_pattern_brush` (vectorcraft-engine), `dialogs::brush_replace_art::tests::leave_strokes_adds_a_copy_and_cancel_changes_nothing`, `panels::brushes::tests::art_alt_dropped_on_a_brush_with_art_replaces_its_art`, `canvas::tests::art_alt_dragged_off_the_canvas_reaches_the_panels_as_the_original` (vectorcraft-ui-egui). In Pattern Brush Options, a menu below the Outer Corner Tile and the Inner Corner Tile sets each to the brush's own corner art (Original), None, or a tile made from the side tile: Auto-Centered stretches one side tile around the corner, Auto-Between bends a side tile on each side into the corner's diagonal, Auto-Sliced cuts a side tile on each side along the diagonal, and Auto-Overlap runs a side tile on each side past the corner. Auto-Sliced masks the tiles at the diagonal, so their outlines stay as drawn. Brushes saved without these choices draw their corners as before (`brush.options` `outer_source`, `inner_source`). Evidence: `tests::pattern_auto_corners_fill_each_corner_of_a_square`, `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), `dialogs::brush_options::tests::pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile` (vectorcraft-ui-egui). Pattern brush corner tiles are square to the side tiles at a right-angle corner and turn 90° from one corner to the next, as the [Using Illustrator CS5](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) help (About patterns) describes. That document's steps for making corner tiles build both the outer and the inner tile as the corner joining a side tile on its right to one below it, and the brush reads corner art that way, with Flip Along and Flip Across or without (#6110). At corners that are not right angles, the tile is turned halfway between the two sides, which is VectorCraft's own rule. Evidence: `tests::pattern_corner_tiles_are_square_to_the_sides`, `tests::pattern_corner_tiles_sit_on_the_corners_diagonal` (vectorcraft-brush). @@ -1326,8 +1383,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. - - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eight generated style libraries (including Game HUD and Status Effects) save and load as `.vcstyles`. + - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; ten generated style libraries (including Game HUD, Status Effects, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. + The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. + Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Neutral wording:** labels, MCP tool text, docs and packaging use neutral names, and `cargo xtask brands` (part of `cargo xtask ci`) fails on vendor names. @@ -1433,11 +1492,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. The drawn art of these files strokes type in an envelope along its bent outlines at the stroke's own weight, Distort Appearance on or off, and VectorCraft draws it so (#6644): an envelope of stroked type whose grid squeezes or stretches it opens live where it draws as that art. In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). - PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). + PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, off by default) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard. PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. + A PDF/A-2b export at PDF 1.4 with a page longer than 14,400 pt is written as PDF 1.6 with a `UserUnit` and a warning, whether or not `longPagesInPoints` is on, so its page boundaries stay within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13) unless the page is too narrow for that (`crates/pdf/src/tests/marks.rs`). PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one. Layers the file leaves out are left out of the flattening, and transparent art that a clipping path hides entirely is removed (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). @@ -1455,19 +1515,25 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `document.pdfInfo` reads an EPS, a `.ps` file or a `.ai` in PostScript form as one page the size of its bounding box (a US Letter page without one), and its `thumbnail: 1` is a PNG of what that page prints (`crates/engine/src/cmd/fileio/tests_pdfimport.rs`). - EPS export with Use Artboards writes a central EPS file of the whole document, bounded by its visible art, beside the file of each artboard when it writes two or more artboards; a document with no visible art gets only the artboard files (`crates/engine/src/cmd/fileio/tests_eps.rs`). EPS export writes a linear or radial gradient of tints of one spot color (and paper white) in that ink's Separation space, at Level 2 and 3, and at Level 3 one that mixes a spot color with process or gray colors, or two spot colors, in a DeviceN space of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. At Level 2, such a mix is written in process colors with a warning. In an RGB export, a gradient that mixes a spot color with RGB or Lab colors is written without the spot ink, with a warning; a CMYK export converts those stops to CMYK first, and the gradient follows the rules above. A Perceptual gradient of spot colors, and a mix whose DeviceN space would need more than 32 inks or a spot color named Cyan, Magenta, Yellow or Black, are also written in process colors with a warning (`crates/eps/src/tests.rs`). A spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4), is written as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients and DSC comments; Registration still prints on every plate (`tests::spot_inks_named_all_or_none_are_written_under_names_of_their_own`). + EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels. There is no PSD import options dialog yet (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). + - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). + - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). + - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. - EPS and PostScript `.ai` import undoes the TIFF predictor (`/Predictor 2`) of `FlateDecode` and `LZWDecode` data at 1, 2, 4 and 16 bits a component as well as 8: each component adds the same component of the pixel to its left within its bit width, 16-bit components add as big-endian numbers, and each row starts again (ISO 32000-1 §7.4.4.4; `crates/eps/src/import/tests_images.rs`, `crates/engine/src/cmd/fileio/tests_epsimport.rs`). At those depths the image drew the stored differences instead of its samples. - - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (version 2000, 1 mm = 1 unit, 256 colors, Maximize Editability with Alter Paths off, Outline Text, PNG placed images), and the menu shows Custom once a field changes (`the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines`, `the_cnc_preset_sets_the_options_that_are_not_given`, `the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom`); VCarve QA remains pending. + - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (version 2000, 1 mm = 1 unit, 256 colors, Maximize Editability with Alter Paths off, Outline Text, placed images and fill hatches left out), and the menu shows Custom once a field changes (`the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines`, `the_cnc_preset_sets_the_options_that_are_not_given`, `the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom`); VCarve QA remains pending. + - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. @@ -1476,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one; the title is not changed (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). + - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root `<title>`. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). - PDF export and PDF-compatible `.ai` and `.ait` saves write File Info's copyright notice, URL and status to the XMP packet (`dc:rights`, `xmpRights:WebStatement`, `xmpRights:Marked`), so a PDF or `.ai` opened from its pages keeps them (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). - Opening a PDF or PDF-compatible `.ai` whose XMP packet nests elements more than 256 deep no longer overflows the stack: File Info leaves the packet out and takes the document information dictionary's values (`crates/pdf/src/tests/file_info.rs`). @@ -1543,7 +1609,6 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 123 ms instead of 403 ms with an open path of 200,000 anchors in view (103 ms with nothing changed), and 13 ms instead of 26 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. When the stroke of a path moved this way has a gradient along or across it, the renderer also draws the gradient from the slices it made before the move, moved by the same offset. It makes the slices again when the path is scaled, rotated or edited, and when the stroke or its gradient changes. The pixels are the same. On Windows at 1600 × 1000, the frame after a 1 pt nudge of an open path of 200,000 anchors takes 75 ms instead of 1,237 ms with the gradient along the stroke and 69 ms instead of 1,420 ms with it across, and with an open path of 50,000 anchors 22 ms instead of 313 ms and 21 ms instead of 352 ms (medians of five interleaved runs). - The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). When an edit changes a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve), the canvas draws again where its art was and is, measured by that art: type and groups were measured by their letters or members, so a shallower or turned solid left pieces of the old one on the canvas. When the canvas draws the part on its own thread, it measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type, where they cropped it to the letters, and Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once unless the object has brushed strokes: 30 extruded type objects measured over 30 artboards take about 2 ms in a release build, where measuring their letters took under 1 ms. A document's first frame builds every 3D object's solid, off the view too, to know whether it reaches into the view. When only anchors of a path or compound path move, the canvas draws again only around the segments that start or end at a moved anchor, grown by the farthest its strokes reach, instead of the whole object before and after. This holds while every fill and stroke is a solid color, and the strokes have no dashes, width profile, arrowheads or brush, and the object has no effects or opacity mask; any other object still counts whole. On a loaded Windows machine at 1600 × 1200, single-threaded in a development build, the frame after one anchor of a filled closed path moves takes 16.6 million CPU cycles instead of 56.4 million with 50,000 anchors and 65.6 million instead of 180.0 million with 200,000 anchors (medians of 15 edits, the two builds run in turn three times). Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. @@ -1639,7 +1704,6 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.<id>`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. -- **Plug-in instruction budget at a bulk memory instruction:** a run that pauses where one slice of its instruction budget ends keeps the instructions the slice still held. A `memory.fill` or `memory.copy` that the slice can't pay for in full runs on the next slice, so a run whose budget covers its work finishes; a run ends with `Limit("instruction budget")` only when the instructions it has left can't pay for the next instruction. Regressions: `crates/plugins/tests/abi.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. @@ -1647,19 +1711,30 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode <subcommand>` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. +- **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-<process id>.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. +- **A disabled plug-in whose update stays in the store is turned on:** when `plugin.install` writes a module that lists permissions to the `Plug-ins` folder, its grant can't be written, and the folder can't be returned to the old module (or, on a first install, the new module can't be removed), the folder holds the new module, so a disabled plug-in is turned on, by id and by stored file, as for any install the folder holds. The old grant, or none, doesn't cover the new module, so the next start skips it until it is approved. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in instruction budget at a bulk memory instruction:** a run that pauses where one slice of its instruction budget ends keeps the instructions the slice still held. A `memory.fill` or `memory.copy` that the slice can't pay for in full runs on the next slice, so a run whose budget covers its work finishes; a run ends with `Limit("instruction budget")` only when the instructions it has left can't pay for the next instruction. Regressions: `crates/plugins/tests/abi.rs`. Scores and hours unchanged. +- **Bulk memory fuzz cases use the host's fuel constants:** `crates/engine/tests/plugin_fuzz.rs` samples runs around one slice of the instruction budget and lengths around the bytes one unit of fuel pays for with `vectorcraft_plugins`' own `FUEL_SLICE` and `BYTES_COPIED_PER_FUEL`, so the sampled cases move when either value changes. Regressions: `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. +- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. +- **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin.<id>.<command>` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. -- **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. +- **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. +- **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged. +- **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in settings and cache (G17, #2191):** at plug-in API level 2 a plug-in with the `settings` permission keeps settings of its own (`env.vc_settings_get`, `_set`, `_delete`) and one with `cache` a cache the user can clear (`env.vc_cache_read`, `_write`, `_clear`), under its id in the `Plug-ins` folder. Keys are plain names, never paths; VectorCraft's own caps refuse a write past 256 settings, 1 MiB of settings or 512 MiB of cache; a damaged settings file is moved aside and the settings start empty. `plugin.clearCache` empties a cache, `plugin.list` and `plugin.info` give `cacheBytes`, replacing a plug-in keeps its storage and `plugin.remove` deletes it. Another module under an id that is installed or has storage installs only with `replace: true`, which the app asks the user for; each storage call counts the whole settings file or cache entry it reads and writes toward the run's 1 GiB. Regressions: `crates/plugins/src/storage.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_clear_cache.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in settings and cache totals in memory (#6228):** the settings stay in memory while `settings.json` keeps its size and modified time, a set to the same value writes nothing, every other change is written to the file before the call returns, and `cacheBytes` comes from a total kept while the `cache` folder keeps its modified time. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in settings a failed removal can't move back:** when `plugin.remove` can't remove the grant and can't rename the plug-in's `.removed` folder back, its error names that folder, and the next load, install or removal of the plug-in renames it back instead of deleting it. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in effects after a plug-in changes:** when a plug-in is installed for the first time, installed again or removed (`plugin.install`, `plugin.reload`, `plugin.remove`, File › Open of a `.wasm` file, the Additional Plug-ins Folder preference), the next frame the canvas draws uses the plug-ins then installed for objects with a plug-in effect and their raster effects, for the blends, envelopes and repeats that show such objects, and for pattern tiles and symbol instances whose art holds one. @@ -1672,6 +1747,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs match main byte for byte; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. +## Eyedropper character dimensions (2026-11-11) + +`appearance.copyFrom` reads the source's effective character dimensions and converts them into each target's local text space, preserving target placement, rotation, shear and reflection (#6404). Point and area text, grouped text, highlighted ranges, reverse and remembered sampling, attribute opt-outs, Undo/Redo and native-file round trips are regression-tested. Picks with unrepresentable dimensions or text that would extend beyond the canvas leave the document, paint defaults and remembered sample intact. Paint-only copying remains available. Tests: `crates/engine/src/tests/eyedropper.rs` (`scaled_type_pick_*`). Scores and estimates unchanged. + ## Highlighted-text Eyedropper (2026-10-21) Type/Eyedropper switches preserve highlighted characters; sampling changes only their enabled @@ -1890,6 +1969,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Cutting Tools add-on: Stencil Bridges (2026-11-12) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. @@ -1918,6 +2001,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Document Tools › Batch Trace Folder (`addon.document.batchTraceFolder`) asks for a folder of images and a destination folder, traces each image with a preset (optionally expanded) and saves it there under its own name as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps`, without replacing files, closing each image's document again and reporting the images it couldn't trace (#4921). A folder with more than 1,000 entries is refused rather than traced in part. Optional settings reject null and values of the wrong type before opening images. Tests: `cmd::addons::document::tests::batch_trace_folder_traces_and_saves_each_image`, `batch_trace_folder_refuses_a_folder_it_cannot_list_in_full`, and `batch_trace_folder_rejects_wrong_typed_options` (engine), `addons::document::tests::batch_trace_folder_asks_for_both_folders` (ui-egui). +## Image Tools add-on: Remove Background (2026-11-11) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Image Tools › Remove Background… (`addon.image.removeBackground`) makes the background of the selected images transparent in their own pixels, in the app with no service or model. The background is the most common edge color (nothing is cleared when the edges hold at least as many clear pixels as pixels of that color), the average of the corners that are not clear, or picked colors. Contiguous (on by default) clears it only where it reaches in from an edge; off, it is cleared everywhere. Tolerance and Softness (0 to 100, 10 by default, VectorCraft's own values) set how near a color is cleared and the band over which pixels fade out, measured as RGB distance or, with Match set to Each Channel, as the largest difference on one channel. The run is one undo step, and none is recorded when no pixel changes. The image stays an image: a PNG with alpha at its own bit depth, gray or color as it was, with its color profile and resolution, and a linked image is embedded. CMYK images, linked images that show their preview, images that would need more than the decode allowance and results with no pixel left are refused. The dialog's Preview works as Release Type on a Path's does; its preview steps decode an image once, and the decoded pixels are released when the dialog closes. Tests: `cmd::addons::image::tests` in `vectorcraft-engine` (edge, corner and picked colors, contiguous on and off, a second run, tolerance and softness by distance and by channel, 16-bit and gray images, the color profile and resolution kept, an image read at another size, linked images, refusals and bad params, and decoded pixels reused across preview steps and released at OK and Cancel), `addons::image::tests::remove_background_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Image Tools add-on. Since 2026-11-12 a selected image also offers Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar, where the reference app offers it (<https://community.adobe.com/announcements-651/ai-powered-image-editing-features-in-illustrator-1624061>); a click runs it at once with the defaults, as one undo step (tests `canvas::tests::the_task_bar_removes_a_selected_images_background` and `addons::image::tests::properties_and_the_control_bar_remove_the_background_at_once`). + ## Color Effects add-on: Find Nearest Swatch (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Color Effects › Find Nearest Swatch… lists each colour of the selection (fills and strokes, as ticked; solid colours and gradient stops, inside groups and type) with the three swatches of the chosen library closest to it by CIEDE2000 difference, with that difference (`addon.color.nearestSwatch`, #4923). The library is the document's swatches, a built-in library, or a library or colour book the user saved or loaded (no colour book data ships with VectorCraft). Apply gives each colour its nearest swatch as one undo step (`addon.color.applyNearestSwatch`): global and spot swatches link, and a library's swatches the colours take are added to the document first, so a spot colour stays spot. Remaining: typing a colour to look up in the dialog (the command takes `color`), and applying a match other than the nearest. Tests: `cmd::addons::color::nearest::tests` (engine), `addons::color::nearest::tests::find_nearest_swatch_lists_the_matches_and_applies_the_nearest` (ui-egui). @@ -1935,7 +2022,7 @@ Edit › Keyboard Shortcuts lists every item of the Effect menu under its menu p A live-effect plug-in installed while the app runs gets its Effect › Plug-ins row in Edit › Keyboard Shortcuts, in `shortcuts.list` and in a Keyboard Shortcuts dialog that is already open, and its key runs it. A removed plug-in's row goes away and its key runs nothing; the shortcut stays saved and applies again when a plug-in with the same id is installed, opening the effect's dialog if the new one has options and applying the effect if it has none. Tests: `shortcuts::tests::a_live_effect_plugin_installed_later_takes_a_shortcut_of_its_own`, `shortcut_editor::tests::an_open_dialog_follows_live_effect_plugins`. -Each installed filter plug-in's Object › Plug-ins item has a row of its own (stored as `plugin:<id>`, since every filter runs `plugin.dialog {id}`), with no default shortcut, also when two filters share a name. The menu shows its shortcut, and pressing it does what a click on the item does: it opens the filter's dialog, or runs a filter without parameters at once as one undo step (a heavy filter starts in the background). A removed filter's row goes away and its key runs nothing; the shortcut stays saved and applies again when a plug-in with the same id is installed. With no document open the key does nothing, as the dimmed item does. The command palette has one result per filter, and Import Shortcut Set offers each filter as a target without matching a row to it by name. Plug-in names stay as the plug-in gives them; the menu path is translated. Tests: `shortcuts::tests::each_filter_plugin_takes_a_shortcut_of_its_own`, `shortcuts::tests::a_filter_plugin_keeps_its_shortcut_when_replaced_or_reloaded`, `shortcuts::tests::a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item`, `shortcuts::tests::a_filter_plugin_row_translates_its_path_and_not_its_name`, `palette::tests::each_filter_plugin_is_a_result_of_its_own`, `dialogs::tests_shortcut_import::an_imported_shortcut_reaches_a_filter_plugin_picked_as_its_target`. +Each installed filter plug-in's Object › Plug-ins item has a row of its own (stored as `plugin:<id>`, since every filter runs `plugin.dialog {id}`), with no default shortcut, also when two filters share a name. The menu shows its shortcut, and pressing it does what a click on the item does: it opens the filter's dialog, or runs a filter without parameters at once as one undo step (a heavy filter, and a light one that lists `progress` and no `commandAllowlist`, starts in the background). A removed filter's row goes away and its key runs nothing; the shortcut stays saved and applies again when a plug-in with the same id is installed. With no document open the key does nothing, as the dimmed item does. The command palette has one result per filter, and Import Shortcut Set offers each filter as a target without matching a row to it by name. Plug-in names stay as the plug-in gives them; the menu path is translated. Tests: `shortcuts::tests::each_filter_plugin_takes_a_shortcut_of_its_own`, `shortcuts::tests::a_filter_plugin_keeps_its_shortcut_when_replaced_or_reloaded`, `shortcuts::tests::a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item`, `shortcuts::tests::a_filter_plugin_row_translates_its_path_and_not_its_name`, `palette::tests::each_filter_plugin_is_a_result_of_its_own`, `dialogs::tests_shortcut_import::an_imported_shortcut_reaches_a_filter_plugin_picked_as_its_target`. ## Live Corners: arrow keys change the corner kind while dragging (2026-11-01) @@ -1971,10 +2058,30 @@ With area type selected, the Properties panel's Paragraph section and the Contro Edit › Copy and Cut put the selected ruler guides on the clipboard, with the selected objects or on their own, so they paste into another artboard or document (#3226). Pasted guides go on the layer new art goes to and are selected; with objects they move as the objects do, and alone they keep their places, while Paste in Place, in Front and in Back put them on the active artboard as they lay on theirs and Paste on All Artboards on every artboard. Guides have no format other apps read, so a Copy of guides alone empties the system clipboard, and the next Paste takes the guides rather than what another app copied before. Tests: `tests::guide_clipboard`, `tests::sysclip_guides` (ui-egui). +- **Live Paint Bucket drag (#6373):** starting on a face, a drag fills every visible face it + crosses in that group, including faces between pointer events. The existing region-crossing + calculation is reused; the gesture is one Undo step and Escape cancels it. Selected paths are + made live by the first press as before. Regression evidence: + `live_paint_bucket_drag_fills_multiple_faces` and + `live_paint_bucket_drag_crosses_thin_grid_cells_and_can_cancel` cover sparse pointer events, + a 0.25 pt grid cell, making selected paths live, deferred drawing, cancellation and Undo; + `live_paint_bucket_drag_rejects_invalid_points_atomically` covers invalid command input. + Behaviour source: [Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html). + Scores and estimates unchanged. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | UI chrome: a numeric-field focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); scores and hours unchanged. | +| 2026-11-03 | minor | File Info on open: an imported document's own title (an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title`) goes into File Info only; the document's name (tab, Save As, default export names) stays the file's name (#3626); scores and estimates unchanged. | +| 2026-11-12 | minor | Type: kerning at the Type tool's caret at the start of a line (the text's, a paragraph's, or after a forced line break) sets the space before the character after it (`kerningBefore`), which moves it and the rest of its line; it did nothing at the text's start and kerned the invisible line break at a paragraph's (#5111). Scores and estimates unchanged. | +| 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | +| 2026-11-11 | minor | Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does (Smart Guides, Snap to Point and the ruler guides, pixels, the grid); evidence updated; scores unchanged. | +| 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | +| 2026-11-11 | minor | Envelopes: with Distort Appearance, type's strokes (characters' and appearance) paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them; paths' strokes, geometry effects, gradients and patterns bend as before; also in an envelope inside an envelope; opacity masks bend as other art; Expand keeps type's strokes as strokes; the visual bounds of envelopes, blends and repeats and the reach of symbol art count type's character strokes as type's own bounds do. Changes how VectorCraft's own envelopes of stroked type draw. Advanced art evidence and `.ai` import evidence updated (#6644); scores and estimates unchanged. | +| 2026-11-11 | minor | Bundled content: built-in Energy Beams brush library (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); brush libraries evidence updated; ~44% → ~46%; more built-in brush libraries remain. | +| 2026-11-11 | minor | Bundled content: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); symbol libraries evidence updated; ~42% → ~44%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Automation: MCP tool count 33; headless `command_list` lists `UI_COMMANDS` (`ui: true`); eight prompts; effect-id vs command-id clarified (#6460); scores and hours unchanged. | | 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | @@ -2150,6 +2257,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-22 | minor | G2: Effect › Sketch › Conté Crayon (Foreground Level, Background Level, Texture, Scaling, Relief, Light Direction, Invert; a black crayon in the dark areas and a white one in the light areas on textured mid-grey paper; ranges and defaults unverified VectorCraft choices); measured Photoshop-style filters 57/57, the Effect Gallery remains (4–6 h); area score unchanged (49%, estimated). | | 2026-10-22 | minor | File formats: Affinity import gains master pages, tables, paragraph formats, text scale, shadows, glows, outlines (also on stroked shapes), overlays, underlines, strikethrough and editable embedded documents, strokes styled None left out, CMYK pixel layers through the document's CMYK profile, text placed as Affinity places it (AF.5, from storytold/designcraft#291); synthetic, corpus and local-thumbnail tests; score and hours unchanged (estimated). Hostile files stay bounded: one budget for the whole read (layers, pixels, characters, table cells, embedded documents included), a work budget for overlays, capped master page copies, objects past `MAX_COORD` left out; the import fuzzer and limit tests cover tables, paragraphs, effects, overlays, master pages, CMYK pixels and embedded documents. | | 2026-10-22 | minor | Recolor Artwork Edit chips scroll within the available screen height (#3416); small palettes retain their tab height; scores and estimates unchanged. | +| 2026-10-21 | minor | Width-profile outlines offset samples added inside a flattened chord along the source curve's exact tangent, so a zoomed outline no longer jogs at flatten vertices; a regression test covers added samples. Scores and estimates unchanged. | | 2026-10-22 | minor | Font pickers list recently applied families first (#3515), using the existing recent-font limit; search, filters, previews and keyboard selection share the same rows. Scores and estimates unchanged. | | 2026-10-21 | minor | Plug-ins: filters keep data with the document (`documentData`), as its foreign data, so the native file needs no section of its own (G17); engine and unit regressions. Scores and hours unchanged. | | 2026-10-21 | minor | Print: PDF/X-1a and PDF/X-3 flattening in a CMYK document rasterizes as ink amounts, so CMYK colours under an image with see-through pixels keep their numbers, K included, instead of going through RGB (#2160); own-fixture test; scores and hours unchanged (estimated) | @@ -2166,6 +2274,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-21 | minor | Snap to Glyph (#3124) removed from View navigation missing lists and menu stubs; scores and hours unchanged at this rounding | | 2026-10-21 | minor | Type core: System Layout (Character panel menu, whole document, off by default) is done; scores and hours unchanged | | 2026-10-22 | minor | Ruby (ふりがな) for live text: `type.ruby` sets/removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); scores and hours unchanged | +| 2026-10-23 | minor | Width-profile outlines sample adaptively: two samples per profile segment, refined where the width bends, and only where the flattened path does not already sample the width. The sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt by default) instead of one cubic per flatten step. On the reviewer's 1,500-ellipse fixture (20–200 pt ellipses, 3–12 pt weights) the PDF falls to 3.59 MB and the SVG to 6.79 MB (reported main baselines 4.48 MB and 9.30 MB, about 0.80× and 0.73×), and `profiled_outlines_stay_compact` guards the path-element count. Scores and estimates unchanged. | | 2026-10-21 | minor | 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged | | 2026-10-21 | minor | Properties: one selected clip group has Edit Clipping Path and Edit Contents at the top of the panel (public doc cited) (G1). Scores and hours unchanged. | | 2026-10-21 | minor | Print: the Print dialog's Media list carries the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5, which keep their ISO 216 sizes, plus はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; the JSON id or the dialog label names a paper, any case and spacing. Print score and hours unchanged. | @@ -2179,6 +2288,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-19 | minor | Plug-ins: parameters with labels, units, help, groups and conditions in their dialogs, `string` and `numberList` types, up to 256 per plug-in (G17); manifest and kittest dialog regressions. Scores and hours unchanged. | | 2026-10-19 | minor | Plug-ins: exporter plug-ins add write-only file formats to Export As and `document.export` (G17); engine, ABI and headless Export As regressions. Scores and hours unchanged. | | 2026-10-19 | minor | Libraries panel: the list fills the panel and scrolls (also while a drag nears its edges); items drag before or after others of their kind and into or out of groups, and groups drag by their headers (`library.moveItem` `before`/`after`, `library.moveGroup`). Scores and estimates unchanged. | +| 2026-10-19 | minor | Width profiles run as a smooth C1 curve between their points (a monotone cubic Hermite, Fritsch-Carlson) instead of straight lines, sampled along the path so the outline follows it on straight runs; steps between coincident points still step. Regression tests cover easing, monotonicity, locality and steps. Scores and estimates unchanged. | | 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | | 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | | 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. | @@ -2359,4 +2469,4 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s 2026-10-28 Flare interaction: the center drag turns only the rays by one degree per document point of increasing pointer y and back at the same rate for decreasing y. This is an application rule independent of event frequency. Shift keeps the current turn; Space during either drag moves the flare without changing its size or turn, including the first drag sample. Releasing a modifier resumes from the current pointer position without catching up skipped rotation. Scores and remaining estimates unchanged. ## EPS Save evidence (2026-10-26) -Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. \ No newline at end of file +Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. \ No newline at end of file diff --git a/docs/three-d.md b/docs/three-d.md index 635c1285e3..a79e6a4900 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -51,8 +51,9 @@ pages describe it. unavailable while a setting of a single light differs between the selected effects. - Each change is one undo step. Dragging a value or a slider previews it on the artboard and records one step when the pointer is released; a typed value is recorded when it is entered. Drawing the panel records nothing. -- The Materials tab, shadows and ray-traced rendering are not built (see below). The rotation and light rings on - the artboard are part of the options dialog only. +- The Lighting tab also holds the Shadows switch and its settings ([Shadows](#shadows)). The Materials tab and + ray-traced rendering are not built (see below). The rotation and light rings on the artboard are part of the + options dialog only. ## Extrude & Bevel @@ -99,7 +100,12 @@ reply on the reference app's bug forum says that strokes "will be treated as out The rest is our reading: - When the fill and every stroke are opaque with Normal blending, the faces of all the solids are drawn in one - back-to-front order, and the caps turned toward the viewer are drawn last, the lower item's first. Otherwise + back-to-front order, and the caps turned toward the viewer are drawn last, the lower item's first. With caps on, + each side face of the fill's solid that is turned toward the viewer is drawn before every face of the same + shape's strokes, turned toward the viewer, whose bounds overlap it, so the stroke's walls cover the fill's walls + at concave corners. This applies to strokes on closed paths without dashes, a width profile or a brush, painted + with a solid color or a gradient without transparent stops; with other strokes, and without caps, the faces keep + their depth order. Otherwise each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not white, each solid is also drawn on its own when one of them is a puffed, shaded Inflate surface in a solid color (drawn as one composite) or is painted with a gradient that has transparent stops (drawn with an opacity mask). @@ -135,7 +141,7 @@ them all. The members stay editable: moving or editing one reshapes the solids. ## Clipping groups, blends and symbol instances -Every 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Inflate, Rotate and Revolve) also applies to a clipping +Every 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Inflate, Rotate, Rotate (Classic), Revolve and Revolve (Classic)) also applies to a clipping group, a blend or a symbol instance, alone or inside a group or layer. The help page says that effects apply to objects, groups or layers ([Apply and modify effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)), that a clipping mask hides everything outside its shape ([Clipping masks](https://helpx.adobe.com/illustrator/using/clipping-masks.html)), @@ -242,6 +248,39 @@ the default light had (45° left of the eye and 45° up). Effects saved before ( `lightAzimuth` and `lightElevation`; those are read as the Rotation, Height and side of the same direction, so the shading is exactly as before. +## Shadows + +The public [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) +page lists shadow settings that apply while shadows are on: a Position behind or below the object, a Distance +from Object from 0 to 100 % and Shadow Bounds from 10 to 400 %. The Lighting tab of Revolve, Extrude & Bevel, +Inflate and Rotate has a **Shadows** switch with those three settings below it. + +| Option | | +|---|---| +| Shadows | Off by default. On, the first light casts a hard-edged shadow of the solid, drawn behind it. | +| Position | **Behind Object** (the default): on a plane square to the view, behind the object. **Below Object**: on the floor under the object, square to its own vertical axis and turned with it. | +| Distance from Object | 0–100 %, default 0 %: how far the plane is from the object, as a share of the object's largest size. | +| Shadow Bounds | 10–400 %, default 100 %: how far the plane reaches. At 100 % it is a square four times the object's largest size across, about the foot of the object's center; the shadow is cut at its edges. | + +Our reading: + +- The shadow is one path, filled black at 50 % opacity with the nonzero rule: every face of every solid of the + object (its fill and its strokes, or the members of a group) projected along the first light onto the plane. + Art that is partly transparent casts its part at 50 % times its opacity, and art with a blending mode casts + its part in that mode, each as a path of its own. A member whose + opacity mask or blending mode applies to its solids casts its part in that mask and mode too. The color, the + opacity and how Distance and Bounds scale are our own. +- No shadow is drawn while Shading is off (the Shadows settings are then unavailable), when the first light's + Intensity is 0 %, or when it does not reach the plane: a light behind the object casts none behind it, and a + light from under the floor casts none below it. A fill, stroke or group member at 0 % opacity casts none. With no X rotation the floor is seen edge-on, so a + shadow below draws nothing until the object is tilted (the default Off-Axis Front position shows it). +- Softness is not applied to the shadow, and only the first light casts one. +- A shadow is cast from at most 327,680 faces, the solids of one object together (our own limit). Past it, a + command is refused with "The 3D shadow is too complex; turn Shadows off or simplify the art", and a loaded + file draws the source path. +- Canvas, SVG and PDF exports draw the shadow, the art's bounds take it in, and Expand Appearance keeps it as a + path below the faces. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. + ## Parameters (`effect.apply`, `effect.setParams`) `threeD.extrude`: `depth`, `twist`, `taper` (%), `cap`, `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, @@ -249,7 +288,7 @@ shading is exactly as before. `threeD.inflate`: `depth`, `volume` (%), `bothSides`. All three take the view and lighting parameters Revolve uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shade`, `lightColor` (`#rrggbb`, default `#ffffff`), `lightIntensity` (%), `lightRotation`, `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). -Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. +Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. All four take `shadow` (boolean, false), `shadowPosition` (`behind` or `below`), `shadowDistance` (0..100%, 0) and `shadowBounds` (10..400%, 100) ([Shadows](#shadows)); values out of range are rejected before editing. ## What differs from the public documentation @@ -258,9 +297,10 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base, Adobe Substance and graphics), **shadows** +- **Materials** (base, Adobe Substance and graphics), soft shadows, shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or - stroke the solid is built for ([Fills and strokes](#fills-and-strokes)). + stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and the shadow is hard-edged + ([Shadows](#shadows)). - The bevel shapes and their names are our own; custom bevel paths are not supported. - Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids @@ -296,8 +336,11 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. outline crosses. An outline of tens of thousands of points that crosses nearly every cell (a comb of 4,000 teeth across the shape) is refused because the 3D surface is too complex; a closed path of 65,536 points round a circle builds. -- **3D (Classic)**: Extrude & Bevel (Classic) is built, with its surface types and blend steps. Revolve (Classic), - Rotate (Classic), the track cube, map art, Turntable and 3D export are separate, unbuilt items. +- **3D (Classic)**: Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) are built, with their surface + types and blend steps. Revolve (Classic) sweeps the surface Revolve sweeps, at 64 segments for a full turn, and draws + every face back to front, so it has no Draw Hidden Faces setting. Rotate (Classic) turns the plane Rotate turns, seen + from either side, with the No Shading and Diffuse surfaces only. The track cube, map art, Turntable and 3D export + are separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). diff --git a/docs/type-parity.md b/docs/type-parity.md index 4013f8be19..30547d5a17 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -25,7 +25,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | | Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | -| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); Direct Selection shows the anchors and direction handles of selected type on a path's path and drags both, the brackets keeping their fractions of the path and the text reflowing along it (#3980, #3565; `text.reshapePath`, `text.setPathHandle`), as the [Direct Selection page](https://helpx.adobe.com/illustrator/using/tool-techniques/direct-selection-tool.html) describes for a path | +| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); Direct Selection shows the anchors and direction handles of selected type on a path's path and drags both, the brackets keeping their fractions of the path and the text reflowing along it (#3980, #3565; `text.reshapePath`, `text.setPathHandle`), as the [Direct Selection page](https://helpx.adobe.com/illustrator/using/tool-techniques/direct-selection-tool.html) describes for a path; Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar) sizes type on a path to fill the span between its brackets and fits it again after each edit, as the [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) describes; the 0.1 pt steps, the 0.1 to 1,296 pt range and keeping the drawn sizes when it is turned off or threaded are VectorCraft's own rules (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`) | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing. Double-clicking a user character style's row opens its Character Style Options, and the dialog keeps a fixed width while its sections scroll when the window is shorter, so its buttons stay on screen; a paragraph style's row opens its Paragraph Style Options, the rename dialog the panel menu opens. Evidence: `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list` | | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | @@ -81,6 +81,9 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Kerning at the start of a line (#5111): at the Type tool's caret before the first character of the text, of a paragraph or after a forced line break, the Kerning field, Alt+arrows and Reset Tracking and Kerning set the space before the character after the caret (`CharStyle::kerning_before`, `kerningBefore` in `text.setRangeStyle`), which moves it and the rest of its line, in horizontal, right-to-left and vertical type and in SVG export. They did nothing at the text's start and kerned the invisible line break at a paragraph's. Scores and estimates unchanged. | +| 2026-11-11 | minor | Type in envelopes: its strokes (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them; with Distort Appearance they bent with the art as their filled outlines. The same holds in an envelope inside an envelope. Geometry effects on type's fills and strokes, and an opacity mask on type, still bend; Expand gives the bent outlines with the strokes on them. The visual bounds of envelopes, blends and repeats count type's character strokes as type's own visual bounds do. This changes how VectorCraft's own envelopes of stroked type draw (#6644). Score unchanged (estimated) | +| 2026-11-11 | minor | Aligned lines of tracked type: a centred or right-aligned line is as wide as its characters without the tracking after its last one (`LineInfo::trailing`), so a centred line sits half that tracking right of where it did and a right-aligned line's last glyph ends on its anchor or frame edge, the tracking after it reaching past. The page of users' `.ai` files (used locally, never committed) aligns tracked lines so: matched glyph by glyph with the page, 176 centred lines of point type in 51 files sat half their last character's tracking left of it (median 0.500 of it; 143 within 0.05 pt), 58 right-aligned lines in 5 files the whole tracking (median 1.001), and 182 left-aligned lines where the page has them; in a line whose last character is tracked 150 and the others −34, the offset is half the last character's tracking (0.498 of it). All those lines end a paragraph. The last character is the last the line draws before a paragraph's end, a forced line break or the spaces a wrap leaves (they hang past the line). Spaces or a tab typed before a paragraph's end or a forced line break are the line's last characters, and the letter before them keeps its tracking: in the 2 such lines in the files, the page counts the space and the letter's tracking and leaves out only the space's own (VectorCraft still leaves trailing spaces out of the width). Forced line breaks and wrapped lines of tracked type aren't in the files: they take the rule unverified, so that Convert To Point Type and Artwork Cleanup's Break Text, which turn wraps into paragraphs and forced line breaks, keep the lines where they were. A hyphenated line, one whose last character hangs, justified, vertical and right-to-left lines and type on a path keep the tracking, and so do right, centre and decimal tab stops, which still align the text after them with its last character's tracking. Manual kerning on the last character, line breaking and justification are unchanged (none in the files). The tracking stays in the last glyph's advance (the caret after it and a selection of it take it in), and Fit Headline still counts it, as line breaking does. Right-aligned area type sets the text after its last tab the same way. Convert To Area Type makes the frame end where the lines are aligned, with room for that tracking, so tracked type converted either way stays where it is (it moved by the tracking on each round trip). Affinity import aligns artistic text by the same rule, so centred or right-aligned tracked artistic text moves by half or all of its last character's tracking (unverified against Affinity). Centred and right-aligned tracked type lays out differently than before in every document. Tests `tests::an_aligned_line_leaves_its_last_characters_tracking_out_of_its_width`, `tests::which_lines_leave_the_tracking_after_their_last_character_out`, `tests::an_aligned_line_leaves_out_its_last_tracking_as_glyph_scaling_sets_it`, `tests::the_text_after_the_last_tab_of_right_aligned_type_leaves_its_last_tracking_out`, and the engine's `converting_tracked_type_between_point_and_area_keeps_it_in_place` and `break_tracked_area_type_keeps_its_aligned_lines_in_place`. Scores and estimates unchanged. (#6610) | | 2026-11-11 | minor | Tracking and manual kerning in horizontally scaled type: they are thousandths of the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), so at 50% a tracking of 100 adds 0.05 em after each character, half as much as at 100%. They were added at the full em whatever the scale, so narrow tracked type drifted further right with each letter. Illustrator's own layout in users' `.ai` files (used locally, not committed) spaces such type so, and PDF scales its character spacing by its horizontal scaling alike (ISO 32000-1 §9.4.4). Inline graphics take it after them too; vertical type keeps the full em, its advances down the column not all taking the Horizontal Scale. The automatic kerning the Character panel reads, Touch Type's limits and Artwork Cleanup's Combine Point Text measure in the same em, and Scale Text Attributes now keeps tracked type where a horizontal stretch of its transform drew it. Type that has both a Horizontal Scale other than 100% and tracking or manual kerning lays out differently than before in every document. Tests `tests::tracking_and_manual_kerning_take_the_horizontal_scale`, `tests::typo::optical_pairs_in_horizontally_scaled_type_measure_without_the_scaled_tracking`, `tests::inline::shift_tracking_and_missing_symbols`, `tests::vertical::vertical_tracking_keeps_the_em_at_any_horizontal_scale` and the engine's `horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it`, `scale_text_attributes_keeps_tracked_type_where_it_was` and `combine_puts_horizontally_scaled_pieces_back_where_they_were`. Scores and estimates unchanged. | | 2026-11-10 | minor | Edit Custom Dictionary (#4936): Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, applied on Done; the Check Spelling dialog remains. Scores and estimates unchanged. | | 2026-11-10 | minor | Type on a path (#3565): Direct Selection shows the direction handles of selected type on a path's path, as of a path selected whole, and drags them (`text.setPathHandle`; Alt: one side, Shift: 45° steps); the text reflows along the new curve. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 964ebdb039..cf6f23fb5d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -240,7 +240,7 @@ tools, never checked side by side) isn't captured row by row. | Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | | A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | -| Ruler origin: corner drag with preview, double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | +| Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer | done | `guide.setLayer`; guides from older files go on a layer | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete); a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701 | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | @@ -271,6 +271,7 @@ tools, never checked side by side) isn't captured row by row. | Split Into Grid dialog: number, height or width, gutter and total for rows and columns, Add Guides, Preview | done | #1462; opens at the selection's size; several paths become one grid painted as the topmost one; a typed height or width keeps the gutter and changes the total (our choice) | | Reference point locator (nine squares) in Control bar and Transform panel | done | | | Transform panel menu: Transform Object Only, Transform Pattern Only, Transform Both (one checked), Use Registration Point for Symbol | done | `transformPanelPatterns` (`object`, `pattern`, `both`) sends `objects` and `patterns` with every field, flip and menu flip of the Transform panel and the Properties panel's Transform section; `useRegistrationPointForSymbol` makes them measure and transform one selected symbol instance from its symbol's registration point (Symbol Options › Registration), where the instance's flips, rotations and shears put it, instead of the reference point; the Properties panel's rotation and flips turn and mirror about it too ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html)); until a choice is made (`default`) the panels follow General › Transform Pattern Tiles as before, the menu checking Transform Both while it is on and Transform Object Only while it is off | +| Transform panel menu and New Document › Advanced Options: Align New Objects to Pixel Grid | done | `document.setup {alignNewObjectsToPixelGrid}` and `file.new {alignNewObjectsToPixelGrid}`: paths and compound paths drawn while it is on are pixel-aligned; on in the Mobile and Web presets; art already in the document, pasted, duplicated or placed keeps its own property (our choice) | | Transform panel, Properties and Control bar X/Y/W/H of the anchor points selected with Direct Selection | done | #1839 (fixes #1824): they show and edit the selected points' bounds; a whole-object selection is unchanged | ## Nudging, numeric entry and precision @@ -302,6 +303,7 @@ tools, never checked side by side) isn't captured row by row. | Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | | Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | | Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); engine pointer and canvas regressions | +| Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | | Eyedropper reads visible sources while their layer/object is locked or outside isolation | done | Ordinary/Shift/Shift+Alt and gradient-stop reads preserve the source and selection; Alt reverse remains editable-only; hidden art stays excluded (`eyedropper_sources.rs`, #1251) | | Add a visible stroke after drawing with inherited None/zero-width paint | done | Paint and Swap Fill/Stroke restore the existing 1 pt default; positive widths and painted zero widths stay as set; Undo/Redo and targeted appearance items tested (`stroke_visibility.rs`, #1253) | @@ -371,6 +373,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po |---|---|---| | Effect > Warp Options: style previews, orientation choices and percent controls | done | #1760; focused input, mixed-style and history checks passed; original captures reviewed. No geometry or optional Properties changes. | | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | +| Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with tutorial counts and empty progress rings, a tutorial shows its numbered steps, Back goes up a level | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.show`; `panels::learn::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | @@ -410,7 +413,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | | Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | -| Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; four built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons; original, generated in code) | +| Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; four built-in libraries (original, generated in code) | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -434,7 +437,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Window › Help Bar shows or hides the tool-help strip apart from the status bar; kept with the preferences and in saved workspaces; Presentation Mode hides both bars | done | `window.helpBar`; `help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar` | | Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library:<kind>:<id>`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | -| DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; native CIRCLE/ARC export and CNC preset remain pending | +| DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); arcs, spirals, flares and Pen paths are not turned | @@ -507,11 +510,21 @@ rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/ coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). +## Live Paint Bucket + +Dragging from a face fills the visible faces crossed in that Live Paint group, even when a +narrow face lies between pointer events. Undo restores the whole drag, and Escape cancels it +before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html). + ## Revision history | Date | Change | Summary | |---|---|---| | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | +| 2026-11-12 | minor | Remove Background for a selected image in the Contextual Task Bar, Properties › Quick Actions and the Control bar, which runs at once with its defaults. Scores and estimates unchanged. | +| 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | +| 2026-11-11 | minor | Ruler origin: the corner drag snaps as a drawn point does, onto the art's and the artboards' anchors, centres, edges and paths, and with Snap to Point along the ruler guides; scores and estimates unchanged | +| 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | | 2026-11-11 | minor | Outline view: a click on a path's outline selects it through an image or a gradient mesh in front, which Outline draws as a frame or mesh lines (#6437). | | 2026-11-11 | minor | A middle-click on a document tab (or its ×) closes it as the × does; closing a document's last view with unsaved changes asks to save first (#6506). VectorCraft addition; scores and estimates unchanged. | | 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | diff --git a/packaging/linux/flatpak/ai.storyteller.vectorcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.vectorcraft.bundle.yml index 840abbc53f..b3b4ad1945 100644 --- a/packaging/linux/flatpak/ai.storyteller.vectorcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.vectorcraft.bundle.yml @@ -17,6 +17,8 @@ runtime-version: '25.08' sdk: org.freedesktop.Sdk command: vectorcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # X11 shared memory (MIT-SHM). Without it the X11 fallback is slow or fails. - --share=ipc diff --git a/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml b/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml index 6817637936..7d14dbe019 100644 --- a/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml @@ -17,6 +17,8 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: vectorcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Keep identical to ai.storyteller.vectorcraft.bundle.yml (the release bundle); comments there. - --share=ipc